WeKnora/internal/application/service/knowledge_post_process.go

202 lines
7.3 KiB
Go
Raw Normal View History

package service
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/Tencent/WeKnora/internal/logger"
feat(observability): extend Langfuse tracing across asynq pipeline Previously the Langfuse integration only traced in-process HTTP requests (chat / search / eval), so file uploads and every downstream asynq task (document parse, chunk embedding, OCR/VLM, summary / question gen, wiki ingest, datasource sync, etc.) produced either disconnected shallow traces or no observation at all. This change threads one trace end-to-end: - tracer: add SPAN observation type and StartSpan; add ResumeTrace so a worker can attach to an upstream trace without emitting a duplicate trace-create; StartGeneration now auto-picks parentObservationId from ctx so nested trace -> span -> generation trees render correctly. - types.TracingContext + LangfuseTracingCarrier: embed on all 17 asynq payloads so trace_id / parent_obs_id / user_id / session_id serialise into every job. - langfuse.InjectTracing: injected at 28 enqueue sites before json.Marshal so the HTTP-layer trace survives the Redis hop. - langfuse.AsynqMiddleware: mux.Use hook that peeks the payload, either resumes the upstream trace or opens a standalone asynq.<type> trace for scheduled jobs, and wraps the handler in a SPAN with task metadata (id / queue / retry / payload_bytes) plus ERROR level on failure. - GinMiddleware.shouldTrace: whitelist ingestion / knowledge-mutation / FAQ / wiki / datasource endpoints so the root trace actually starts. - Tests: tracer_test.go covers span nesting, error status, and ResumeTrace no-trace-create guarantee; asynq_test.go covers InjectTracing round-trip, middleware resume path, and standalone trace fallback. - Docs: docs/Langfuse\u96c6\u6210.md now lists the covered task types and documents the cross-process propagation model. No behavioural change when Langfuse is disabled (all new code paths are no-ops and carriers serialise to empty strings with omitempty).
2026-04-24 04:23:30 +00:00
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/hibiken/asynq"
"github.com/redis/go-redis/v9"
)
// KnowledgePostProcessService acts as an orchestrator for all post-processing tasks
// after a document has been parsed and split into chunks (including multimodal OCR/Caption).
type KnowledgePostProcessService struct {
perf(wiki-ingest): scale to 4w-doc KBs + generic task queue / dead-letter The wiki ingest post-process pipeline OOM'd and ran for hours on KBs with ~40k documents. The dominant tail was a per-batch ListAllPages that pulled every page (multi-MB content blobs) into Go memory, plus a 24h-TTL Redis pending list whose data could be evicted before a long serialized backlog drained. dedup did O(P × N) Jaccard scoring in Go on every batch. Lint loaded the full graph. The index page kept the entire wiki directory in its content column and rewrote the TOAST chunk on every ingest. None of these survive at 4w docs. This change reworks the write path end to end and pulls the durable- queue + dead-letter primitives out of wiki and into shared infrastructure that every asynq task type now benefits from. - migration 000041: task_pending_ops + task_dead_letters tables, plus three GIN indexes on wiki_pages (source_refs jsonb_path_ops, source_refs text fallback, lower(title) trgm). - TaskPendingOpsRepository + TaskDeadLetterRepository in internal/application/repository/task_queue.go: cursor-paginated list, atomic IncrFailCount via UPDATE…RETURNING, dedup-key scoped delete that refuses empty keys so a buggy caller can't wipe a KB's queue. - internal/middleware/asynqdl: writes a task_dead_letters row when an asynq task exhausts its retry budget. Payload-agnostic — a small probe struct extracts TenantID + scope hints across every existing payload type, so summary:generation / image:multimodal / faq_import / kb:clone / etc. all dead-letter without per-handler code. Best-effort: an insert failure never masks the underlying task error. Installed in router/task.go before the langfuse mw so it sees raw errors. - Pending queue moved Redis → PG (no TTL, restart-durable). Redis keeps just the active-batch lock and the delete tombstone. - In-batch retry budget (wikiMaxFailRetries=5) tracked via pendingRepo.IncrFailCount; over the cap the row is moved to task_dead_letters with task_type=wiki:ingest, related_id=knowledge id. Asynq retries (10) are handled by the new middleware. - Removed the per-batch ListAllPages. WikiBatchContext now carries lazy fetcher closures (SlugTitleMany, SummaryByKnowledgeID) with mutex-protected caches; reduce reaches for titles / summaries on demand instead of pre-loading the whole KB. - getExistingPageSlugsForKnowledge now uses ListSlugsBySourceRef, which the new GIN index on source_refs serves as a Bitmap Index Scan instead of a sequential text LIKE. - Dedup pre-filter uses pg_trgm via FindSimilarPages (idx_wiki_pages_title_trgm). For each new entity/concept (and each of its aliases) we ask the DB for the top-K trigram-similar existing pages and union the results — bounded prompt size, no Go- side O(P × M) loop. Small KBs (≤25 entities) bypass the pre-filter. - cleanDeadLinks / injectCrossLinks are scoped to the batch's affected slugs (a few dozen) instead of every page in the KB. Both use the new lite ListBySlugs / ExistsSlugs repo methods so they pull only slug + title + outlinks, not full content. - Slug fuzzy resolve (slug_fuzzy.go): when the LLM emits [[bad-slug|display]] the cleanup path now tries display-text reverse lookup → hyphen/case normalized equality → char-bigram Jaccard ≥ 0.8 before stripping. Recovers the common pinyin-word- break drift case ("shang-hai-tower" vs "shanghai-tower") in place instead of replacing the link with plain text. - rebuildIndexPage uses ListByTypeRecent(200) for the first-time intro and drops the full DocumentSummaries blob from the incremental update prompt, so its context stays bounded regardless of KB size. - Concurrency tunables surfaced in WikiConfig: IngestBatchSize / IngestMapParallel / IngestReduceParallel, with sensible defaults via OrDefault helpers. scheduleFollowUp drops to ProcessIn(0) so follow-ups don't waste asynq retry slots bouncing on the active lock. - RunLint walks pages via the new ListPagesCursor in 200-page windows and computes the live-slug set with a one-column ListAllSlugs Pluck instead of a Limit:0 GetGraph that materialized every node + edge. Memory is now bounded; 40k pages walks in constant ~4MB. - 14 GORM tests for both repos against an in-memory SQLite mirror of the production DDL (task_queue_test.go). - 6 tests for the dead-letter middleware covering retry budget detection, payload-agnostic scope inference, error truncation, and repo-failure isolation. - 7 tests for the slug fuzzy resolve helper covering the three resolution stages, display-text priority over normalized equality, bigram fallback acceptance, and rejection of unrelated slugs. - Existing wiki_ingest / wiki_lint / wiki_page tests updated to the new fetcher / cursor APIs.
2026-05-09 15:42:53 +00:00
knowledgeRepo interfaces.KnowledgeRepository
kbService interfaces.KnowledgeBaseService
chunkService interfaces.ChunkService
taskEnqueuer interfaces.TaskEnqueuer
pendingRepo interfaces.TaskPendingOpsRepository
redisClient *redis.Client
}
func NewKnowledgePostProcessService(
knowledgeRepo interfaces.KnowledgeRepository,
kbService interfaces.KnowledgeBaseService,
chunkService interfaces.ChunkService,
taskEnqueuer interfaces.TaskEnqueuer,
perf(wiki-ingest): scale to 4w-doc KBs + generic task queue / dead-letter The wiki ingest post-process pipeline OOM'd and ran for hours on KBs with ~40k documents. The dominant tail was a per-batch ListAllPages that pulled every page (multi-MB content blobs) into Go memory, plus a 24h-TTL Redis pending list whose data could be evicted before a long serialized backlog drained. dedup did O(P × N) Jaccard scoring in Go on every batch. Lint loaded the full graph. The index page kept the entire wiki directory in its content column and rewrote the TOAST chunk on every ingest. None of these survive at 4w docs. This change reworks the write path end to end and pulls the durable- queue + dead-letter primitives out of wiki and into shared infrastructure that every asynq task type now benefits from. - migration 000041: task_pending_ops + task_dead_letters tables, plus three GIN indexes on wiki_pages (source_refs jsonb_path_ops, source_refs text fallback, lower(title) trgm). - TaskPendingOpsRepository + TaskDeadLetterRepository in internal/application/repository/task_queue.go: cursor-paginated list, atomic IncrFailCount via UPDATE…RETURNING, dedup-key scoped delete that refuses empty keys so a buggy caller can't wipe a KB's queue. - internal/middleware/asynqdl: writes a task_dead_letters row when an asynq task exhausts its retry budget. Payload-agnostic — a small probe struct extracts TenantID + scope hints across every existing payload type, so summary:generation / image:multimodal / faq_import / kb:clone / etc. all dead-letter without per-handler code. Best-effort: an insert failure never masks the underlying task error. Installed in router/task.go before the langfuse mw so it sees raw errors. - Pending queue moved Redis → PG (no TTL, restart-durable). Redis keeps just the active-batch lock and the delete tombstone. - In-batch retry budget (wikiMaxFailRetries=5) tracked via pendingRepo.IncrFailCount; over the cap the row is moved to task_dead_letters with task_type=wiki:ingest, related_id=knowledge id. Asynq retries (10) are handled by the new middleware. - Removed the per-batch ListAllPages. WikiBatchContext now carries lazy fetcher closures (SlugTitleMany, SummaryByKnowledgeID) with mutex-protected caches; reduce reaches for titles / summaries on demand instead of pre-loading the whole KB. - getExistingPageSlugsForKnowledge now uses ListSlugsBySourceRef, which the new GIN index on source_refs serves as a Bitmap Index Scan instead of a sequential text LIKE. - Dedup pre-filter uses pg_trgm via FindSimilarPages (idx_wiki_pages_title_trgm). For each new entity/concept (and each of its aliases) we ask the DB for the top-K trigram-similar existing pages and union the results — bounded prompt size, no Go- side O(P × M) loop. Small KBs (≤25 entities) bypass the pre-filter. - cleanDeadLinks / injectCrossLinks are scoped to the batch's affected slugs (a few dozen) instead of every page in the KB. Both use the new lite ListBySlugs / ExistsSlugs repo methods so they pull only slug + title + outlinks, not full content. - Slug fuzzy resolve (slug_fuzzy.go): when the LLM emits [[bad-slug|display]] the cleanup path now tries display-text reverse lookup → hyphen/case normalized equality → char-bigram Jaccard ≥ 0.8 before stripping. Recovers the common pinyin-word- break drift case ("shang-hai-tower" vs "shanghai-tower") in place instead of replacing the link with plain text. - rebuildIndexPage uses ListByTypeRecent(200) for the first-time intro and drops the full DocumentSummaries blob from the incremental update prompt, so its context stays bounded regardless of KB size. - Concurrency tunables surfaced in WikiConfig: IngestBatchSize / IngestMapParallel / IngestReduceParallel, with sensible defaults via OrDefault helpers. scheduleFollowUp drops to ProcessIn(0) so follow-ups don't waste asynq retry slots bouncing on the active lock. - RunLint walks pages via the new ListPagesCursor in 200-page windows and computes the live-slug set with a one-column ListAllSlugs Pluck instead of a Limit:0 GetGraph that materialized every node + edge. Memory is now bounded; 40k pages walks in constant ~4MB. - 14 GORM tests for both repos against an in-memory SQLite mirror of the production DDL (task_queue_test.go). - 6 tests for the dead-letter middleware covering retry budget detection, payload-agnostic scope inference, error truncation, and repo-failure isolation. - 7 tests for the slug fuzzy resolve helper covering the three resolution stages, display-text priority over normalized equality, bigram fallback acceptance, and rejection of unrelated slugs. - Existing wiki_ingest / wiki_lint / wiki_page tests updated to the new fetcher / cursor APIs.
2026-05-09 15:42:53 +00:00
pendingRepo interfaces.TaskPendingOpsRepository,
redisClient *redis.Client,
) interfaces.TaskHandler {
return &KnowledgePostProcessService{
knowledgeRepo: knowledgeRepo,
kbService: kbService,
chunkService: chunkService,
taskEnqueuer: taskEnqueuer,
perf(wiki-ingest): scale to 4w-doc KBs + generic task queue / dead-letter The wiki ingest post-process pipeline OOM'd and ran for hours on KBs with ~40k documents. The dominant tail was a per-batch ListAllPages that pulled every page (multi-MB content blobs) into Go memory, plus a 24h-TTL Redis pending list whose data could be evicted before a long serialized backlog drained. dedup did O(P × N) Jaccard scoring in Go on every batch. Lint loaded the full graph. The index page kept the entire wiki directory in its content column and rewrote the TOAST chunk on every ingest. None of these survive at 4w docs. This change reworks the write path end to end and pulls the durable- queue + dead-letter primitives out of wiki and into shared infrastructure that every asynq task type now benefits from. - migration 000041: task_pending_ops + task_dead_letters tables, plus three GIN indexes on wiki_pages (source_refs jsonb_path_ops, source_refs text fallback, lower(title) trgm). - TaskPendingOpsRepository + TaskDeadLetterRepository in internal/application/repository/task_queue.go: cursor-paginated list, atomic IncrFailCount via UPDATE…RETURNING, dedup-key scoped delete that refuses empty keys so a buggy caller can't wipe a KB's queue. - internal/middleware/asynqdl: writes a task_dead_letters row when an asynq task exhausts its retry budget. Payload-agnostic — a small probe struct extracts TenantID + scope hints across every existing payload type, so summary:generation / image:multimodal / faq_import / kb:clone / etc. all dead-letter without per-handler code. Best-effort: an insert failure never masks the underlying task error. Installed in router/task.go before the langfuse mw so it sees raw errors. - Pending queue moved Redis → PG (no TTL, restart-durable). Redis keeps just the active-batch lock and the delete tombstone. - In-batch retry budget (wikiMaxFailRetries=5) tracked via pendingRepo.IncrFailCount; over the cap the row is moved to task_dead_letters with task_type=wiki:ingest, related_id=knowledge id. Asynq retries (10) are handled by the new middleware. - Removed the per-batch ListAllPages. WikiBatchContext now carries lazy fetcher closures (SlugTitleMany, SummaryByKnowledgeID) with mutex-protected caches; reduce reaches for titles / summaries on demand instead of pre-loading the whole KB. - getExistingPageSlugsForKnowledge now uses ListSlugsBySourceRef, which the new GIN index on source_refs serves as a Bitmap Index Scan instead of a sequential text LIKE. - Dedup pre-filter uses pg_trgm via FindSimilarPages (idx_wiki_pages_title_trgm). For each new entity/concept (and each of its aliases) we ask the DB for the top-K trigram-similar existing pages and union the results — bounded prompt size, no Go- side O(P × M) loop. Small KBs (≤25 entities) bypass the pre-filter. - cleanDeadLinks / injectCrossLinks are scoped to the batch's affected slugs (a few dozen) instead of every page in the KB. Both use the new lite ListBySlugs / ExistsSlugs repo methods so they pull only slug + title + outlinks, not full content. - Slug fuzzy resolve (slug_fuzzy.go): when the LLM emits [[bad-slug|display]] the cleanup path now tries display-text reverse lookup → hyphen/case normalized equality → char-bigram Jaccard ≥ 0.8 before stripping. Recovers the common pinyin-word- break drift case ("shang-hai-tower" vs "shanghai-tower") in place instead of replacing the link with plain text. - rebuildIndexPage uses ListByTypeRecent(200) for the first-time intro and drops the full DocumentSummaries blob from the incremental update prompt, so its context stays bounded regardless of KB size. - Concurrency tunables surfaced in WikiConfig: IngestBatchSize / IngestMapParallel / IngestReduceParallel, with sensible defaults via OrDefault helpers. scheduleFollowUp drops to ProcessIn(0) so follow-ups don't waste asynq retry slots bouncing on the active lock. - RunLint walks pages via the new ListPagesCursor in 200-page windows and computes the live-slug set with a one-column ListAllSlugs Pluck instead of a Limit:0 GetGraph that materialized every node + edge. Memory is now bounded; 40k pages walks in constant ~4MB. - 14 GORM tests for both repos against an in-memory SQLite mirror of the production DDL (task_queue_test.go). - 6 tests for the dead-letter middleware covering retry budget detection, payload-agnostic scope inference, error truncation, and repo-failure isolation. - 7 tests for the slug fuzzy resolve helper covering the three resolution stages, display-text priority over normalized equality, bigram fallback acceptance, and rejection of unrelated slugs. - Existing wiki_ingest / wiki_lint / wiki_page tests updated to the new fetcher / cursor APIs.
2026-05-09 15:42:53 +00:00
pendingRepo: pendingRepo,
redisClient: redisClient,
}
}
// Handle implements asynq handler for TypeKnowledgePostProcess.
func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Task) error {
var payload types.KnowledgePostProcessPayload
if err := json.Unmarshal(task.Payload(), &payload); err != nil {
return fmt.Errorf("unmarshal knowledge post process payload: %w", err)
}
logger.Infof(ctx, "[KnowledgePostProcess] Orchestrating post processing for knowledge: %s", payload.KnowledgeID)
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
if payload.Language != "" {
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
}
// 1. Fetch Knowledge and KB
knowledge, err := s.knowledgeRepo.GetKnowledgeByIDOnly(ctx, payload.KnowledgeID)
if err != nil {
return fmt.Errorf("get knowledge %s: %w", payload.KnowledgeID, err)
}
if knowledge == nil {
logger.Warnf(ctx, "[KnowledgePostProcess] Knowledge %s not found, aborting.", payload.KnowledgeID)
return nil
}
kb, err := s.kbService.GetKnowledgeBaseByIDOnly(ctx, payload.KnowledgeBaseID)
if err != nil || kb == nil {
return fmt.Errorf("get knowledge base %s: %w", payload.KnowledgeBaseID, err)
}
// 2. Fetch all chunks
chunks, err := s.chunkService.ListChunksByKnowledgeID(ctx, payload.KnowledgeID)
if err != nil {
return fmt.Errorf("list chunks for knowledge %s: %w", payload.KnowledgeID, err)
}
// Gather all text-like chunks (including newly added OCR and Caption from multimodal tasks)
var textChunks []*types.Chunk
for _, c := range chunks {
if c.ChunkType == types.ChunkTypeText || c.ChunkType == types.ChunkTypeImageOCR || c.ChunkType == types.ChunkTypeImageCaption {
textChunks = append(textChunks, c)
}
}
// 3. Update ParseStatus to Completed
// (Except if it's already completed or if it was marked as failed/deleting, but we'll just set it to completed if it's processing)
if knowledge.ParseStatus == types.ParseStatusProcessing {
knowledge.ParseStatus = types.ParseStatusCompleted
knowledge.UpdatedAt = time.Now()
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
// Setup summary status
if len(textChunks) > 0 {
knowledge.SummaryStatus = types.SummaryStatusPending
} else {
knowledge.SummaryStatus = types.SummaryStatusNone
}
if err := s.knowledgeRepo.UpdateKnowledge(ctx, knowledge); err != nil {
logger.Warnf(ctx, "[KnowledgePostProcess] Failed to update knowledge status to completed: %v", err)
} else {
logger.Infof(ctx, "[KnowledgePostProcess] Knowledge %s marked as completed.", payload.KnowledgeID)
}
}
// 4. Spawn Summary and Question Tasks
if len(textChunks) > 0 {
s.enqueueSummaryGenerationTask(ctx, payload)
// Question generation only makes sense for RAG indexing (improves chunk recall).
// Skip when only Wiki/Graph is enabled without vector/keyword search.
if kb.NeedsEmbeddingModel() {
s.enqueueQuestionGenerationIfEnabled(ctx, payload, kb)
}
}
// 5. Spawn Graph RAG Tasks — only when graph indexing is enabled in IndexingStrategy
if kb.IsGraphEnabled() {
logger.Infof(ctx, "[KnowledgePostProcess] Spawning Graph RAG extract tasks for %d text-like chunks", len(textChunks))
for _, chunk := range textChunks {
err := NewChunkExtractTask(ctx, s.taskEnqueuer, payload.TenantID, chunk.ID, kb.SummaryModelID)
if err != nil {
logger.Errorf(ctx, "[KnowledgePostProcess] Failed to create chunk extract task for %s: %v", chunk.ID, err)
}
}
}
// 6. Spawn Wiki Ingest Task if wiki indexing is enabled in IndexingStrategy
if kb.IndexingStrategy.WikiEnabled && len(textChunks) > 0 {
perf(wiki-ingest): scale to 4w-doc KBs + generic task queue / dead-letter The wiki ingest post-process pipeline OOM'd and ran for hours on KBs with ~40k documents. The dominant tail was a per-batch ListAllPages that pulled every page (multi-MB content blobs) into Go memory, plus a 24h-TTL Redis pending list whose data could be evicted before a long serialized backlog drained. dedup did O(P × N) Jaccard scoring in Go on every batch. Lint loaded the full graph. The index page kept the entire wiki directory in its content column and rewrote the TOAST chunk on every ingest. None of these survive at 4w docs. This change reworks the write path end to end and pulls the durable- queue + dead-letter primitives out of wiki and into shared infrastructure that every asynq task type now benefits from. - migration 000041: task_pending_ops + task_dead_letters tables, plus three GIN indexes on wiki_pages (source_refs jsonb_path_ops, source_refs text fallback, lower(title) trgm). - TaskPendingOpsRepository + TaskDeadLetterRepository in internal/application/repository/task_queue.go: cursor-paginated list, atomic IncrFailCount via UPDATE…RETURNING, dedup-key scoped delete that refuses empty keys so a buggy caller can't wipe a KB's queue. - internal/middleware/asynqdl: writes a task_dead_letters row when an asynq task exhausts its retry budget. Payload-agnostic — a small probe struct extracts TenantID + scope hints across every existing payload type, so summary:generation / image:multimodal / faq_import / kb:clone / etc. all dead-letter without per-handler code. Best-effort: an insert failure never masks the underlying task error. Installed in router/task.go before the langfuse mw so it sees raw errors. - Pending queue moved Redis → PG (no TTL, restart-durable). Redis keeps just the active-batch lock and the delete tombstone. - In-batch retry budget (wikiMaxFailRetries=5) tracked via pendingRepo.IncrFailCount; over the cap the row is moved to task_dead_letters with task_type=wiki:ingest, related_id=knowledge id. Asynq retries (10) are handled by the new middleware. - Removed the per-batch ListAllPages. WikiBatchContext now carries lazy fetcher closures (SlugTitleMany, SummaryByKnowledgeID) with mutex-protected caches; reduce reaches for titles / summaries on demand instead of pre-loading the whole KB. - getExistingPageSlugsForKnowledge now uses ListSlugsBySourceRef, which the new GIN index on source_refs serves as a Bitmap Index Scan instead of a sequential text LIKE. - Dedup pre-filter uses pg_trgm via FindSimilarPages (idx_wiki_pages_title_trgm). For each new entity/concept (and each of its aliases) we ask the DB for the top-K trigram-similar existing pages and union the results — bounded prompt size, no Go- side O(P × M) loop. Small KBs (≤25 entities) bypass the pre-filter. - cleanDeadLinks / injectCrossLinks are scoped to the batch's affected slugs (a few dozen) instead of every page in the KB. Both use the new lite ListBySlugs / ExistsSlugs repo methods so they pull only slug + title + outlinks, not full content. - Slug fuzzy resolve (slug_fuzzy.go): when the LLM emits [[bad-slug|display]] the cleanup path now tries display-text reverse lookup → hyphen/case normalized equality → char-bigram Jaccard ≥ 0.8 before stripping. Recovers the common pinyin-word- break drift case ("shang-hai-tower" vs "shanghai-tower") in place instead of replacing the link with plain text. - rebuildIndexPage uses ListByTypeRecent(200) for the first-time intro and drops the full DocumentSummaries blob from the incremental update prompt, so its context stays bounded regardless of KB size. - Concurrency tunables surfaced in WikiConfig: IngestBatchSize / IngestMapParallel / IngestReduceParallel, with sensible defaults via OrDefault helpers. scheduleFollowUp drops to ProcessIn(0) so follow-ups don't waste asynq retry slots bouncing on the active lock. - RunLint walks pages via the new ListPagesCursor in 200-page windows and computes the live-slug set with a one-column ListAllSlugs Pluck instead of a Limit:0 GetGraph that materialized every node + edge. Memory is now bounded; 40k pages walks in constant ~4MB. - 14 GORM tests for both repos against an in-memory SQLite mirror of the production DDL (task_queue_test.go). - 6 tests for the dead-letter middleware covering retry budget detection, payload-agnostic scope inference, error truncation, and repo-failure isolation. - 7 tests for the slug fuzzy resolve helper covering the three resolution stages, display-text priority over normalized equality, bigram fallback acceptance, and rejection of unrelated slugs. - Existing wiki_ingest / wiki_lint / wiki_page tests updated to the new fetcher / cursor APIs.
2026-05-09 15:42:53 +00:00
EnqueueWikiIngest(ctx, s.taskEnqueuer, s.pendingRepo, payload.TenantID, payload.KnowledgeBaseID, payload.KnowledgeID)
feat: Implement comprehensive wiki feature for knowledge bases This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes: **Backend Changes:** - Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log) - Database schema: wiki_pages table with full migration support - WikiPageService: CRUD operations and page management - WikiPageRepository: GORM-based persistence layer - Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents * Summary page generation using LLM * Entity and concept extraction in a single LLM call * Synthesis opportunity detection * Index page rebuilding * Log page maintenance - Wiki boost feature: Enhance chat retrieval with wiki context - Wiki linting: Maintenance and validation utilities - Agent wiki tools: Enable agents to query and interact with wiki pages - Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks - Language support: Reuse existing middleware language infrastructure for LLM prompts **Frontend Changes:** - Wiki browser UI: View all wiki pages with filtering and search - Wiki API client: Knowledge base wiki management endpoints - Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model) - i18n updates: Support for English, Korean, Russian, and Chinese interfaces **Configuration:** - Container DI: Wire up all wiki services - Router: Register wiki API endpoints - Task handling: Support async wiki ingest tasks **Testing:** - Unit tests for wiki page types - Service layer tests - Endpoint tests for wiki operations - Integration tests with LLM mocking **Documentation:** - Language refactoring analysis and guides - Implementation completion reports - Quick reference guides for developers **Key Features:** ✅ LLM-powered wiki page generation from documents ✅ Multi-language support (9+ languages) ✅ Automatic extraction of entities and concepts ✅ Synthesis opportunity detection ✅ Index and log page maintenance ✅ Progressive wiki building across multiple documents ✅ Agent-based wiki interaction ✅ Chat retrieval enhancement with wiki context ✅ Full frontend UI for wiki browsing Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
logger.Infof(ctx, "[KnowledgePostProcess] Enqueued wiki ingest task for %s", payload.KnowledgeID)
}
return nil
}
func (s *KnowledgePostProcessService) enqueueSummaryGenerationTask(ctx context.Context, payload types.KnowledgePostProcessPayload) {
if s.taskEnqueuer == nil {
return
}
taskPayload := types.SummaryGenerationPayload{
TenantID: payload.TenantID,
KnowledgeBaseID: payload.KnowledgeBaseID,
KnowledgeID: payload.KnowledgeID,
Language: payload.Language,
}
feat(observability): extend Langfuse tracing across asynq pipeline Previously the Langfuse integration only traced in-process HTTP requests (chat / search / eval), so file uploads and every downstream asynq task (document parse, chunk embedding, OCR/VLM, summary / question gen, wiki ingest, datasource sync, etc.) produced either disconnected shallow traces or no observation at all. This change threads one trace end-to-end: - tracer: add SPAN observation type and StartSpan; add ResumeTrace so a worker can attach to an upstream trace without emitting a duplicate trace-create; StartGeneration now auto-picks parentObservationId from ctx so nested trace -> span -> generation trees render correctly. - types.TracingContext + LangfuseTracingCarrier: embed on all 17 asynq payloads so trace_id / parent_obs_id / user_id / session_id serialise into every job. - langfuse.InjectTracing: injected at 28 enqueue sites before json.Marshal so the HTTP-layer trace survives the Redis hop. - langfuse.AsynqMiddleware: mux.Use hook that peeks the payload, either resumes the upstream trace or opens a standalone asynq.<type> trace for scheduled jobs, and wraps the handler in a SPAN with task metadata (id / queue / retry / payload_bytes) plus ERROR level on failure. - GinMiddleware.shouldTrace: whitelist ingestion / knowledge-mutation / FAQ / wiki / datasource endpoints so the root trace actually starts. - Tests: tracer_test.go covers span nesting, error status, and ResumeTrace no-trace-create guarantee; asynq_test.go covers InjectTracing round-trip, middleware resume path, and standalone trace fallback. - Docs: docs/Langfuse\u96c6\u6210.md now lists the covered task types and documents the cross-process propagation model. No behavioural change when Langfuse is disabled (all new code paths are no-ops and carriers serialise to empty strings with omitempty).
2026-04-24 04:23:30 +00:00
langfuse.InjectTracing(ctx, &taskPayload)
payloadBytes, err := json.Marshal(taskPayload)
if err != nil {
logger.Warnf(ctx, "[KnowledgePostProcess] Failed to marshal summary generation payload: %v", err)
return
}
task := asynq.NewTask(types.TypeSummaryGeneration, payloadBytes, asynq.Queue("low"), asynq.MaxRetry(3))
if _, err := s.taskEnqueuer.Enqueue(task); err != nil {
logger.Warnf(ctx, "[KnowledgePostProcess] Failed to enqueue summary generation for %s: %v", payload.KnowledgeID, err)
} else {
logger.Infof(ctx, "[KnowledgePostProcess] Enqueued summary generation task for %s", payload.KnowledgeID)
}
}
func (s *KnowledgePostProcessService) enqueueQuestionGenerationIfEnabled(ctx context.Context, payload types.KnowledgePostProcessPayload, kb *types.KnowledgeBase) {
if s.taskEnqueuer == nil {
return
}
if kb.QuestionGenerationConfig == nil || !kb.QuestionGenerationConfig.Enabled {
return
}
questionCount := kb.QuestionGenerationConfig.QuestionCount
if questionCount <= 0 {
questionCount = 3
}
if questionCount > 10 {
questionCount = 10
}
taskPayload := types.QuestionGenerationPayload{
TenantID: payload.TenantID,
KnowledgeBaseID: payload.KnowledgeBaseID,
KnowledgeID: payload.KnowledgeID,
QuestionCount: questionCount,
Language: payload.Language,
}
feat(observability): extend Langfuse tracing across asynq pipeline Previously the Langfuse integration only traced in-process HTTP requests (chat / search / eval), so file uploads and every downstream asynq task (document parse, chunk embedding, OCR/VLM, summary / question gen, wiki ingest, datasource sync, etc.) produced either disconnected shallow traces or no observation at all. This change threads one trace end-to-end: - tracer: add SPAN observation type and StartSpan; add ResumeTrace so a worker can attach to an upstream trace without emitting a duplicate trace-create; StartGeneration now auto-picks parentObservationId from ctx so nested trace -> span -> generation trees render correctly. - types.TracingContext + LangfuseTracingCarrier: embed on all 17 asynq payloads so trace_id / parent_obs_id / user_id / session_id serialise into every job. - langfuse.InjectTracing: injected at 28 enqueue sites before json.Marshal so the HTTP-layer trace survives the Redis hop. - langfuse.AsynqMiddleware: mux.Use hook that peeks the payload, either resumes the upstream trace or opens a standalone asynq.<type> trace for scheduled jobs, and wraps the handler in a SPAN with task metadata (id / queue / retry / payload_bytes) plus ERROR level on failure. - GinMiddleware.shouldTrace: whitelist ingestion / knowledge-mutation / FAQ / wiki / datasource endpoints so the root trace actually starts. - Tests: tracer_test.go covers span nesting, error status, and ResumeTrace no-trace-create guarantee; asynq_test.go covers InjectTracing round-trip, middleware resume path, and standalone trace fallback. - Docs: docs/Langfuse\u96c6\u6210.md now lists the covered task types and documents the cross-process propagation model. No behavioural change when Langfuse is disabled (all new code paths are no-ops and carriers serialise to empty strings with omitempty).
2026-04-24 04:23:30 +00:00
langfuse.InjectTracing(ctx, &taskPayload)
payloadBytes, err := json.Marshal(taskPayload)
if err != nil {
logger.Warnf(ctx, "[KnowledgePostProcess] Failed to marshal question generation payload: %v", err)
return
}
task := asynq.NewTask(types.TypeQuestionGeneration, payloadBytes, asynq.Queue("low"), asynq.MaxRetry(3))
if _, err := s.taskEnqueuer.Enqueue(task); err != nil {
logger.Warnf(ctx, "[KnowledgePostProcess] Failed to enqueue question generation for %s: %v", payload.KnowledgeID, err)
} else {
logger.Infof(ctx, "[KnowledgePostProcess] Enqueued question generation task for %s (count=%d)", payload.KnowledgeID, questionCount)
}
}