feat: Add pending tasks and active status to WikiStats
- Introduced `pending_tasks` and `is_active` fields in the `WikiStats` interface to track the number of tasks waiting for processing and the current activity status of the wiki ingestion. - Updated localization files for English, Korean, Russian, and Chinese to include a new message for displaying the number of pending tasks in the wiki queue. - Enhanced the `WikiBrowser` component to display the queue status, improving user awareness of ongoing tasks. - Implemented polling logic to refresh wiki stats periodically when there are pending tasks or active ingestion, ensuring up-to-date information is presented. These changes enhance the functionality and user experience of the wiki management system by providing real-time insights into task status.
This commit is contained in:
@@ -40,6 +40,8 @@ export interface WikiStats {
|
|||||||
total_links: number;
|
total_links: number;
|
||||||
orphan_count: number;
|
orphan_count: number;
|
||||||
recent_updates: WikiPage[];
|
recent_updates: WikiPage[];
|
||||||
|
pending_tasks: number;
|
||||||
|
is_active: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wiki API Functions
|
// Wiki API Functions
|
||||||
|
|||||||
@@ -1636,6 +1636,7 @@ export default {
|
|||||||
showArrows: 'Show arrows',
|
showArrows: 'Show arrows',
|
||||||
hideArrows: 'Hide arrows',
|
hideArrows: 'Hide arrows',
|
||||||
healthCheck: 'Health Check',
|
healthCheck: 'Health Check',
|
||||||
|
queueStatus: '{count} pending tasks in Wiki queue',
|
||||||
},
|
},
|
||||||
buttons: {
|
buttons: {
|
||||||
create: 'Create Knowledge Base',
|
create: 'Create Knowledge Base',
|
||||||
|
|||||||
@@ -2159,6 +2159,7 @@ export default {
|
|||||||
showArrows: '화살표 표시',
|
showArrows: '화살표 표시',
|
||||||
hideArrows: '화살표 숨기기',
|
hideArrows: '화살표 숨기기',
|
||||||
healthCheck: "상태 점검",
|
healthCheck: "상태 점검",
|
||||||
|
queueStatus: "Wiki 대기열에 {count}개의 보류 중인 작업",
|
||||||
},
|
},
|
||||||
buttons: {
|
buttons: {
|
||||||
create: "지식베이스 생성",
|
create: "지식베이스 생성",
|
||||||
|
|||||||
@@ -1838,6 +1838,7 @@ export default {
|
|||||||
showArrows: 'Показать стрелки',
|
showArrows: 'Показать стрелки',
|
||||||
hideArrows: 'Скрыть стрелки',
|
hideArrows: 'Скрыть стрелки',
|
||||||
healthCheck: 'Проверка здоровья',
|
healthCheck: 'Проверка здоровья',
|
||||||
|
queueStatus: '{count} ожидающих задач в очереди Wiki',
|
||||||
},
|
},
|
||||||
buttons: {
|
buttons: {
|
||||||
create: 'Создать базу знаний',
|
create: 'Создать базу знаний',
|
||||||
|
|||||||
@@ -2144,6 +2144,7 @@ export default {
|
|||||||
showArrows: '显示箭头',
|
showArrows: '显示箭头',
|
||||||
hideArrows: '隐藏箭头',
|
hideArrows: '隐藏箭头',
|
||||||
healthCheck: "健康检查",
|
healthCheck: "健康检查",
|
||||||
|
queueStatus: "Wiki 队列中 {count} 个待处理任务",
|
||||||
},
|
},
|
||||||
buttons: {
|
buttons: {
|
||||||
create: "创建知识库",
|
create: "创建知识库",
|
||||||
|
|||||||
@@ -91,6 +91,10 @@
|
|||||||
<!-- Left Panel: Page List -->
|
<!-- Left Panel: Page List -->
|
||||||
<aside class="wiki-sidebar">
|
<aside class="wiki-sidebar">
|
||||||
<div class="wiki-sidebar-header">
|
<div class="wiki-sidebar-header">
|
||||||
|
<div v-if="stats && (stats.pending_tasks > 0 || stats.is_active)" class="wiki-queue-status">
|
||||||
|
<t-loading size="small" />
|
||||||
|
<span class="queue-text">{{ $t('knowledgeEditor.wikiBrowser.queueStatus', { count: stats.pending_tasks || 0 }) }}</span>
|
||||||
|
</div>
|
||||||
<t-input
|
<t-input
|
||||||
v-model="searchQuery"
|
v-model="searchQuery"
|
||||||
:placeholder="$t('knowledgeEditor.wikiBrowser.searchPlaceholder')"
|
:placeholder="$t('knowledgeEditor.wikiBrowser.searchPlaceholder')"
|
||||||
@@ -255,7 +259,7 @@
|
|||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { ref, computed, onMounted, watch, nextTick, reactive } from 'vue'
|
import { ref, computed, onMounted, onUnmounted, watch, nextTick, reactive } from 'vue'
|
||||||
import { useI18n } from 'vue-i18n'
|
import { useI18n } from 'vue-i18n'
|
||||||
import { marked } from 'marked'
|
import { marked } from 'marked'
|
||||||
import { hydrateProtectedFileImages } from '@/utils/security'
|
import { hydrateProtectedFileImages } from '@/utils/security'
|
||||||
@@ -477,10 +481,26 @@ async function loadPages() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let statsTimer: ReturnType<typeof setInterval> | null = null
|
||||||
|
|
||||||
async function loadStats() {
|
async function loadStats() {
|
||||||
try {
|
try {
|
||||||
const res = await getWikiStats(props.knowledgeBaseId)
|
const res = await getWikiStats(props.knowledgeBaseId)
|
||||||
stats.value = (res as any).data || res as any
|
stats.value = (res as any).data || res as any
|
||||||
|
|
||||||
|
// Poll if there are pending tasks or wiki ingest is active
|
||||||
|
if (stats.value && (stats.value.pending_tasks > 0 || stats.value.is_active)) {
|
||||||
|
if (!statsTimer) {
|
||||||
|
statsTimer = setInterval(() => {
|
||||||
|
loadStats()
|
||||||
|
}, 5000)
|
||||||
|
}
|
||||||
|
} else if (statsTimer) {
|
||||||
|
// If completed, clear timer and reload pages once to get new content
|
||||||
|
clearInterval(statsTimer)
|
||||||
|
statsTimer = null
|
||||||
|
loadPages()
|
||||||
|
}
|
||||||
} catch (e) { /* ignore */ }
|
} catch (e) { /* ignore */ }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1300,6 +1320,12 @@ onMounted(() => {
|
|||||||
loadStats()
|
loadStats()
|
||||||
if (props.view === 'graph') loadGraph()
|
if (props.view === 'graph') loadGraph()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
if (statsTimer) {
|
||||||
|
clearInterval(statsTimer)
|
||||||
|
}
|
||||||
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<style scoped lang="less">
|
<style scoped lang="less">
|
||||||
@@ -1323,6 +1349,24 @@ onMounted(() => {
|
|||||||
|
|
||||||
.wiki-sidebar-header {
|
.wiki-sidebar-header {
|
||||||
padding: 16px 16px 12px;
|
padding: 16px 16px 12px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wiki-queue-status {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 8px 12px;
|
||||||
|
background: var(--td-bg-color-secondarycontainer);
|
||||||
|
border-radius: 6px;
|
||||||
|
color: var(--td-text-color-secondary);
|
||||||
|
font-size: 13px;
|
||||||
|
|
||||||
|
.queue-text {
|
||||||
|
line-height: 1.2;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.wiki-page-list {
|
.wiki-page-list {
|
||||||
|
|||||||
@@ -85,6 +85,9 @@ Only include concepts that are substantively discussed. Skip trivial or overly g
|
|||||||
- If something is a specific named thing (person, company, product, place), put it ONLY in "entities".
|
- If something is a specific named thing (person, company, product, place), put it ONLY in "entities".
|
||||||
- If something is an abstract idea, methodology, or theory, put it ONLY in "concepts".
|
- If something is an abstract idea, methodology, or theory, put it ONLY in "concepts".
|
||||||
- Never duplicate items across the two arrays.
|
- Never duplicate items across the two arrays.
|
||||||
|
|
||||||
|
### JSON Formatting Rules
|
||||||
|
- **CRITICAL**: Do NOT use literal newline characters inside JSON string values. If you need a newline in a string, you MUST use the escaped sequence \n.
|
||||||
</instructions>
|
</instructions>
|
||||||
|
|
||||||
Output ONLY valid JSON. Example:
|
Output ONLY valid JSON. Example:
|
||||||
@@ -139,6 +142,8 @@ const WikiPageUpdatePrompt = `You are a wiki editor tasked with updating an exis
|
|||||||
Output the SUMMARY line first, then the updated Markdown content. Do not include any other preamble.`
|
Output the SUMMARY line first, then the updated Markdown content. Do not include any other preamble.`
|
||||||
|
|
||||||
// WikiPageRetractPrompt removes information contributed by a deleted document from an existing wiki page.
|
// WikiPageRetractPrompt removes information contributed by a deleted document from an existing wiki page.
|
||||||
|
// It includes the actual content of remaining source documents (from their summary pages) so the LLM
|
||||||
|
// can accurately determine which facts are still supported and which should be removed.
|
||||||
const WikiPageRetractPrompt = `You are a wiki editor. A source document has been DELETED from the knowledge base. You must update the existing wiki page to remove any information that came exclusively from this deleted document.
|
const WikiPageRetractPrompt = `You are a wiki editor. A source document has been DELETED from the knowledge base. You must update the existing wiki page to remove any information that came exclusively from this deleted document.
|
||||||
|
|
||||||
<existing_page_content>
|
<existing_page_content>
|
||||||
@@ -152,9 +157,9 @@ const WikiPageRetractPrompt = `You are a wiki editor. A source document has been
|
|||||||
</content>
|
</content>
|
||||||
</deleted_document>
|
</deleted_document>
|
||||||
|
|
||||||
<remaining_sources>
|
<remaining_source_documents>
|
||||||
{{.RemainingSources}}
|
{{.RemainingSourcesContent}}
|
||||||
</remaining_sources>
|
</remaining_source_documents>
|
||||||
|
|
||||||
<valid_wiki_links>
|
<valid_wiki_links>
|
||||||
{{.AvailableSlugs}}
|
{{.AvailableSlugs}}
|
||||||
@@ -162,9 +167,9 @@ const WikiPageRetractPrompt = `You are a wiki editor. A source document has been
|
|||||||
|
|
||||||
<instructions>
|
<instructions>
|
||||||
1. The FIRST line of your output MUST be: SUMMARY: {one sentence, 15-40 words, describing what this page is about after retraction — for wiki index listing}
|
1. The FIRST line of your output MUST be: SUMMARY: {one sentence, 15-40 words, describing what this page is about after retraction — for wiki index listing}
|
||||||
2. Carefully review the existing page content and compare it with the deleted document content above.
|
2. Carefully review the existing page content. Compare it against BOTH the deleted document and the remaining source documents above.
|
||||||
3. Remove any facts, claims, or details that were ONLY sourced from the deleted document.
|
3. Remove any facts, claims, or details that were ONLY sourced from the deleted document and are NOT present in any remaining source document.
|
||||||
4. If a fact is also supported by the remaining source documents, KEEP it.
|
4. If a fact appears in both the deleted document and a remaining source, KEEP it.
|
||||||
5. If you are unsure whether a fact came from the deleted document, keep it as-is — do NOT add any review notes or annotations.
|
5. If you are unsure whether a fact came from the deleted document, keep it as-is — do NOT add any review notes or annotations.
|
||||||
6. Update or remove the "Source: {{.DeletedDocTitle}}" reference line if present.
|
6. Update or remove the "Source: {{.DeletedDocTitle}}" reference line if present.
|
||||||
7. Keep [[slug|name]] wiki-link references ONLY if the slug appears in the <valid_wiki_links> list above. Remove any [[slug|name]] whose slug is NOT in that list.
|
7. Keep [[slug|name]] wiki-link references ONLY if the slug appears in the <valid_wiki_links> list above. Remove any [[slug|name]] whose slug is NOT in that list.
|
||||||
@@ -284,6 +289,9 @@ For each newly extracted item, check if it refers to the same real-world entity
|
|||||||
Return a JSON object with a "merges" map. The key is the NEW item's slug, the value is the EXISTING page's slug that it should merge into. Only include items that have a match.
|
Return a JSON object with a "merges" map. The key is the NEW item's slug, the value is the EXISTING page's slug that it should merge into. Only include items that have a match.
|
||||||
|
|
||||||
If no items match any existing pages, return: {"merges": {}}
|
If no items match any existing pages, return: {"merges": {}}
|
||||||
|
|
||||||
|
### JSON Formatting Rules
|
||||||
|
- **CRITICAL**: Do NOT use literal newline characters inside JSON string values. If you need a newline in a string, you MUST use the escaped sequence \n.
|
||||||
</instructions>
|
</instructions>
|
||||||
|
|
||||||
Output ONLY valid JSON. Example:
|
Output ONLY valid JSON. Example:
|
||||||
|
|||||||
@@ -154,9 +154,6 @@ func (r *wikiPageRepository) List(ctx context.Context, req *types.WikiPageListRe
|
|||||||
if pageSize < 1 {
|
if pageSize < 1 {
|
||||||
pageSize = 20
|
pageSize = 20
|
||||||
}
|
}
|
||||||
if pageSize > 100 {
|
|
||||||
pageSize = 100
|
|
||||||
}
|
|
||||||
offset := (page - 1) * pageSize
|
offset := (page - 1) * pageSize
|
||||||
query = query.Offset(offset).Limit(pageSize)
|
query = query.Offset(offset).Limit(pageSize)
|
||||||
|
|
||||||
|
|||||||
@@ -1331,7 +1331,7 @@ func (s *knowledgeService) cleanupWikiOnKnowledgeDelete(ctx context.Context, kbI
|
|||||||
if len(retractSlugs) > 0 {
|
if len(retractSlugs) > 0 {
|
||||||
lang, _ := types.LanguageFromContext(ctx)
|
lang, _ := types.LanguageFromContext(ctx)
|
||||||
tenantID, _ := types.TenantIDFromContext(ctx)
|
tenantID, _ := types.TenantIDFromContext(ctx)
|
||||||
EnqueueWikiRetract(ctx, s.task, WikiRetractPayload{
|
EnqueueWikiRetract(ctx, s.task, s.redisClient, WikiRetractPayload{
|
||||||
TenantID: tenantID,
|
TenantID: tenantID,
|
||||||
KnowledgeBaseID: kbID,
|
KnowledgeBaseID: kbID,
|
||||||
KnowledgeID: knowledgeID,
|
KnowledgeID: knowledgeID,
|
||||||
@@ -2494,11 +2494,53 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
|
|||||||
|
|
||||||
// ProcessQuestionGeneration handles async question generation task
|
// ProcessQuestionGeneration handles async question generation task
|
||||||
func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asynq.Task) error {
|
func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asynq.Task) error {
|
||||||
ctx, span := tracing.ContextWithSpan(ctx, "knowledgeService.ProcessQuestionGeneration")
|
taskStartedAt := time.Now()
|
||||||
defer span.End()
|
retryCount, _ := asynq.GetRetryCount(ctx)
|
||||||
|
maxRetry, _ := asynq.GetMaxRetry(ctx)
|
||||||
|
|
||||||
var payload types.QuestionGenerationPayload
|
var payload types.QuestionGenerationPayload
|
||||||
|
exitStatus := "success"
|
||||||
|
totalChunks := 0
|
||||||
|
totalTextChunks := 0
|
||||||
|
emptyContentChunks := 0
|
||||||
|
llmCallAttempts := 0
|
||||||
|
llmCallSuccess := 0
|
||||||
|
llmCallFailed := 0
|
||||||
|
llmCallEmpty := 0
|
||||||
|
generatedQuestionsTotal := 0
|
||||||
|
chunkMetadataSetFailed := 0
|
||||||
|
chunkUpdateFailed := 0
|
||||||
|
indexEntriesPrepared := 0
|
||||||
|
indexBatchAttempted := false
|
||||||
|
indexBatchSucceeded := false
|
||||||
|
defer func() {
|
||||||
|
logger.Infof(
|
||||||
|
ctx,
|
||||||
|
"Question generation stats: knowledge=%s kb=%s retry=%d/%d status=%s elapsed=%s chunks(total=%d,text=%d,empty_text=%d) llm(attempt=%d,success=%d,empty=%d,failed=%d) generated_questions=%d chunk_update_failed=%d metadata_set_failed=%d index(prepared=%d,attempted=%v,succeeded=%v)",
|
||||||
|
payload.KnowledgeID,
|
||||||
|
payload.KnowledgeBaseID,
|
||||||
|
retryCount,
|
||||||
|
maxRetry,
|
||||||
|
exitStatus,
|
||||||
|
time.Since(taskStartedAt).Round(time.Millisecond),
|
||||||
|
totalChunks,
|
||||||
|
totalTextChunks,
|
||||||
|
emptyContentChunks,
|
||||||
|
llmCallAttempts,
|
||||||
|
llmCallSuccess,
|
||||||
|
llmCallEmpty,
|
||||||
|
llmCallFailed,
|
||||||
|
generatedQuestionsTotal,
|
||||||
|
chunkUpdateFailed,
|
||||||
|
chunkMetadataSetFailed,
|
||||||
|
indexEntriesPrepared,
|
||||||
|
indexBatchAttempted,
|
||||||
|
indexBatchSucceeded,
|
||||||
|
)
|
||||||
|
}()
|
||||||
|
|
||||||
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
|
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
|
||||||
|
exitStatus = "invalid_payload"
|
||||||
logger.Errorf(ctx, "Failed to unmarshal question generation payload: %v", err)
|
logger.Errorf(ctx, "Failed to unmarshal question generation payload: %v", err)
|
||||||
return nil // Don't retry on unmarshal error
|
return nil // Don't retry on unmarshal error
|
||||||
}
|
}
|
||||||
@@ -2512,6 +2554,7 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
|||||||
}
|
}
|
||||||
|
|
||||||
if strings.TrimSpace(s.config.Conversation.GenerateQuestionsPrompt) == "" {
|
if strings.TrimSpace(s.config.Conversation.GenerateQuestionsPrompt) == "" {
|
||||||
|
exitStatus = "prompt_not_configured"
|
||||||
logger.Errorf(ctx, "GenerateQuestionsPrompt is empty: configure conversation.generate_questions_prompt_id")
|
logger.Errorf(ctx, "GenerateQuestionsPrompt is empty: configure conversation.generate_questions_prompt_id")
|
||||||
return fmt.Errorf("generate questions prompt not configured")
|
return fmt.Errorf("generate questions prompt not configured")
|
||||||
}
|
}
|
||||||
@@ -2519,6 +2562,7 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
|||||||
// Get knowledge base
|
// Get knowledge base
|
||||||
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, payload.KnowledgeBaseID)
|
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, payload.KnowledgeBaseID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
exitStatus = "kb_not_found"
|
||||||
logger.Errorf(ctx, "Failed to get knowledge base: %v", err)
|
logger.Errorf(ctx, "Failed to get knowledge base: %v", err)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -2526,6 +2570,7 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
|||||||
// Get knowledge
|
// Get knowledge
|
||||||
knowledge, err := s.repo.GetKnowledgeByID(ctx, payload.TenantID, payload.KnowledgeID)
|
knowledge, err := s.repo.GetKnowledgeByID(ctx, payload.TenantID, payload.KnowledgeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
exitStatus = "knowledge_not_found"
|
||||||
logger.Errorf(ctx, "Failed to get knowledge: %v", err)
|
logger.Errorf(ctx, "Failed to get knowledge: %v", err)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -2533,9 +2578,11 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
|||||||
// Get text chunks for this knowledge
|
// Get text chunks for this knowledge
|
||||||
chunks, err := s.chunkService.ListChunksByKnowledgeID(ctx, payload.KnowledgeID)
|
chunks, err := s.chunkService.ListChunksByKnowledgeID(ctx, payload.KnowledgeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
exitStatus = "list_chunks_failed"
|
||||||
logger.Errorf(ctx, "Failed to get chunks: %v", err)
|
logger.Errorf(ctx, "Failed to get chunks: %v", err)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
totalChunks = len(chunks)
|
||||||
|
|
||||||
// Filter text chunks only
|
// Filter text chunks only
|
||||||
textChunks := make([]*types.Chunk, 0)
|
textChunks := make([]*types.Chunk, 0)
|
||||||
@@ -2544,8 +2591,10 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
|||||||
textChunks = append(textChunks, chunk)
|
textChunks = append(textChunks, chunk)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
totalTextChunks = len(textChunks)
|
||||||
|
|
||||||
if len(textChunks) == 0 {
|
if len(textChunks) == 0 {
|
||||||
|
exitStatus = "no_text_chunks"
|
||||||
logger.Infof(ctx, "No text chunks found for knowledge: %s", payload.KnowledgeID)
|
logger.Infof(ctx, "No text chunks found for knowledge: %s", payload.KnowledgeID)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -2558,6 +2607,7 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
|||||||
// Initialize chat model
|
// Initialize chat model
|
||||||
chatModel, err := s.modelService.GetChatModel(ctx, kb.SummaryModelID)
|
chatModel, err := s.modelService.GetChatModel(ctx, kb.SummaryModelID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
exitStatus = "get_chat_model_failed"
|
||||||
logger.Errorf(ctx, "Failed to get chat model: %v", err)
|
logger.Errorf(ctx, "Failed to get chat model: %v", err)
|
||||||
return fmt.Errorf("failed to get chat model: %w", err)
|
return fmt.Errorf("failed to get chat model: %w", err)
|
||||||
}
|
}
|
||||||
@@ -2565,12 +2615,14 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
|||||||
// Initialize embedding model and retrieval engine
|
// Initialize embedding model and retrieval engine
|
||||||
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
exitStatus = "get_embedding_model_failed"
|
||||||
logger.Errorf(ctx, "Failed to get embedding model: %v", err)
|
logger.Errorf(ctx, "Failed to get embedding model: %v", err)
|
||||||
return fmt.Errorf("failed to get embedding model: %w", err)
|
return fmt.Errorf("failed to get embedding model: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
|
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
exitStatus = "get_tenant_failed"
|
||||||
logger.Errorf(ctx, "Failed to get tenant info: %v", err)
|
logger.Errorf(ctx, "Failed to get tenant info: %v", err)
|
||||||
return fmt.Errorf("failed to get tenant info: %w", err)
|
return fmt.Errorf("failed to get tenant info: %w", err)
|
||||||
}
|
}
|
||||||
@@ -2578,6 +2630,7 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
|||||||
|
|
||||||
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.GetEffectiveEngines())
|
retrieveEngine, err := retriever.NewCompositeRetrieveEngine(s.retrieveEngine, tenantInfo.GetEffectiveEngines())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
exitStatus = "init_retrieve_engine_failed"
|
||||||
logger.Errorf(ctx, "Failed to init retrieve engine: %v", err)
|
logger.Errorf(ctx, "Failed to init retrieve engine: %v", err)
|
||||||
return fmt.Errorf("failed to init retrieve engine: %w", err)
|
return fmt.Errorf("failed to init retrieve engine: %w", err)
|
||||||
}
|
}
|
||||||
@@ -2608,30 +2661,34 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
|||||||
// Generate questions for each chunk with context
|
// Generate questions for each chunk with context
|
||||||
var indexInfoList []*types.IndexInfo
|
var indexInfoList []*types.IndexInfo
|
||||||
for i, chunk := range textChunks {
|
for i, chunk := range textChunks {
|
||||||
|
if strings.TrimSpace(chunk.Content) == "" {
|
||||||
|
emptyContentChunks++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
// Build context from adjacent chunks
|
// Build context from adjacent chunks
|
||||||
var prevContent, nextContent string
|
var prevContent, nextContent string
|
||||||
if i > 0 {
|
if i > 0 {
|
||||||
prevContent = enrichContent(textChunks[i-1])
|
prevContent = enrichContent(textChunks[i-1])
|
||||||
if len(prevContent) > 500 {
|
|
||||||
prevContent = prevContent[len(prevContent)-500:]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if i < len(textChunks)-1 {
|
if i < len(textChunks)-1 {
|
||||||
nextContent = enrichContent(textChunks[i+1])
|
nextContent = enrichContent(textChunks[i+1])
|
||||||
if len(nextContent) > 500 {
|
|
||||||
nextContent = nextContent[:500]
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
llmCallAttempts++
|
||||||
questions, err := s.generateQuestionsWithContext(ctx, chatModel, enrichContent(chunk), prevContent, nextContent, knowledge.Title, questionCount)
|
questions, err := s.generateQuestionsWithContext(ctx, chatModel, enrichContent(chunk), prevContent, nextContent, knowledge.Title, questionCount)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
llmCallFailed++
|
||||||
logger.Warnf(ctx, "Failed to generate questions for chunk %s: %v", chunk.ID, err)
|
logger.Warnf(ctx, "Failed to generate questions for chunk %s: %v", chunk.ID, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(questions) == 0 {
|
if len(questions) == 0 {
|
||||||
|
llmCallEmpty++
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
llmCallSuccess++
|
||||||
|
generatedQuestionsTotal += len(questions)
|
||||||
|
|
||||||
// Update chunk metadata with unique IDs for each question
|
// Update chunk metadata with unique IDs for each question
|
||||||
generatedQuestions := make([]types.GeneratedQuestion, len(questions))
|
generatedQuestions := make([]types.GeneratedQuestion, len(questions))
|
||||||
@@ -2646,12 +2703,14 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
|||||||
GeneratedQuestions: generatedQuestions,
|
GeneratedQuestions: generatedQuestions,
|
||||||
}
|
}
|
||||||
if err := chunk.SetDocumentMetadata(meta); err != nil {
|
if err := chunk.SetDocumentMetadata(meta); err != nil {
|
||||||
|
chunkMetadataSetFailed++
|
||||||
logger.Warnf(ctx, "Failed to set document metadata for chunk %s: %v", chunk.ID, err)
|
logger.Warnf(ctx, "Failed to set document metadata for chunk %s: %v", chunk.ID, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update chunk in database
|
// Update chunk in database
|
||||||
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
|
if err := s.chunkService.UpdateChunk(ctx, chunk); err != nil {
|
||||||
|
chunkUpdateFailed++
|
||||||
logger.Warnf(ctx, "Failed to update chunk %s: %v", chunk.ID, err)
|
logger.Warnf(ctx, "Failed to update chunk %s: %v", chunk.ID, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@@ -2671,13 +2730,17 @@ func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asy
|
|||||||
}
|
}
|
||||||
logger.Debugf(ctx, "Generated %d questions for chunk %s", len(questions), chunk.ID)
|
logger.Debugf(ctx, "Generated %d questions for chunk %s", len(questions), chunk.ID)
|
||||||
}
|
}
|
||||||
|
indexEntriesPrepared = len(indexInfoList)
|
||||||
|
|
||||||
// Index generated questions
|
// Index generated questions
|
||||||
if len(indexInfoList) > 0 {
|
if len(indexInfoList) > 0 {
|
||||||
|
indexBatchAttempted = true
|
||||||
if err := retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfoList); err != nil {
|
if err := retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfoList); err != nil {
|
||||||
|
exitStatus = "index_questions_failed"
|
||||||
logger.Errorf(ctx, "Failed to index generated questions: %v", err)
|
logger.Errorf(ctx, "Failed to index generated questions: %v", err)
|
||||||
return fmt.Errorf("failed to index questions: %w", err)
|
return fmt.Errorf("failed to index questions: %w", err)
|
||||||
}
|
}
|
||||||
|
indexBatchSucceeded = true
|
||||||
logger.Infof(ctx, "Successfully indexed %d generated questions for knowledge: %s", len(indexInfoList), payload.KnowledgeID)
|
logger.Infof(ctx, "Successfully indexed %d generated questions for knowledge: %s", len(indexInfoList), payload.KnowledgeID)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2702,10 +2765,10 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
|
|||||||
if prevContent != "" || nextContent != "" {
|
if prevContent != "" || nextContent != "" {
|
||||||
contextSection = "<surrounding_context>\n"
|
contextSection = "<surrounding_context>\n"
|
||||||
if prevContent != "" {
|
if prevContent != "" {
|
||||||
contextSection += fmt.Sprintf("[Preceding Content]\n%s\n\n", prevContent)
|
contextSection += fmt.Sprintf("<preceding_content>\n%s\n\n</preceding_content>\n\n", prevContent)
|
||||||
}
|
}
|
||||||
if nextContent != "" {
|
if nextContent != "" {
|
||||||
contextSection += fmt.Sprintf("[Following Content]\n%s\n\n", nextContent)
|
contextSection += fmt.Sprintf("<following_content>\n%s\n\n</following_content>\n\n", nextContent)
|
||||||
}
|
}
|
||||||
contextSection += "</surrounding_context>\n\n"
|
contextSection += "</surrounding_context>\n\n"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,10 +38,6 @@ const (
|
|||||||
// wikiPendingTTL prevents stale pending lists from accumulating.
|
// wikiPendingTTL prevents stale pending lists from accumulating.
|
||||||
wikiPendingTTL = 24 * time.Hour
|
wikiPendingTTL = 24 * time.Hour
|
||||||
|
|
||||||
// wikiActiveTTL is the max time the "batch in progress" flag stays set.
|
|
||||||
// Safety net — auto-expires if a batch crashes without cleanup.
|
|
||||||
wikiActiveTTL = 60 * time.Minute
|
|
||||||
|
|
||||||
// wikiMaxDocsPerBatch limits how many documents a single batch processes.
|
// wikiMaxDocsPerBatch limits how many documents a single batch processes.
|
||||||
// Prevents unbounded execution time. Remaining docs stay in the pending list
|
// Prevents unbounded execution time. Remaining docs stay in the pending list
|
||||||
// and are picked up by the follow-up task.
|
// and are picked up by the follow-up task.
|
||||||
@@ -54,8 +50,9 @@ const (
|
|||||||
type WikiIngestPayload struct {
|
type WikiIngestPayload struct {
|
||||||
TenantID uint64 `json:"tenant_id"`
|
TenantID uint64 `json:"tenant_id"`
|
||||||
KnowledgeBaseID string `json:"knowledge_base_id"`
|
KnowledgeBaseID string `json:"knowledge_base_id"`
|
||||||
KnowledgeID string `json:"knowledge_id,omitempty"` // Lite mode only
|
|
||||||
Language string `json:"language,omitempty"`
|
Language string `json:"language,omitempty"`
|
||||||
|
// Fallback for Lite mode (no Redis)
|
||||||
|
LiteOps []WikiPendingOp `json:"lite_ops,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// WikiRetractPayload is the asynq task payload for wiki content retraction
|
// WikiRetractPayload is the asynq task payload for wiki content retraction
|
||||||
@@ -69,6 +66,23 @@ type WikiRetractPayload struct {
|
|||||||
PageSlugs []string `json:"page_slugs"`
|
PageSlugs []string `json:"page_slugs"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
WikiOpIngest = "ingest"
|
||||||
|
WikiOpRetract = "retract"
|
||||||
|
)
|
||||||
|
|
||||||
|
// WikiPendingOp represents a single operation in the Redis pending queue
|
||||||
|
type WikiPendingOp struct {
|
||||||
|
Op string `json:"op"`
|
||||||
|
KnowledgeID string `json:"knowledge_id"`
|
||||||
|
// Ingest fields
|
||||||
|
Language string `json:"language,omitempty"`
|
||||||
|
// Retract fields
|
||||||
|
DocTitle string `json:"doc_title,omitempty"`
|
||||||
|
DocSummary string `json:"doc_summary,omitempty"`
|
||||||
|
PageSlugs []string `json:"page_slugs,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
// wikiIngestService handles the LLM-powered wiki generation pipeline
|
// wikiIngestService handles the LLM-powered wiki generation pipeline
|
||||||
type wikiIngestService struct {
|
type wikiIngestService struct {
|
||||||
wikiService interfaces.WikiPageService
|
wikiService interfaces.WikiPageService
|
||||||
@@ -124,24 +138,37 @@ func NewWikiIngestService(
|
|||||||
func EnqueueWikiIngest(ctx context.Context, task interfaces.TaskEnqueuer, redisClient *redis.Client, tenantID uint64, kbID, knowledgeID string) {
|
func EnqueueWikiIngest(ctx context.Context, task interfaces.TaskEnqueuer, redisClient *redis.Client, tenantID uint64, kbID, knowledgeID string) {
|
||||||
lang, _ := types.LanguageFromContext(ctx)
|
lang, _ := types.LanguageFromContext(ctx)
|
||||||
|
|
||||||
// Push to Redis pending list (if Redis available)
|
|
||||||
if redisClient != nil {
|
|
||||||
pendingKey := wikiPendingKeyPrefix + kbID
|
|
||||||
redisClient.RPush(ctx, pendingKey, knowledgeID)
|
|
||||||
redisClient.Expire(ctx, pendingKey, wikiPendingTTL)
|
|
||||||
}
|
|
||||||
|
|
||||||
payload := WikiIngestPayload{
|
payload := WikiIngestPayload{
|
||||||
TenantID: tenantID,
|
TenantID: tenantID,
|
||||||
KnowledgeBaseID: kbID,
|
KnowledgeBaseID: kbID,
|
||||||
KnowledgeID: knowledgeID, // fallback for Lite mode
|
|
||||||
Language: lang,
|
Language: lang,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Push to Redis pending list (if Redis available)
|
||||||
|
if redisClient != nil {
|
||||||
|
pendingKey := wikiPendingKeyPrefix + kbID
|
||||||
|
op := WikiPendingOp{
|
||||||
|
Op: WikiOpIngest,
|
||||||
|
KnowledgeID: knowledgeID,
|
||||||
|
Language: lang,
|
||||||
|
}
|
||||||
|
opBytes, _ := json.Marshal(op)
|
||||||
|
redisClient.RPush(ctx, pendingKey, string(opBytes))
|
||||||
|
redisClient.Expire(ctx, pendingKey, wikiPendingTTL)
|
||||||
|
} else {
|
||||||
|
// Fallback for Lite mode (no Redis)
|
||||||
|
payload.LiteOps = []WikiPendingOp{{
|
||||||
|
Op: WikiOpIngest,
|
||||||
|
KnowledgeID: knowledgeID,
|
||||||
|
Language: lang,
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
|
||||||
payloadBytes, _ := json.Marshal(payload)
|
payloadBytes, _ := json.Marshal(payload)
|
||||||
|
|
||||||
t := asynq.NewTask(types.TypeWikiIngest, payloadBytes,
|
t := asynq.NewTask(types.TypeWikiIngest, payloadBytes,
|
||||||
asynq.Queue("low"),
|
asynq.Queue("low"),
|
||||||
asynq.MaxRetry(3),
|
asynq.MaxRetry(10), // Increased from 3 to 10 to ensure it can outlast the 5-minute active lock TTL
|
||||||
asynq.Timeout(60*time.Minute),
|
asynq.Timeout(60*time.Minute),
|
||||||
asynq.ProcessIn(wikiIngestDelay),
|
asynq.ProcessIn(wikiIngestDelay),
|
||||||
)
|
)
|
||||||
@@ -151,13 +178,39 @@ func EnqueueWikiIngest(ctx context.Context, task interfaces.TaskEnqueuer, redisC
|
|||||||
}
|
}
|
||||||
|
|
||||||
// EnqueueWikiRetract enqueues an async wiki content retraction task
|
// EnqueueWikiRetract enqueues an async wiki content retraction task
|
||||||
func EnqueueWikiRetract(ctx context.Context, task interfaces.TaskEnqueuer, payload WikiRetractPayload) {
|
func EnqueueWikiRetract(ctx context.Context, task interfaces.TaskEnqueuer, redisClient *redis.Client, payload WikiRetractPayload) {
|
||||||
payloadBytes, err := json.Marshal(payload)
|
ingestPayload := WikiIngestPayload{
|
||||||
if err != nil {
|
TenantID: payload.TenantID,
|
||||||
logger.Errorf(ctx, "wiki retract: failed to marshal payload: %v", err)
|
KnowledgeBaseID: payload.KnowledgeBaseID,
|
||||||
return
|
Language: payload.Language,
|
||||||
}
|
}
|
||||||
t := asynq.NewTask(types.TypeWikiRetract, payloadBytes, asynq.Queue("low"), asynq.MaxRetry(3), asynq.Timeout(60*time.Minute))
|
|
||||||
|
op := WikiPendingOp{
|
||||||
|
Op: WikiOpRetract,
|
||||||
|
KnowledgeID: payload.KnowledgeID,
|
||||||
|
DocTitle: payload.DocTitle,
|
||||||
|
DocSummary: payload.DocSummary,
|
||||||
|
PageSlugs: payload.PageSlugs,
|
||||||
|
Language: payload.Language,
|
||||||
|
}
|
||||||
|
|
||||||
|
if redisClient != nil {
|
||||||
|
pendingKey := wikiPendingKeyPrefix + payload.KnowledgeBaseID
|
||||||
|
opBytes, _ := json.Marshal(op)
|
||||||
|
redisClient.RPush(ctx, pendingKey, string(opBytes))
|
||||||
|
redisClient.Expire(ctx, pendingKey, wikiPendingTTL)
|
||||||
|
} else {
|
||||||
|
// Fallback for Lite mode (no Redis)
|
||||||
|
ingestPayload.LiteOps = []WikiPendingOp{op}
|
||||||
|
}
|
||||||
|
|
||||||
|
payloadBytes, _ := json.Marshal(ingestPayload)
|
||||||
|
t := asynq.NewTask(types.TypeWikiIngest, payloadBytes,
|
||||||
|
asynq.Queue("low"),
|
||||||
|
asynq.MaxRetry(10), // Increased from 3 to 10 to outlast the active lock TTL
|
||||||
|
asynq.Timeout(60*time.Minute),
|
||||||
|
asynq.ProcessIn(5*time.Second), // Retract can trigger the batch quickly
|
||||||
|
)
|
||||||
if _, err := task.Enqueue(t); err != nil {
|
if _, err := task.Enqueue(t); err != nil {
|
||||||
logger.Warnf(ctx, "wiki retract: failed to enqueue task: %v", err)
|
logger.Warnf(ctx, "wiki retract: failed to enqueue task: %v", err)
|
||||||
}
|
}
|
||||||
@@ -167,72 +220,8 @@ func EnqueueWikiRetract(ctx context.Context, task interfaces.TaskEnqueuer, paylo
|
|||||||
// Wiki ingest tasks are debounced via asynq.Unique + ProcessIn, so at most
|
// Wiki ingest tasks are debounced via asynq.Unique + ProcessIn, so at most
|
||||||
// one ingest task runs per KB at a time. No distributed lock needed.
|
// one ingest task runs per KB at a time. No distributed lock needed.
|
||||||
func (s *wikiIngestService) Handle(ctx context.Context, t *asynq.Task) error {
|
func (s *wikiIngestService) Handle(ctx context.Context, t *asynq.Task) error {
|
||||||
switch t.Type() {
|
|
||||||
case types.TypeWikiRetract:
|
|
||||||
return s.ProcessWikiRetract(ctx, t)
|
|
||||||
default:
|
|
||||||
return s.ProcessWikiIngest(ctx, t)
|
return s.ProcessWikiIngest(ctx, t)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// ProcessWikiRetract uses LLM to remove deleted document's contributions from wiki pages
|
|
||||||
func (s *wikiIngestService) ProcessWikiRetract(ctx context.Context, t *asynq.Task) error {
|
|
||||||
var payload WikiRetractPayload
|
|
||||||
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
|
|
||||||
return fmt.Errorf("wiki retract: unmarshal payload: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.Infof(ctx, "wiki retract: starting for knowledge %s (%s), %d pages",
|
|
||||||
payload.KnowledgeID, payload.DocTitle, len(payload.PageSlugs))
|
|
||||||
|
|
||||||
// Inject context values
|
|
||||||
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
|
|
||||||
if payload.Language != "" {
|
|
||||||
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get KB and synthesis model
|
|
||||||
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("wiki retract: get KB: %w", err)
|
|
||||||
}
|
|
||||||
synthesisModelID := kb.WikiConfig.SynthesisModelID
|
|
||||||
if synthesisModelID == "" {
|
|
||||||
synthesisModelID = kb.SummaryModelID
|
|
||||||
}
|
|
||||||
if synthesisModelID == "" {
|
|
||||||
return fmt.Errorf("wiki retract: no synthesis model for KB %s", kb.ID)
|
|
||||||
}
|
|
||||||
chatModel, err := s.modelService.GetChatModel(ctx, synthesisModelID)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("wiki retract: get chat model: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
lang := types.LanguageNameFromContext(ctx)
|
|
||||||
|
|
||||||
s.retractPagesContent(ctx, chatModel, payload.KnowledgeBaseID, payload.DocTitle, payload.DocSummary, payload.PageSlugs, lang)
|
|
||||||
|
|
||||||
// Rebuild index page to reflect changes
|
|
||||||
retractChangeDesc := fmt.Sprintf("Removed document '%s': %s", payload.DocTitle, payload.DocSummary)
|
|
||||||
if err := s.rebuildIndexPage(ctx, chatModel, WikiIngestPayload{
|
|
||||||
TenantID: payload.TenantID,
|
|
||||||
KnowledgeBaseID: payload.KnowledgeBaseID,
|
|
||||||
}, retractChangeDesc, lang); err != nil {
|
|
||||||
logger.Warnf(ctx, "wiki retract: rebuild index failed: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Append log entry
|
|
||||||
s.appendLogEntry(ctx, WikiIngestPayload{
|
|
||||||
TenantID: payload.TenantID,
|
|
||||||
KnowledgeBaseID: payload.KnowledgeBaseID,
|
|
||||||
KnowledgeID: payload.KnowledgeID,
|
|
||||||
}, "retract", payload.DocTitle, payload.PageSlugs, "")
|
|
||||||
|
|
||||||
// Clean up dead links pointing to archived/deleted pages
|
|
||||||
s.cleanDeadLinks(ctx, payload.KnowledgeBaseID)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// retractPagesContent uses LLM to remove a deleted/stale document's contributions
|
// retractPagesContent uses LLM to remove a deleted/stale document's contributions
|
||||||
// from the given wiki pages. docContent is the deleted document's content (or summary)
|
// from the given wiki pages. docContent is the deleted document's content (or summary)
|
||||||
@@ -247,10 +236,20 @@ func (s *wikiIngestService) retractPagesContent(
|
|||||||
) {
|
) {
|
||||||
allPages, _ := s.wikiService.ListAllPages(ctx, kbID)
|
allPages, _ := s.wikiService.ListAllPages(ctx, kbID)
|
||||||
slugTitleMap := make(map[string]string)
|
slugTitleMap := make(map[string]string)
|
||||||
|
summaryContentByKnowledgeID := make(map[string]string)
|
||||||
for _, p := range allPages {
|
for _, p := range allPages {
|
||||||
if p.PageType != types.WikiPageTypeIndex && p.PageType != types.WikiPageTypeLog && p.Status != types.WikiPageStatusArchived {
|
if p.PageType != types.WikiPageTypeIndex && p.PageType != types.WikiPageTypeLog && p.Status != types.WikiPageStatusArchived {
|
||||||
slugTitleMap[p.Slug] = p.Title
|
slugTitleMap[p.Slug] = p.Title
|
||||||
}
|
}
|
||||||
|
if p.PageType == types.WikiPageTypeSummary && p.Content != "" {
|
||||||
|
for _, ref := range p.SourceRefs {
|
||||||
|
kid := ref
|
||||||
|
if pipeIdx := strings.Index(ref, "|"); pipeIdx > 0 {
|
||||||
|
kid = ref[:pipeIdx]
|
||||||
|
}
|
||||||
|
summaryContentByKnowledgeID[kid] = p.Content
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, slug := range pageSlugs {
|
for _, slug := range pageSlugs {
|
||||||
@@ -259,17 +258,25 @@ func (s *wikiIngestService) retractPagesContent(
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
var remainingSources string
|
var remainingSourcesContent strings.Builder
|
||||||
for _, ref := range page.SourceRefs {
|
for _, ref := range page.SourceRefs {
|
||||||
pipeIdx := strings.Index(ref, "|")
|
pipeIdx := strings.Index(ref, "|")
|
||||||
|
var refKnowledgeID, refTitle string
|
||||||
if pipeIdx > 0 {
|
if pipeIdx > 0 {
|
||||||
remainingSources += "- " + ref[pipeIdx+1:] + "\n"
|
refKnowledgeID = ref[:pipeIdx]
|
||||||
|
refTitle = ref[pipeIdx+1:]
|
||||||
} else {
|
} else {
|
||||||
remainingSources += "- " + ref + "\n"
|
refKnowledgeID = ref
|
||||||
|
refTitle = ref
|
||||||
|
}
|
||||||
|
if content, ok := summaryContentByKnowledgeID[refKnowledgeID]; ok {
|
||||||
|
fmt.Fprintf(&remainingSourcesContent, "<source title=%q>\n%s\n</source>\n\n", refTitle, content)
|
||||||
|
} else {
|
||||||
|
fmt.Fprintf(&remainingSourcesContent, "<source title=%q>\n(summary not available)\n</source>\n\n", refTitle)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if remainingSources == "" {
|
if remainingSourcesContent.Len() == 0 {
|
||||||
remainingSources = "(no other sources)"
|
remainingSourcesContent.WriteString("(no remaining sources)")
|
||||||
}
|
}
|
||||||
|
|
||||||
var relatedSlugs strings.Builder
|
var relatedSlugs strings.Builder
|
||||||
@@ -283,7 +290,7 @@ func (s *wikiIngestService) retractPagesContent(
|
|||||||
"ExistingContent": page.Content,
|
"ExistingContent": page.Content,
|
||||||
"DeletedDocTitle": docTitle,
|
"DeletedDocTitle": docTitle,
|
||||||
"DeletedDocContent": docContent,
|
"DeletedDocContent": docContent,
|
||||||
"RemainingSources": remainingSources,
|
"RemainingSourcesContent": remainingSourcesContent.String(),
|
||||||
"AvailableSlugs": relatedSlugs.String(),
|
"AvailableSlugs": relatedSlugs.String(),
|
||||||
"Language": lang,
|
"Language": lang,
|
||||||
})
|
})
|
||||||
@@ -322,8 +329,57 @@ func (s *wikiIngestService) retractPagesContent(
|
|||||||
//
|
//
|
||||||
// This ensures: one batch per KB at a time, no locks, no blocking, no timeouts.
|
// This ensures: one batch per KB at a time, no locks, no blocking, no timeouts.
|
||||||
func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task) error {
|
func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task) error {
|
||||||
|
taskStartedAt := time.Now()
|
||||||
|
retryCount, _ := asynq.GetRetryCount(ctx)
|
||||||
|
maxRetry, _ := asynq.GetMaxRetry(ctx)
|
||||||
|
|
||||||
var payload WikiIngestPayload
|
var payload WikiIngestPayload
|
||||||
|
exitStatus := "success"
|
||||||
|
mode := "redis"
|
||||||
|
lockAcquired := false
|
||||||
|
pendingOpsCount := 0
|
||||||
|
ingestOps := 0
|
||||||
|
retractOps := 0
|
||||||
|
ingestSucceeded := 0
|
||||||
|
ingestFailed := 0
|
||||||
|
retractHandled := 0
|
||||||
|
indexRebuildAttempted := false
|
||||||
|
indexRebuildSucceeded := false
|
||||||
|
followUpScheduled := false
|
||||||
|
ingestPagesCount := 0
|
||||||
|
retractPagesCount := 0
|
||||||
|
totalPagesAffected := 0
|
||||||
|
docPreview := make([]string, 0, 6)
|
||||||
|
defer func() {
|
||||||
|
logger.Infof(
|
||||||
|
ctx,
|
||||||
|
"wiki ingest stats: kb=%s tenant=%d retry=%d/%d status=%s elapsed=%s mode=%s lock_acquired=%v pending_ops=%d ops(ingest=%d,retract=%d) ingest(success=%d,failed=%d) retract_handled=%d pages(ingest=%d,retract=%d,total=%d) index(rebuild_attempted=%v,rebuild_succeeded=%v) followup=%v preview=%s",
|
||||||
|
payload.KnowledgeBaseID,
|
||||||
|
payload.TenantID,
|
||||||
|
retryCount,
|
||||||
|
maxRetry,
|
||||||
|
exitStatus,
|
||||||
|
time.Since(taskStartedAt).Round(time.Millisecond),
|
||||||
|
mode,
|
||||||
|
lockAcquired,
|
||||||
|
pendingOpsCount,
|
||||||
|
ingestOps,
|
||||||
|
retractOps,
|
||||||
|
ingestSucceeded,
|
||||||
|
ingestFailed,
|
||||||
|
retractHandled,
|
||||||
|
ingestPagesCount,
|
||||||
|
retractPagesCount,
|
||||||
|
totalPagesAffected,
|
||||||
|
indexRebuildAttempted,
|
||||||
|
indexRebuildSucceeded,
|
||||||
|
followUpScheduled,
|
||||||
|
previewStringSlice(docPreview, 6),
|
||||||
|
)
|
||||||
|
}()
|
||||||
|
|
||||||
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
|
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
|
||||||
|
exitStatus = "invalid_payload"
|
||||||
return fmt.Errorf("wiki ingest: unmarshal payload: %w", err)
|
return fmt.Errorf("wiki ingest: unmarshal payload: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -336,30 +392,61 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
|||||||
// Try to acquire the "active batch" flag (non-blocking)
|
// Try to acquire the "active batch" flag (non-blocking)
|
||||||
if s.redisClient != nil {
|
if s.redisClient != nil {
|
||||||
activeKey := wikiActiveKeyPrefix + payload.KnowledgeBaseID
|
activeKey := wikiActiveKeyPrefix + payload.KnowledgeBaseID
|
||||||
acquired, err := s.redisClient.SetNX(ctx, activeKey, "1", wikiActiveTTL).Result()
|
// Use a 5-minute initial TTL
|
||||||
|
acquired, err := s.redisClient.SetNX(ctx, activeKey, "1", 5*time.Minute).Result()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warnf(ctx, "wiki ingest: redis SetNX failed: %v", err)
|
logger.Warnf(ctx, "wiki ingest: redis SetNX failed: %v", err)
|
||||||
// Proceed anyway — better to risk brief overlap than drop documents
|
// Proceed anyway — better to risk brief overlap than drop documents
|
||||||
} else if !acquired {
|
} else if !acquired {
|
||||||
// Another batch is actively processing this KB — bail out.
|
exitStatus = "active_lock_conflict"
|
||||||
// Our documents are safe in the pending list; the active batch will
|
// Another batch is actively processing this KB.
|
||||||
// pick them up via its follow-up check, or a future task will.
|
// By returning an error, we leverage Asynq's built-in exponential backoff to retry this task later.
|
||||||
logger.Infof(ctx, "wiki ingest: another batch active for KB %s, skipping (docs safe in pending list)", payload.KnowledgeBaseID)
|
// This ensures that if the active task crashes (leaking the lock until its TTL expires),
|
||||||
return nil
|
// this task will eventually retry and process the remaining items in the queue, preventing a stalled queue.
|
||||||
|
logger.Infof(ctx, "wiki ingest: another batch active for KB %s, deferring to asynq retry", payload.KnowledgeBaseID)
|
||||||
|
return fmt.Errorf("concurrent wiki task active, please retry")
|
||||||
}
|
}
|
||||||
|
lockAcquired = acquired
|
||||||
|
|
||||||
|
// Create a context to cancel the keep-alive goroutine when we're done
|
||||||
|
lockCtx, cancelLock := context.WithCancel(context.Background())
|
||||||
|
|
||||||
// We own the flag — make sure to release it when done
|
// We own the flag — make sure to release it when done
|
||||||
defer s.redisClient.Del(ctx, activeKey)
|
defer func() {
|
||||||
|
cancelLock()
|
||||||
|
// Use context.Background() to ensure release even if ctx is cancelled
|
||||||
|
s.redisClient.Del(context.Background(), activeKey)
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Keep-alive goroutine to extend lock TTL while the task is running
|
||||||
|
go func() {
|
||||||
|
ticker := time.NewTicker(2 * time.Minute)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-lockCtx.Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
s.redisClient.Expire(context.Background(), activeKey, 5*time.Minute)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
} else {
|
||||||
|
mode = "lite"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get KB and validate
|
// Get KB and validate
|
||||||
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID)
|
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
exitStatus = "get_kb_failed"
|
||||||
return fmt.Errorf("wiki ingest: get KB: %w", err)
|
return fmt.Errorf("wiki ingest: get KB: %w", err)
|
||||||
}
|
}
|
||||||
if !kb.IsWikiEnabled() {
|
if !kb.IsWikiEnabled() {
|
||||||
|
exitStatus = "kb_not_wiki_enabled"
|
||||||
return fmt.Errorf("wiki ingest: KB %s is not wiki type", kb.ID)
|
return fmt.Errorf("wiki ingest: KB %s is not wiki type", kb.ID)
|
||||||
}
|
}
|
||||||
if kb.WikiConfig == nil || !kb.WikiConfig.AutoIngest {
|
if kb.WikiConfig == nil || !kb.WikiConfig.AutoIngest {
|
||||||
|
exitStatus = "auto_ingest_disabled"
|
||||||
logger.Infof(ctx, "wiki ingest: auto_ingest disabled for KB %s, skipping", kb.ID)
|
logger.Infof(ctx, "wiki ingest: auto_ingest disabled for KB %s, skipping", kb.ID)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -370,80 +457,154 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
|||||||
synthesisModelID = kb.SummaryModelID
|
synthesisModelID = kb.SummaryModelID
|
||||||
}
|
}
|
||||||
if synthesisModelID == "" {
|
if synthesisModelID == "" {
|
||||||
|
exitStatus = "missing_synthesis_model"
|
||||||
return fmt.Errorf("wiki ingest: no synthesis model configured for KB %s", kb.ID)
|
return fmt.Errorf("wiki ingest: no synthesis model configured for KB %s", kb.ID)
|
||||||
}
|
}
|
||||||
chatModel, err := s.modelService.GetChatModel(ctx, synthesisModelID)
|
chatModel, err := s.modelService.GetChatModel(ctx, synthesisModelID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
exitStatus = "get_chat_model_failed"
|
||||||
return fmt.Errorf("wiki ingest: get chat model: %w", err)
|
return fmt.Errorf("wiki ingest: get chat model: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
lang := types.LanguageNameFromContext(ctx)
|
lang := types.LanguageNameFromContext(ctx)
|
||||||
|
|
||||||
// Drain Redis pending list to get all documents queued for this KB
|
// Peek Redis pending list to get all operations queued for this KB without removing them
|
||||||
knowledgeIDs := s.drainPendingList(ctx, payload.KnowledgeBaseID)
|
pendingOps, peekedCount := s.peekPendingList(ctx, payload.KnowledgeBaseID)
|
||||||
if len(knowledgeIDs) == 0 {
|
pendingOpsCount = len(pendingOps)
|
||||||
|
if len(pendingOps) == 0 {
|
||||||
if s.redisClient != nil {
|
if s.redisClient != nil {
|
||||||
// Redis mode: list was already drained — nothing to do
|
// Redis mode: list was already drained — nothing to do
|
||||||
|
exitStatus = "no_pending_ops"
|
||||||
|
logger.Infof(ctx, "wiki ingest: no pending operations for KB %s", payload.KnowledgeBaseID)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
// Lite mode (no Redis): use the single KnowledgeID from payload
|
// Lite mode (no Redis): use LiteOps from payload
|
||||||
if payload.KnowledgeID != "" {
|
if len(payload.LiteOps) > 0 {
|
||||||
knowledgeIDs = []string{payload.KnowledgeID}
|
pendingOps = payload.LiteOps
|
||||||
|
peekedCount = len(pendingOps)
|
||||||
|
pendingOpsCount = len(pendingOps)
|
||||||
} else {
|
} else {
|
||||||
|
exitStatus = "no_lite_ops"
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Infof(ctx, "wiki ingest: batch processing %d documents for KB %s: %v",
|
logger.Infof(ctx, "wiki ingest: batch processing %d ops for KB %s",
|
||||||
len(knowledgeIDs), payload.KnowledgeBaseID, knowledgeIDs)
|
len(pendingOps), payload.KnowledgeBaseID)
|
||||||
|
|
||||||
// Process each document
|
// Process each operation
|
||||||
var allPagesAffected []string
|
var ingestPagesAffected []string
|
||||||
|
var retractPagesAffected []string
|
||||||
var docResults []*docIngestResult
|
var docResults []*docIngestResult
|
||||||
for _, knowledgeID := range knowledgeIDs {
|
var retractChangeDesc strings.Builder
|
||||||
result, err := s.processOneDocument(ctx, chatModel, payload, knowledgeID, lang)
|
|
||||||
|
for _, op := range pendingOps {
|
||||||
|
if op.Op == WikiOpRetract {
|
||||||
|
retractOps++
|
||||||
|
logger.Infof(ctx, "wiki ingest: retracting document '%s' (%s)", op.DocTitle, op.KnowledgeID)
|
||||||
|
s.retractPagesContent(ctx, chatModel, payload.KnowledgeBaseID, op.DocTitle, op.DocSummary, op.PageSlugs, op.Language)
|
||||||
|
retractPagesAffected = append(retractPagesAffected, op.PageSlugs...)
|
||||||
|
retractPagesCount += len(op.PageSlugs)
|
||||||
|
retractHandled++
|
||||||
|
docPreview = append(docPreview,
|
||||||
|
fmt.Sprintf("retract[%s]: %s", previewText(op.KnowledgeID, 24), previewText(op.DocTitle, 48)))
|
||||||
|
fmt.Fprintf(&retractChangeDesc, "Removed document '%s': %s\n", op.DocTitle, op.DocSummary)
|
||||||
|
s.appendLogEntry(ctx, WikiIngestPayload{
|
||||||
|
TenantID: payload.TenantID,
|
||||||
|
KnowledgeBaseID: payload.KnowledgeBaseID,
|
||||||
|
}, "retract", op.KnowledgeID, op.DocTitle, op.PageSlugs, "")
|
||||||
|
} else {
|
||||||
|
ingestOps++
|
||||||
|
// Default to ingest
|
||||||
|
logger.Infof(ctx, "wiki ingest: processing document '%s' (%s)", op.DocTitle, op.KnowledgeID)
|
||||||
|
result, err := s.processOneDocument(ctx, chatModel, payload, op.KnowledgeID, op.Language)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warnf(ctx, "wiki ingest: failed to process knowledge %s: %v", knowledgeID, err)
|
ingestFailed++
|
||||||
|
logger.Warnf(ctx, "wiki ingest: failed to process knowledge %s: %v", op.KnowledgeID, err)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if result != nil {
|
if result != nil {
|
||||||
allPagesAffected = append(allPagesAffected, result.Pages...)
|
ingestSucceeded++
|
||||||
|
ingestPagesAffected = append(ingestPagesAffected, result.Pages...)
|
||||||
|
ingestPagesCount += len(result.Pages)
|
||||||
docResults = append(docResults, result)
|
docResults = append(docResults, result)
|
||||||
|
docPreview = append(docPreview,
|
||||||
|
fmt.Sprintf(
|
||||||
|
"ingest[%s]: title=%s summary=%s pages=%s",
|
||||||
|
previewText(result.KnowledgeID, 24),
|
||||||
|
previewText(result.DocTitle, 40),
|
||||||
|
previewText(result.Summary, 64),
|
||||||
|
previewStringSlice(result.Pages, 4),
|
||||||
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
allPagesAffected := append(ingestPagesAffected, retractPagesAffected...)
|
||||||
|
totalPagesAffected = len(allPagesAffected)
|
||||||
|
|
||||||
// Batch post-processing (once for the whole batch, not per-doc)
|
// Batch post-processing (once for the whole batch, not per-doc)
|
||||||
|
|
||||||
// Build change description from processed documents
|
// Build change description from processed documents
|
||||||
var changeDesc strings.Builder
|
var changeDesc strings.Builder
|
||||||
|
if len(docResults) > 0 {
|
||||||
fmt.Fprintf(&changeDesc, "Added %d documents:\n", len(docResults))
|
fmt.Fprintf(&changeDesc, "Added %d documents:\n", len(docResults))
|
||||||
for _, r := range docResults {
|
for _, r := range docResults {
|
||||||
fmt.Fprintf(&changeDesc, "- %s: %s\n", r.DocTitle, r.Summary)
|
fmt.Fprintf(&changeDesc, "- %s: %s\n", r.DocTitle, r.Summary)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
// Rebuild index page
|
if retractChangeDesc.Len() > 0 {
|
||||||
if err := s.rebuildIndexPage(ctx, chatModel, payload, changeDesc.String(), lang); err != nil {
|
changeDesc.WriteString(retractChangeDesc.String())
|
||||||
logger.Warnf(ctx, "wiki ingest: rebuild index failed: %v", err)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Append log entry
|
// Rebuild index page
|
||||||
s.appendLogEntry(ctx, payload, "ingest",
|
if changeDesc.Len() > 0 {
|
||||||
fmt.Sprintf("%d documents", len(knowledgeIDs)),
|
indexRebuildAttempted = true
|
||||||
allPagesAffected, "")
|
logger.Infof(ctx, "wiki ingest: rebuilding index page")
|
||||||
|
if err := s.rebuildIndexPage(ctx, chatModel, payload, changeDesc.String(), lang); err != nil {
|
||||||
|
logger.Warnf(ctx, "wiki ingest: rebuild index failed: %v", err)
|
||||||
|
docPreview = append(docPreview,
|
||||||
|
fmt.Sprintf("index_change=%s", previewText(changeDesc.String(), 160)))
|
||||||
|
} else {
|
||||||
|
indexRebuildSucceeded = true
|
||||||
|
docPreview = append(docPreview,
|
||||||
|
fmt.Sprintf("index_change=%s", previewText(changeDesc.String(), 160)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Append log entry for ingests
|
||||||
|
if len(docResults) > 0 {
|
||||||
|
s.appendLogEntry(ctx, payload, "ingest", "",
|
||||||
|
fmt.Sprintf("%d documents", len(docResults)),
|
||||||
|
ingestPagesAffected, "")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clean dead links (needed after retracts)
|
||||||
|
if len(retractPagesAffected) > 0 {
|
||||||
|
logger.Infof(ctx, "wiki ingest: cleaning dead links")
|
||||||
|
s.cleanDeadLinks(ctx, payload.KnowledgeBaseID)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(allPagesAffected) > 0 {
|
||||||
// Cross-link injection
|
// Cross-link injection
|
||||||
|
logger.Infof(ctx, "wiki ingest: injecting cross links")
|
||||||
s.injectCrossLinks(ctx, payload.KnowledgeBaseID, allPagesAffected)
|
s.injectCrossLinks(ctx, payload.KnowledgeBaseID, allPagesAffected)
|
||||||
|
|
||||||
// Publish all draft pages
|
// Publish all draft pages
|
||||||
|
logger.Infof(ctx, "wiki ingest: publishing draft pages")
|
||||||
s.publishDraftPages(ctx, payload.KnowledgeBaseID, allPagesAffected)
|
s.publishDraftPages(ctx, payload.KnowledgeBaseID, allPagesAffected)
|
||||||
|
}
|
||||||
|
|
||||||
logger.Infof(ctx, "wiki ingest: batch completed for KB %s, %d docs, %d pages affected",
|
// Trim the pending list now that processing is complete
|
||||||
payload.KnowledgeBaseID, len(knowledgeIDs), len(allPagesAffected))
|
s.trimPendingList(ctx, payload.KnowledgeBaseID, peekedCount)
|
||||||
|
|
||||||
|
logger.Infof(ctx, "wiki ingest: batch completed for KB %s, %d ops, %d pages affected",
|
||||||
|
payload.KnowledgeBaseID, len(pendingOps), len(allPagesAffected))
|
||||||
|
|
||||||
// After clearing active flag (via defer above), check for follow-up work.
|
// After clearing active flag (via defer above), check for follow-up work.
|
||||||
// Note: this runs BEFORE defer, but defer runs LIFO so active flag is still set here.
|
// Note: this runs BEFORE defer, but defer runs LIFO so active flag is still set here.
|
||||||
// We need to clear it first, then check. Use a closure:
|
// We need to clear it first, then check. Use a closure:
|
||||||
s.scheduleFollowUp(ctx, payload)
|
followUpScheduled = s.scheduleFollowUp(ctx, payload)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -451,14 +612,14 @@ func (s *wikiIngestService) ProcessWikiIngest(ctx context.Context, t *asynq.Task
|
|||||||
// scheduleFollowUp checks if documents arrived in the pending list during batch processing.
|
// scheduleFollowUp checks if documents arrived in the pending list during batch processing.
|
||||||
// Called right before the active flag is released (via defer). Enqueues a new task with
|
// Called right before the active flag is released (via defer). Enqueues a new task with
|
||||||
// minimal delay so the next batch picks up new docs promptly.
|
// minimal delay so the next batch picks up new docs promptly.
|
||||||
func (s *wikiIngestService) scheduleFollowUp(ctx context.Context, payload WikiIngestPayload) {
|
func (s *wikiIngestService) scheduleFollowUp(ctx context.Context, payload WikiIngestPayload) bool {
|
||||||
if s.redisClient == nil {
|
if s.redisClient == nil {
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
pendingKey := wikiPendingKeyPrefix + payload.KnowledgeBaseID
|
pendingKey := wikiPendingKeyPrefix + payload.KnowledgeBaseID
|
||||||
count, err := s.redisClient.LLen(ctx, pendingKey).Result()
|
count, err := s.redisClient.LLen(ctx, pendingKey).Result()
|
||||||
if err != nil || count == 0 {
|
if err != nil || count == 0 {
|
||||||
return
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.Infof(ctx, "wiki ingest: %d more documents pending for KB %s, scheduling follow-up", count, payload.KnowledgeBaseID)
|
logger.Infof(ctx, "wiki ingest: %d more documents pending for KB %s, scheduling follow-up", count, payload.KnowledgeBaseID)
|
||||||
@@ -466,45 +627,77 @@ func (s *wikiIngestService) scheduleFollowUp(ctx context.Context, payload WikiIn
|
|||||||
payloadBytes, _ := json.Marshal(payload)
|
payloadBytes, _ := json.Marshal(payload)
|
||||||
t := asynq.NewTask(types.TypeWikiIngest, payloadBytes,
|
t := asynq.NewTask(types.TypeWikiIngest, payloadBytes,
|
||||||
asynq.Queue("low"),
|
asynq.Queue("low"),
|
||||||
asynq.MaxRetry(3),
|
asynq.MaxRetry(10), // Increased from 3 to 10 to outlast the active lock TTL
|
||||||
asynq.Timeout(60*time.Minute),
|
asynq.Timeout(60*time.Minute),
|
||||||
asynq.ProcessIn(5*time.Second), // short delay — active flag will be released by then
|
asynq.ProcessIn(5*time.Second), // short delay — active flag will be released by then
|
||||||
)
|
)
|
||||||
if _, err := s.task.Enqueue(t); err != nil {
|
if _, err := s.task.Enqueue(t); err != nil {
|
||||||
logger.Warnf(ctx, "wiki ingest: follow-up enqueue failed: %v", err)
|
logger.Warnf(ctx, "wiki ingest: follow-up enqueue failed: %v", err)
|
||||||
|
return false
|
||||||
}
|
}
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// drainPendingList atomically pops up to wikiMaxDocsPerBatch entries from the
|
// peekPendingList gets up to wikiMaxDocsPerBatch entries from the Redis pending list
|
||||||
// Redis pending list. Remaining entries stay in the list for the follow-up batch.
|
// WITHOUT removing them. It returns the unique ops and the actual number of items peeked.
|
||||||
func (s *wikiIngestService) drainPendingList(ctx context.Context, kbID string) []string {
|
func (s *wikiIngestService) peekPendingList(ctx context.Context, kbID string) ([]WikiPendingOp, int) {
|
||||||
if s.redisClient == nil {
|
if s.redisClient == nil {
|
||||||
return nil
|
return nil, 0
|
||||||
}
|
}
|
||||||
pendingKey := wikiPendingKeyPrefix + kbID
|
pendingKey := wikiPendingKeyPrefix + kbID
|
||||||
|
|
||||||
// Atomically pop up to N items: LRANGE + LTRIM in a single Lua script
|
result, err := s.redisClient.LRange(ctx, pendingKey, 0, wikiMaxDocsPerBatch-1).Result()
|
||||||
script := redis.NewScript(`
|
|
||||||
local items = redis.call("LRANGE", KEYS[1], 0, tonumber(ARGV[1]) - 1)
|
|
||||||
redis.call("LTRIM", KEYS[1], tonumber(ARGV[1]), -1)
|
|
||||||
return items
|
|
||||||
`)
|
|
||||||
result, err := script.Run(ctx, s.redisClient, []string{pendingKey}, wikiMaxDocsPerBatch).StringSlice()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warnf(ctx, "wiki ingest: failed to drain pending list: %v", err)
|
logger.Warnf(ctx, "wiki ingest: failed to peek pending list: %v", err)
|
||||||
return nil
|
return nil, 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deduplicate (same doc could be pushed multiple times if re-uploaded)
|
var ops []WikiPendingOp
|
||||||
|
for _, item := range result {
|
||||||
|
if !strings.HasPrefix(item, "{") {
|
||||||
|
// Backward compatibility: raw knowledgeID string
|
||||||
|
ops = append(ops, WikiPendingOp{
|
||||||
|
Op: WikiOpIngest,
|
||||||
|
KnowledgeID: item,
|
||||||
|
})
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
var op WikiPendingOp
|
||||||
|
if err := json.Unmarshal([]byte(item), &op); err == nil {
|
||||||
|
ops = append(ops, op)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deduplicate by KnowledgeID, keeping only the *last* operation for each document.
|
||||||
|
// This optimizes out redundant sequences (e.g., upload then immediate delete: [ingest, retract] -> [retract]).
|
||||||
seen := make(map[string]bool)
|
seen := make(map[string]bool)
|
||||||
var unique []string
|
var reversedUnique []WikiPendingOp
|
||||||
for _, id := range result {
|
for i := len(ops) - 1; i >= 0; i-- {
|
||||||
if !seen[id] {
|
op := ops[i]
|
||||||
seen[id] = true
|
if !seen[op.KnowledgeID] {
|
||||||
unique = append(unique, id)
|
seen[op.KnowledgeID] = true
|
||||||
|
reversedUnique = append(reversedUnique, op)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return unique
|
|
||||||
|
// Reverse back to maintain chronological order
|
||||||
|
var unique []WikiPendingOp
|
||||||
|
for i := len(reversedUnique) - 1; i >= 0; i-- {
|
||||||
|
unique = append(unique, reversedUnique[i])
|
||||||
|
}
|
||||||
|
|
||||||
|
return unique, len(result)
|
||||||
|
}
|
||||||
|
|
||||||
|
// trimPendingList removes the first `count` items from the Redis pending list.
|
||||||
|
func (s *wikiIngestService) trimPendingList(ctx context.Context, kbID string, count int) {
|
||||||
|
if s.redisClient == nil || count <= 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pendingKey := wikiPendingKeyPrefix + kbID
|
||||||
|
if err := s.redisClient.LTrim(ctx, pendingKey, int64(count), -1).Err(); err != nil {
|
||||||
|
logger.Warnf(ctx, "wiki ingest: failed to trim pending list: %v", err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// docIngestResult captures per-document info for batch post-processing.
|
// docIngestResult captures per-document info for batch post-processing.
|
||||||
@@ -523,19 +716,25 @@ func (s *wikiIngestService) processOneDocument(
|
|||||||
knowledgeID string,
|
knowledgeID string,
|
||||||
lang string,
|
lang string,
|
||||||
) (*docIngestResult, error) {
|
) (*docIngestResult, error) {
|
||||||
|
docStartedAt := time.Now()
|
||||||
// Get document chunks and reconstruct content
|
// Get document chunks and reconstruct content
|
||||||
chunks, err := s.chunkRepo.ListChunksByKnowledgeID(ctx, payload.TenantID, knowledgeID)
|
chunks, err := s.chunkRepo.ListChunksByKnowledgeID(ctx, payload.TenantID, knowledgeID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("get chunks: %w", err)
|
return nil, fmt.Errorf("get chunks: %w", err)
|
||||||
}
|
}
|
||||||
if len(chunks) == 0 {
|
if len(chunks) == 0 {
|
||||||
|
logger.Infof(ctx, "wiki ingest: document %s has no chunks, skip", knowledgeID)
|
||||||
return nil, nil
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
content := reconstructContent(chunks)
|
content := reconstructContent(chunks)
|
||||||
|
rawRuneCount := len([]rune(content))
|
||||||
if len([]rune(content)) > maxContentForWiki {
|
if len([]rune(content)) > maxContentForWiki {
|
||||||
content = string([]rune(content)[:maxContentForWiki])
|
content = string([]rune(content)[:maxContentForWiki])
|
||||||
}
|
}
|
||||||
|
logger.Infof(ctx,
|
||||||
|
"wiki ingest: doc %s chunks=%d content_len(raw=%d,truncated=%d) content_preview=%q",
|
||||||
|
knowledgeID, len(chunks), rawRuneCount, len([]rune(content)), previewText(content, 120))
|
||||||
|
|
||||||
// Get document title
|
// Get document title
|
||||||
docTitle := knowledgeID
|
docTitle := knowledgeID
|
||||||
@@ -561,15 +760,11 @@ func (s *wikiIngestService) processOneDocument(
|
|||||||
oldPageSlugs := s.getExistingPageSlugsForKnowledge(ctx, payload.KnowledgeBaseID, knowledgeID)
|
oldPageSlugs := s.getExistingPageSlugsForKnowledge(ctx, payload.KnowledgeBaseID, knowledgeID)
|
||||||
|
|
||||||
// Build a per-doc payload for functions that still need KnowledgeID
|
// Build a per-doc payload for functions that still need KnowledgeID
|
||||||
docPayload := WikiIngestPayload{
|
// (docPayload removed as WikiIngestPayload no longer holds KnowledgeID)
|
||||||
TenantID: payload.TenantID,
|
|
||||||
KnowledgeBaseID: payload.KnowledgeBaseID,
|
|
||||||
KnowledgeID: knowledgeID,
|
|
||||||
Language: payload.Language,
|
|
||||||
}
|
|
||||||
|
|
||||||
// Step 1: Extract entities and concepts
|
// Step 1: Extract entities and concepts
|
||||||
extractedPages, slugItems, err := s.extractEntitiesAndConcepts(ctx, chatModel, content, docTitle, lang, docPayload, sourceRef, oldPageSlugs)
|
logger.Infof(ctx, "wiki ingest: extracting entities and concepts for %s", knowledgeID)
|
||||||
|
extractedPages, slugItems, err := s.extractEntitiesAndConcepts(ctx, chatModel, content, docTitle, lang, payload, sourceRef, oldPageSlugs)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warnf(ctx, "wiki ingest: knowledge extraction failed for %s: %v", knowledgeID, err)
|
logger.Warnf(ctx, "wiki ingest: knowledge extraction failed for %s: %v", knowledgeID, err)
|
||||||
} else {
|
} else {
|
||||||
@@ -577,6 +772,7 @@ func (s *wikiIngestService) processOneDocument(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Step 2: Generate summary page
|
// Step 2: Generate summary page
|
||||||
|
logger.Infof(ctx, "wiki ingest: generating summary page for %s", knowledgeID)
|
||||||
summarySlug := fmt.Sprintf("summary/%s", slugify(docTitle))
|
summarySlug := fmt.Sprintf("summary/%s", slugify(docTitle))
|
||||||
var slugListing string
|
var slugListing string
|
||||||
for _, slug := range extractedPages {
|
for _, slug := range extractedPages {
|
||||||
@@ -609,7 +805,26 @@ func (s *wikiIngestService) processOneDocument(
|
|||||||
sumLine = docTitle
|
sumLine = docTitle
|
||||||
}
|
}
|
||||||
docSummaryLine = sumLine
|
docSummaryLine = sumLine
|
||||||
_, err := s.wikiService.CreatePage(ctx, &types.WikiPage{
|
logger.Infof(ctx, "wiki ingest: summary preview for %s => line=%q body=%q",
|
||||||
|
knowledgeID, previewText(sumLine, 100), previewText(sumBody, 140))
|
||||||
|
|
||||||
|
existingSummary, err := s.wikiService.GetPageBySlug(ctx, payload.KnowledgeBaseID, summarySlug)
|
||||||
|
if err == nil && existingSummary != nil {
|
||||||
|
// Update existing summary page (idempotent for retries)
|
||||||
|
existingSummary.Title = docTitle + " - Summary"
|
||||||
|
existingSummary.Content = sumBody
|
||||||
|
existingSummary.Summary = sumLine
|
||||||
|
existingSummary.Status = types.WikiPageStatusDraft
|
||||||
|
existingSummary.SourceRefs = appendUnique(existingSummary.SourceRefs, sourceRef)
|
||||||
|
|
||||||
|
if _, err := s.wikiService.UpdatePage(ctx, existingSummary); err != nil {
|
||||||
|
logger.Warnf(ctx, "wiki ingest: update summary page failed for %s: %v", knowledgeID, err)
|
||||||
|
} else {
|
||||||
|
pagesAffected = append(pagesAffected, summarySlug)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Create new summary page
|
||||||
|
_, err = s.wikiService.CreatePage(ctx, &types.WikiPage{
|
||||||
ID: uuid.New().String(),
|
ID: uuid.New().String(),
|
||||||
TenantID: payload.TenantID,
|
TenantID: payload.TenantID,
|
||||||
KnowledgeBaseID: payload.KnowledgeBaseID,
|
KnowledgeBaseID: payload.KnowledgeBaseID,
|
||||||
@@ -627,11 +842,21 @@ func (s *wikiIngestService) processOneDocument(
|
|||||||
pagesAffected = append(pagesAffected, summarySlug)
|
pagesAffected = append(pagesAffected, summarySlug)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Retract stale pages (pages this doc previously contributed to but no longer does)
|
// Retract stale pages (pages this doc previously contributed to but no longer does)
|
||||||
s.retractStalePages(ctx, chatModel, docPayload, oldPageSlugs, pagesAffected, docTitle, content, lang)
|
logger.Infof(ctx, "wiki ingest: retracting stale pages for %s", knowledgeID)
|
||||||
|
s.retractStalePages(ctx, chatModel, payload, knowledgeID, oldPageSlugs, pagesAffected, docTitle, content, lang)
|
||||||
|
|
||||||
logger.Infof(ctx, "wiki ingest: processed knowledge %s, %d pages affected", knowledgeID, len(pagesAffected))
|
logger.Infof(ctx,
|
||||||
|
"wiki ingest: processed knowledge %s title=%q affected_pages=%d page_preview=%s extracted_pages=%s elapsed=%s",
|
||||||
|
knowledgeID,
|
||||||
|
previewText(docTitle, 80),
|
||||||
|
len(pagesAffected),
|
||||||
|
previewStringSlice(pagesAffected, 6),
|
||||||
|
previewStringSlice(extractedPages, 6),
|
||||||
|
time.Since(docStartedAt).Round(time.Millisecond),
|
||||||
|
)
|
||||||
return &docIngestResult{
|
return &docIngestResult{
|
||||||
KnowledgeID: knowledgeID,
|
KnowledgeID: knowledgeID,
|
||||||
DocTitle: docTitle,
|
DocTitle: docTitle,
|
||||||
@@ -640,6 +865,41 @@ func (s *wikiIngestService) processOneDocument(
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func previewText(s string, maxRunes int) string {
|
||||||
|
s = strings.TrimSpace(s)
|
||||||
|
s = strings.ReplaceAll(s, "\n", " ")
|
||||||
|
s = strings.ReplaceAll(s, "\t", " ")
|
||||||
|
for strings.Contains(s, " ") {
|
||||||
|
s = strings.ReplaceAll(s, " ", " ")
|
||||||
|
}
|
||||||
|
r := []rune(s)
|
||||||
|
if maxRunes <= 0 || len(r) <= maxRunes {
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
return string(r[:maxRunes]) + "...(truncated)"
|
||||||
|
}
|
||||||
|
|
||||||
|
func previewStringSlice(items []string, limit int) string {
|
||||||
|
if len(items) == 0 {
|
||||||
|
return "[]"
|
||||||
|
}
|
||||||
|
if limit <= 0 {
|
||||||
|
limit = 1
|
||||||
|
}
|
||||||
|
n := len(items)
|
||||||
|
if n > limit {
|
||||||
|
items = items[:limit]
|
||||||
|
}
|
||||||
|
out := make([]string, 0, len(items))
|
||||||
|
for _, it := range items {
|
||||||
|
out = append(out, previewText(it, 48))
|
||||||
|
}
|
||||||
|
if n > limit {
|
||||||
|
return fmt.Sprintf("[%s ...(+%d)]", strings.Join(out, ", "), n-limit)
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("[%s]", strings.Join(out, ", "))
|
||||||
|
}
|
||||||
|
|
||||||
// cleanDeadLinks removes [[wiki-links]] that point to archived or deleted pages.
|
// cleanDeadLinks removes [[wiki-links]] that point to archived or deleted pages.
|
||||||
// Scans all published pages, checks each out_link, and removes references to
|
// Scans all published pages, checks each out_link, and removes references to
|
||||||
// pages that no longer exist or are archived. No LLM call — pure text cleanup.
|
// pages that no longer exist or are archived. No LLM call — pure text cleanup.
|
||||||
@@ -703,7 +963,7 @@ func (s *wikiIngestService) cleanDeadLinks(ctx context.Context, kbID string) {
|
|||||||
|
|
||||||
// injectCrossLinks scans affected pages and injects [[wiki-links]] for mentions
|
// injectCrossLinks scans affected pages and injects [[wiki-links]] for mentions
|
||||||
// of other wiki page titles in the content. Pure text replacement, no LLM call.
|
// of other wiki page titles in the content. Pure text replacement, no LLM call.
|
||||||
// Only processes entity/concept/synthesis/comparison pages (not index/log/summary).
|
// Processes entity/concept/synthesis/comparison and summary pages (not index/log).
|
||||||
func (s *wikiIngestService) injectCrossLinks(ctx context.Context, kbID string, affectedSlugs []string) {
|
func (s *wikiIngestService) injectCrossLinks(ctx context.Context, kbID string, affectedSlugs []string) {
|
||||||
// Build a title→slug lookup from ALL pages in this KB
|
// Build a title→slug lookup from ALL pages in this KB
|
||||||
allPages, err := s.wikiService.ListAllPages(ctx, kbID)
|
allPages, err := s.wikiService.ListAllPages(ctx, kbID)
|
||||||
@@ -754,8 +1014,8 @@ func (s *wikiIngestService) injectCrossLinks(ctx context.Context, kbID string, a
|
|||||||
if !affectedSet[p.Slug] {
|
if !affectedSet[p.Slug] {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
// Skip system pages and summary (summary already has links from the prompt)
|
// Skip system pages (index, log). We allow summary to be processed so it gets links to other KB entities.
|
||||||
if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog || p.PageType == types.WikiPageTypeSummary {
|
if p.PageType == types.WikiPageTypeIndex || p.PageType == types.WikiPageTypeLog {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -856,6 +1116,7 @@ func (s *wikiIngestService) retractStalePages(
|
|||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
chatModel chat.Chat,
|
chatModel chat.Chat,
|
||||||
payload WikiIngestPayload,
|
payload WikiIngestPayload,
|
||||||
|
knowledgeID string,
|
||||||
oldSlugs map[string]bool,
|
oldSlugs map[string]bool,
|
||||||
newSlugs []string,
|
newSlugs []string,
|
||||||
docTitle, docContent, lang string,
|
docTitle, docContent, lang string,
|
||||||
@@ -884,8 +1145,8 @@ func (s *wikiIngestService) retractStalePages(
|
|||||||
logger.Infof(ctx, "wiki ingest: %d stale pages detected after document update: %v", len(staleSlugs), staleSlugs)
|
logger.Infof(ctx, "wiki ingest: %d stale pages detected after document update: %v", len(staleSlugs), staleSlugs)
|
||||||
|
|
||||||
var retractSlugs []string
|
var retractSlugs []string
|
||||||
sourceRef := fmt.Sprintf("%s|%s", payload.KnowledgeID, docTitle)
|
sourceRef := fmt.Sprintf("%s|%s", knowledgeID, docTitle)
|
||||||
prefix := payload.KnowledgeID + "|"
|
prefix := knowledgeID + "|"
|
||||||
|
|
||||||
for _, slug := range staleSlugs {
|
for _, slug := range staleSlugs {
|
||||||
page, err := s.wikiService.GetPageBySlug(ctx, payload.KnowledgeBaseID, slug)
|
page, err := s.wikiService.GetPageBySlug(ctx, payload.KnowledgeBaseID, slug)
|
||||||
@@ -896,7 +1157,7 @@ func (s *wikiIngestService) retractStalePages(
|
|||||||
// Remove this doc's source ref
|
// Remove this doc's source ref
|
||||||
var remaining types.StringArray
|
var remaining types.StringArray
|
||||||
for _, ref := range page.SourceRefs {
|
for _, ref := range page.SourceRefs {
|
||||||
if ref == payload.KnowledgeID || ref == sourceRef || strings.HasPrefix(ref, prefix) {
|
if ref == knowledgeID || ref == sourceRef || strings.HasPrefix(ref, prefix) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
remaining = append(remaining, ref)
|
remaining = append(remaining, ref)
|
||||||
@@ -980,18 +1241,22 @@ func (s *wikiIngestService) extractEntitiesAndConcepts(
|
|||||||
extractionJSON = strings.TrimSuffix(extractionJSON, "```")
|
extractionJSON = strings.TrimSuffix(extractionJSON, "```")
|
||||||
extractionJSON = strings.TrimSpace(extractionJSON)
|
extractionJSON = strings.TrimSpace(extractionJSON)
|
||||||
|
|
||||||
|
extractionJSON = sanitizeJSONString(extractionJSON)
|
||||||
|
|
||||||
var result combinedExtraction
|
var result combinedExtraction
|
||||||
if err := json.Unmarshal([]byte(extractionJSON), &result); err != nil {
|
if err := json.Unmarshal([]byte(extractionJSON), &result); err != nil {
|
||||||
logger.Warnf(ctx, "wiki ingest: failed to parse combined extraction JSON: %v\nRaw: %s", err, truncateString(extractionJSON, 500))
|
logger.Warnf(ctx, "wiki ingest: failed to parse combined extraction JSON: %v\nRaw: %s", err, extractionJSON)
|
||||||
return nil, nil, fmt.Errorf("parse combined extraction JSON: %w", err)
|
return nil, nil, fmt.Errorf("parse combined extraction JSON: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var affected []string
|
var affected []string
|
||||||
|
|
||||||
// Deduplicate entities against existing wiki pages (LLM-based)
|
// Deduplicate entities against existing wiki pages (LLM-based)
|
||||||
|
logger.Infof(ctx, "wiki ingest: deduplicating %d entities", len(result.Entities))
|
||||||
result.Entities = s.deduplicateItems(ctx, chatModel, result.Entities, types.WikiPageTypeEntity, payload.KnowledgeBaseID)
|
result.Entities = s.deduplicateItems(ctx, chatModel, result.Entities, types.WikiPageTypeEntity, payload.KnowledgeBaseID)
|
||||||
|
|
||||||
// Deduplicate concepts against existing wiki pages (LLM-based)
|
// Deduplicate concepts against existing wiki pages (LLM-based)
|
||||||
|
logger.Infof(ctx, "wiki ingest: deduplicating %d concepts", len(result.Concepts))
|
||||||
result.Concepts = s.deduplicateItems(ctx, chatModel, result.Concepts, types.WikiPageTypeConcept, payload.KnowledgeBaseID)
|
result.Concepts = s.deduplicateItems(ctx, chatModel, result.Concepts, types.WikiPageTypeConcept, payload.KnowledgeBaseID)
|
||||||
|
|
||||||
// Build slug→item map for wiki-link generation in summary pages
|
// Build slug→item map for wiki-link generation in summary pages
|
||||||
@@ -1008,6 +1273,7 @@ func (s *wikiIngestService) extractEntitiesAndConcepts(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Upsert entity pages
|
// Upsert entity pages
|
||||||
|
logger.Infof(ctx, "wiki ingest: upserting %d entity pages", len(result.Entities))
|
||||||
entitySlugs, err := s.upsertExtractedPages(ctx, chatModel, result.Entities, types.WikiPageTypeEntity, docTitle, lang, payload, sourceRef)
|
entitySlugs, err := s.upsertExtractedPages(ctx, chatModel, result.Entities, types.WikiPageTypeEntity, docTitle, lang, payload, sourceRef)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warnf(ctx, "wiki ingest: entity upsert failed: %v", err)
|
logger.Warnf(ctx, "wiki ingest: entity upsert failed: %v", err)
|
||||||
@@ -1016,6 +1282,7 @@ func (s *wikiIngestService) extractEntitiesAndConcepts(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Upsert concept pages
|
// Upsert concept pages
|
||||||
|
logger.Infof(ctx, "wiki ingest: upserting %d concept pages", len(result.Concepts))
|
||||||
conceptSlugs, err := s.upsertExtractedPages(ctx, chatModel, result.Concepts, types.WikiPageTypeConcept, docTitle, lang, payload, sourceRef)
|
conceptSlugs, err := s.upsertExtractedPages(ctx, chatModel, result.Concepts, types.WikiPageTypeConcept, docTitle, lang, payload, sourceRef)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Warnf(ctx, "wiki ingest: concept upsert failed: %v", err)
|
logger.Warnf(ctx, "wiki ingest: concept upsert failed: %v", err)
|
||||||
@@ -1258,7 +1525,7 @@ func splitSummaryLine(raw string) (summary string, content string) {
|
|||||||
// appendLogEntry appends a structured, grep-parseable entry to the log page.
|
// appendLogEntry appends a structured, grep-parseable entry to the log page.
|
||||||
// Format: ## [2026-04-07 19:50:02] action | title
|
// Format: ## [2026-04-07 19:50:02] action | title
|
||||||
// Followed by key-value metadata lines. No sub-headings — keeps `grep "^## \[" log.md` clean.
|
// Followed by key-value metadata lines. No sub-headings — keeps `grep "^## \[" log.md` clean.
|
||||||
func (s *wikiIngestService) appendLogEntry(ctx context.Context, payload WikiIngestPayload, action, docTitle string, pagesAffected []string, extra string) {
|
func (s *wikiIngestService) appendLogEntry(ctx context.Context, payload WikiIngestPayload, action, knowledgeID, docTitle string, pagesAffected []string, extra string) {
|
||||||
logPage, _ := s.wikiService.GetLog(ctx, payload.KnowledgeBaseID)
|
logPage, _ := s.wikiService.GetLog(ctx, payload.KnowledgeBaseID)
|
||||||
if logPage == nil {
|
if logPage == nil {
|
||||||
return
|
return
|
||||||
@@ -1270,7 +1537,9 @@ func (s *wikiIngestService) appendLogEntry(ctx context.Context, payload WikiInge
|
|||||||
action,
|
action,
|
||||||
docTitle,
|
docTitle,
|
||||||
)
|
)
|
||||||
fmt.Fprintf(&sb, "- **Source**: knowledge/%s\n", payload.KnowledgeID)
|
if knowledgeID != "" {
|
||||||
|
fmt.Fprintf(&sb, "- **Source**: knowledge/%s\n", knowledgeID)
|
||||||
|
}
|
||||||
if len(pagesAffected) > 0 {
|
if len(pagesAffected) > 0 {
|
||||||
fmt.Fprintf(&sb, "- **Pages affected**: %d (%s)\n", len(pagesAffected), strings.Join(pagesAffected, ", "))
|
fmt.Fprintf(&sb, "- **Pages affected**: %d (%s)\n", len(pagesAffected), strings.Join(pagesAffected, ", "))
|
||||||
}
|
}
|
||||||
@@ -1368,11 +1637,13 @@ func (s *wikiIngestService) deduplicateItems(
|
|||||||
dedupeJSON = strings.TrimSuffix(dedupeJSON, "```")
|
dedupeJSON = strings.TrimSuffix(dedupeJSON, "```")
|
||||||
dedupeJSON = strings.TrimSpace(dedupeJSON)
|
dedupeJSON = strings.TrimSpace(dedupeJSON)
|
||||||
|
|
||||||
|
dedupeJSON = sanitizeJSONString(dedupeJSON)
|
||||||
|
|
||||||
var dedupeResult struct {
|
var dedupeResult struct {
|
||||||
Merges map[string]string `json:"merges"`
|
Merges map[string]string `json:"merges"`
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal([]byte(dedupeJSON), &dedupeResult); err != nil {
|
if err := json.Unmarshal([]byte(dedupeJSON), &dedupeResult); err != nil {
|
||||||
logger.Warnf(ctx, "wiki ingest: failed to parse dedup JSON: %v", err)
|
logger.Warnf(ctx, "wiki ingest: failed to parse dedup JSON: %v\nRaw: %s", err, dedupeJSON)
|
||||||
return items
|
return items
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1560,3 +1831,53 @@ func appendUnique(arr types.StringArray, s string) types.StringArray {
|
|||||||
}
|
}
|
||||||
return append(arr, s)
|
return append(arr, s)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// sanitizeJSONString sanitizes a string that is intended to be parsed as JSON,
|
||||||
|
// by properly escaping unescaped control characters (like newlines) inside string literals.
|
||||||
|
func sanitizeJSONString(s string) string {
|
||||||
|
var buf strings.Builder
|
||||||
|
buf.Grow(len(s))
|
||||||
|
inString := false
|
||||||
|
escape := false
|
||||||
|
for _, r := range s {
|
||||||
|
if escape {
|
||||||
|
if r == '\n' {
|
||||||
|
buf.WriteString(`n`)
|
||||||
|
} else if r == '\r' {
|
||||||
|
buf.WriteString(`r`)
|
||||||
|
} else if r == '\t' {
|
||||||
|
buf.WriteString(`t`)
|
||||||
|
} else {
|
||||||
|
buf.WriteRune(r)
|
||||||
|
}
|
||||||
|
escape = false
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if r == '\\' {
|
||||||
|
escape = true
|
||||||
|
buf.WriteRune(r)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if r == '"' {
|
||||||
|
inString = !inString
|
||||||
|
buf.WriteRune(r)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if inString {
|
||||||
|
if r == '\n' {
|
||||||
|
buf.WriteString(`\n`)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if r == '\r' {
|
||||||
|
buf.WriteString(`\r`)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if r == '\t' {
|
||||||
|
buf.WriteString(`\t`)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buf.WriteRune(r)
|
||||||
|
}
|
||||||
|
return buf.String()
|
||||||
|
}
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import (
|
|||||||
"github.com/Tencent/WeKnora/internal/types"
|
"github.com/Tencent/WeKnora/internal/types"
|
||||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
|
"github.com/redis/go-redis/v9"
|
||||||
)
|
)
|
||||||
|
|
||||||
// wikiLinkRegex matches [[wiki-link]] syntax in markdown content
|
// wikiLinkRegex matches [[wiki-link]] syntax in markdown content
|
||||||
@@ -23,6 +24,7 @@ type wikiPageService struct {
|
|||||||
repo interfaces.WikiPageRepository
|
repo interfaces.WikiPageRepository
|
||||||
chunkRepo interfaces.ChunkRepository
|
chunkRepo interfaces.ChunkRepository
|
||||||
kbService interfaces.KnowledgeBaseService
|
kbService interfaces.KnowledgeBaseService
|
||||||
|
redisClient *redis.Client
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewWikiPageService creates a new wiki page service
|
// NewWikiPageService creates a new wiki page service
|
||||||
@@ -30,11 +32,13 @@ func NewWikiPageService(
|
|||||||
repo interfaces.WikiPageRepository,
|
repo interfaces.WikiPageRepository,
|
||||||
chunkRepo interfaces.ChunkRepository,
|
chunkRepo interfaces.ChunkRepository,
|
||||||
kbService interfaces.KnowledgeBaseService,
|
kbService interfaces.KnowledgeBaseService,
|
||||||
|
redisClient *redis.Client,
|
||||||
) interfaces.WikiPageService {
|
) interfaces.WikiPageService {
|
||||||
return &wikiPageService{
|
return &wikiPageService{
|
||||||
repo: repo,
|
repo: repo,
|
||||||
chunkRepo: chunkRepo,
|
chunkRepo: chunkRepo,
|
||||||
kbService: kbService,
|
kbService: kbService,
|
||||||
|
redisClient: redisClient,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -283,12 +287,22 @@ func (s *wikiPageService) GetStats(ctx context.Context, kbID string) (*types.Wik
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var pendingTasks int64
|
||||||
|
var isActive bool
|
||||||
|
if s.redisClient != nil {
|
||||||
|
pendingTasks, _ = s.redisClient.LLen(ctx, "wiki:pending:"+kbID).Result()
|
||||||
|
activeFlag, _ := s.redisClient.Exists(ctx, "wiki:active:"+kbID).Result()
|
||||||
|
isActive = activeFlag > 0
|
||||||
|
}
|
||||||
|
|
||||||
return &types.WikiStats{
|
return &types.WikiStats{
|
||||||
TotalPages: total,
|
TotalPages: total,
|
||||||
PagesByType: counts,
|
PagesByType: counts,
|
||||||
TotalLinks: totalLinks,
|
TotalLinks: totalLinks,
|
||||||
OrphanCount: orphans,
|
OrphanCount: orphans,
|
||||||
RecentUpdates: recentPages,
|
RecentUpdates: recentPages,
|
||||||
|
PendingTasks: pendingTasks,
|
||||||
|
IsActive: isActive,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -37,8 +37,8 @@ func TestIsIconImage(t *testing.T) {
|
|||||||
expect bool
|
expect bool
|
||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "tiny bytes (< 2KB)",
|
name: "tiny bytes (< 512B)",
|
||||||
data: make([]byte, 1024),
|
data: make([]byte, 256),
|
||||||
expect: true,
|
expect: true,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -102,6 +102,5 @@ func RegisterSyncHandlers(params SyncTaskParams) {
|
|||||||
params.Executor.RegisterHandler(types.TypeKnowledgePostProcess, params.KnowledgePostProcess.Handle)
|
params.Executor.RegisterHandler(types.TypeKnowledgePostProcess, params.KnowledgePostProcess.Handle)
|
||||||
params.Executor.RegisterHandler(types.TypeDataSourceSync, params.DataSourceService.ProcessSync)
|
params.Executor.RegisterHandler(types.TypeDataSourceSync, params.DataSourceService.ProcessSync)
|
||||||
params.Executor.RegisterHandler(types.TypeWikiIngest, params.WikiIngest.Handle)
|
params.Executor.RegisterHandler(types.TypeWikiIngest, params.WikiIngest.Handle)
|
||||||
params.Executor.RegisterHandler(types.TypeWikiRetract, params.WikiIngest.Handle)
|
|
||||||
logger.Infof(context.Background(), "[SyncTask] All task handlers registered (Lite mode, no Redis)")
|
logger.Infof(context.Background(), "[SyncTask] All task handlers registered (Lite mode, no Redis)")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -119,7 +119,6 @@ func RunAsynqServer(params AsynqTaskParams) *asynq.ServeMux {
|
|||||||
|
|
||||||
// Register wiki ingest handler
|
// Register wiki ingest handler
|
||||||
mux.HandleFunc(types.TypeWikiIngest, params.WikiIngest.Handle)
|
mux.HandleFunc(types.TypeWikiIngest, params.WikiIngest.Handle)
|
||||||
mux.HandleFunc(types.TypeWikiRetract, params.WikiIngest.Handle)
|
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
// Start the server
|
// Start the server
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ const (
|
|||||||
TypeManualProcess = "manual:process" // 手工知识更新任务(cleanup + 重新索引)
|
TypeManualProcess = "manual:process" // 手工知识更新任务(cleanup + 重新索引)
|
||||||
TypeDataSourceSync = "datasource:sync" // 数据源同步任务
|
TypeDataSourceSync = "datasource:sync" // 数据源同步任务
|
||||||
TypeWikiIngest = "wiki:ingest" // Wiki 页面同步任务
|
TypeWikiIngest = "wiki:ingest" // Wiki 页面同步任务
|
||||||
TypeWikiRetract = "wiki:retract" // Wiki 内容回收任务(文档删除时)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// ExtractChunkPayload represents the extract chunk task payload
|
// ExtractChunkPayload represents the extract chunk task payload
|
||||||
|
|||||||
@@ -168,4 +168,6 @@ type WikiStats struct {
|
|||||||
TotalLinks int64 `json:"total_links"`
|
TotalLinks int64 `json:"total_links"`
|
||||||
OrphanCount int64 `json:"orphan_count"` // pages with no inbound links
|
OrphanCount int64 `json:"orphan_count"` // pages with no inbound links
|
||||||
RecentUpdates []*WikiPage `json:"recent_updates"` // last N updated pages
|
RecentUpdates []*WikiPage `json:"recent_updates"` // last N updated pages
|
||||||
|
PendingTasks int64 `json:"pending_tasks"` // number of documents waiting to be ingested
|
||||||
|
IsActive bool `json:"is_active"` // whether wiki ingestion is currently running
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ CREATE TABLE IF NOT EXISTS wiki_pages (
|
|||||||
in_links JSONB DEFAULT '[]'::JSONB,
|
in_links JSONB DEFAULT '[]'::JSONB,
|
||||||
out_links JSONB DEFAULT '[]'::JSONB,
|
out_links JSONB DEFAULT '[]'::JSONB,
|
||||||
page_metadata JSONB DEFAULT '{}'::JSONB,
|
page_metadata JSONB DEFAULT '{}'::JSONB,
|
||||||
|
aliases JSONB DEFAULT '[]'::JSONB,
|
||||||
version INT NOT NULL DEFAULT 1,
|
version INT NOT NULL DEFAULT 1,
|
||||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
||||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
||||||
|
|||||||
Reference in New Issue
Block a user