2025-09-24 04:15:17 +00:00
package router
import (
2026-05-27 05:17:08 +00:00
"context"
"encoding/json"
2026-04-22 12:25:08 +00:00
"errors"
2025-09-24 04:15:17 +00:00
"log"
"os"
2025-12-30 04:06:29 +00:00
"strconv"
2026-05-27 05:17:08 +00:00
"strings"
2025-09-24 04:15:17 +00:00
"time"
2026-04-22 12:25:08 +00:00
"github.com/Tencent/WeKnora/internal/application/service"
2026-07-06 15:02:02 +00:00
"github.com/Tencent/WeKnora/internal/common"
2026-05-27 05:17:08 +00:00
"github.com/Tencent/WeKnora/internal/logger"
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
"github.com/Tencent/WeKnora/internal/middleware/asynqdl"
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"
2025-09-24 04:15:17 +00:00
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/hibiken/asynq"
"go.uber.org/dig"
)
type AsynqTaskParams struct {
dig . In
2026-07-13 06:55:59 +00:00
// Dedicated servers provide minimum capacity for parse, post-process,
// enrichment, maintenance, and Wiki work. SharedServer is the elastic tier:
// it also subscribes to core/enrichment queues so either stage can borrow
// otherwise-idle capacity without consuming the other stage's guarantee.
2026-07-10 15:19:41 +00:00
CoreServer * asynq . Server ` name:"coreAsynqServer" `
2026-07-13 06:55:59 +00:00
PostProcessServer * asynq . Server ` name:"postProcessAsynqServer" `
2026-07-10 15:19:41 +00:00
EnrichmentServer * asynq . Server ` name:"enrichmentAsynqServer" `
MaintenanceServer * asynq . Server ` name:"maintenanceAsynqServer" `
2026-07-13 06:55:59 +00:00
SharedServer * asynq . Server ` name:"sharedAsynqServer" `
2026-07-09 05:27:47 +00:00
WikiServer * asynq . Server ` name:"wikiAsynqServer" `
2025-12-25 11:33:58 +00:00
KnowledgeService interfaces . KnowledgeService
KnowledgeBaseService interfaces . KnowledgeBaseService
TagService interfaces . KnowledgeTagService
2026-03-27 07:02:40 +00:00
DataSourceService interfaces . DataSourceService
2026-02-06 03:55:46 +00:00
ChunkExtractor interfaces . TaskHandler ` name:"chunkExtractor" `
2025-12-23 08:56:30 +00:00
DataTableSummary interfaces . TaskHandler ` name:"dataTableSummary" `
2026-02-28 05:22:07 +00:00
ImageMultimodal interfaces . TaskHandler ` name:"imageMultimodal" `
2026-04-16 06:59:23 +00:00
KnowledgePostProcess interfaces . TaskHandler ` name:"knowledgePostProcess" `
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
WikiIngest interfaces . TaskHandler ` name:"wikiIngest" `
2026-07-16 06:48:20 +00:00
TemporaryDocument interfaces . TemporaryDocumentService
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
DeadLetterRepo interfaces . TaskDeadLetterRepository
fix(knowledge): close root span on terminal state, enrich stage metadata
The root span created by OpenAttempt was never closed: PostProcess only
ended the postprocess stage, so the root row stayed at status=running
forever even after parse_status flipped to completed/failed. The
timeline rendered "进行中" indefinitely on the root, defeating the
whole "is the document done" question the timeline is meant to answer.
- SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg):
closes the root row idempotently. Re-closing a terminal root no-ops
so success / cascade-fail / dead-letter paths can fire without
coordination.
- PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess)
on the success path. Async downstream work (summary/question/wiki/
graph) still records its own spans; their completion extends the
trace's wall-clock end-time but doesn't reopen the root.
- FailSpan auto-closes the root when a MAIN pipeline stage fails
(docreader / chunking / embedding / multimodal / postprocess).
Cascade-cancelled siblings stay closed-with-the-cascade as before.
- Dead-letter callback (router/task.go) accepts the SpanTracker via
DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a
document-related task exhausts retries. The probe payload now
extracts the Attempt field that Document/Manual/PostProcess
payloads already thread through.
Stage spans were also being recorded with nil input/output, leaving
the new detail panel with timestamps only. Each Begin/End site now
emits useful work metrics:
- DocReader input: file_name, file_type, is_url, url
output: text_length, images_found, is_audio, pages
- Chunking input: chunks_planned
output: chunks_written, total_text_chars
- Embedding input: chunks_to_embed, model_id, dim
output: vectors_written, storage_bytes
- Multimodal input: image_count, enable_ocr, enable_caption
- PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph
i18n: add knowledgeStages.root ("Knowledge processing") so the UI
can render a localized name instead of the raw span identifier.
2026-05-27 08:54:09 +00:00
SpanTracker service . SpanTracker
2025-09-24 04:15:17 +00:00
}
2026-05-27 05:17:08 +00:00
// defaultRedisOpTimeout is the previous hard-coded read timeout. The 100ms
// floor was tight enough to cause spurious i/o timeout errors during bursty
// workloads (large batch uploads, multimodal counter DECRs under load), so we
// raise the default to 500ms while still allowing operators to tune via env.
const defaultRedisOpTimeoutMs = 500
// readRedisOpTimeoutMs reads WEKNORA_REDIS_OP_TIMEOUT_MS, falling back to
// defaultRedisOpTimeoutMs on missing/invalid input. Kept as a separate helper
// so both ReadTimeout and WriteTimeout share the same source of truth.
func readRedisOpTimeoutMs ( ) int {
if v := strings . TrimSpace ( os . Getenv ( "WEKNORA_REDIS_OP_TIMEOUT_MS" ) ) ; v != "" {
if parsed , err := strconv . Atoi ( v ) ; err == nil && parsed > 0 {
return parsed
}
}
return defaultRedisOpTimeoutMs
}
2025-09-24 04:15:17 +00:00
func getAsynqRedisClientOpt ( ) * asynq . RedisClientOpt {
2025-12-30 04:06:29 +00:00
db := 0
if dbStr := os . Getenv ( "REDIS_DB" ) ; dbStr != "" {
if parsed , err := strconv . Atoi ( dbStr ) ; err == nil {
db = parsed
}
}
2026-05-27 05:17:08 +00:00
timeoutMs := readRedisOpTimeoutMs ( )
2025-09-24 04:15:17 +00:00
opt := & asynq . RedisClientOpt {
2026-05-27 05:17:08 +00:00
Addr : os . Getenv ( "REDIS_ADDR" ) ,
Username : os . Getenv ( "REDIS_USERNAME" ) ,
Password : os . Getenv ( "REDIS_PASSWORD" ) ,
ReadTimeout : time . Duration ( timeoutMs ) * time . Millisecond ,
// Writes are typically more sensitive to congestion than reads
// (RESP pipelining, BRPOPLPUSH on Asynq dequeue), so we keep
// WriteTimeout slightly larger to absorb head-of-line stalls.
WriteTimeout : time . Duration ( timeoutMs * 2 ) * time . Millisecond ,
2025-12-30 04:06:29 +00:00
DB : db ,
2026-07-06 15:02:02 +00:00
TLSConfig : common . RedisTLSConfig ( ) ,
2025-09-24 04:15:17 +00:00
}
return opt
}
2025-11-10 14:45:27 +00:00
func NewAsyncqClient ( ) ( * asynq . Client , error ) {
2025-09-24 04:15:17 +00:00
opt := getAsynqRedisClientOpt ( )
client := asynq . NewClient ( opt )
2025-11-10 14:45:27 +00:00
err := client . Ping ( )
if err != nil {
return nil , err
}
return client , nil
2025-09-24 04:15:17 +00:00
}
2026-04-22 12:25:08 +00:00
// wikiIngestRetryDelay is a fixed, short backoff for wiki ingest lock
// conflicts. Must be slightly longer than the active-lock TTL's worst-case
// "just got set" window so the retry is highly likely to succeed without
// burning through retries; but short enough that users don't feel the stall.
const wikiIngestRetryDelay = 15 * time . Second
// asynqRetryDelayFunc customizes per-task retry backoff.
//
// Default asynq backoff is exponential (≈10s, 40s, 90s, 2.5m, ...), which
// is appropriate for transient errors like remote HTTP failures. But for
// wiki ingest lock conflicts (ErrWikiIngestConcurrent), exponential
// backoff is harmful: a freshly orphaned lock expires in ≤60s, so a 15s
// fixed retry virtually guarantees the next attempt succeeds. Without
// this override, a crash-restart cycle can leave a KB unable to make
// progress for 7– 10 minutes while the orphan lock expires AND the retry
// schedule catches up.
func asynqRetryDelayFunc ( n int , e error , t * asynq . Task ) time . Duration {
if errors . Is ( e , service . ErrWikiIngestConcurrent ) {
return wikiIngestRetryDelay
}
return asynq . DefaultRetryDelayFunc ( n , e , t )
}
2026-07-10 15:19:41 +00:00
// Worker defaults live in types so server construction and runtime reporting
// cannot drift. The upstream budget is divided without increasing historical
// total capacity; Wiki remains separate because its model-heavy workload has a
// different provider-capacity profile.
2026-07-09 05:27:47 +00:00
// newAsynqServer builds an asynq server bound to a specific queue set and
2026-07-10 15:19:41 +00:00
// concurrency. Every worker pool uses it so Redis options and retry-delay
// policy stay consistent across the topology.
2026-07-09 05:27:47 +00:00
func newAsynqServer ( concurrency int , queues map [ string ] int ) * asynq . Server {
2026-06-03 04:00:09 +00:00
opt := getAsynqRedisClientOpt ( )
2026-07-09 05:27:47 +00:00
return asynq . NewServer (
opt ,
asynq . Config {
Concurrency : concurrency ,
Queues : queues ,
RetryDelayFunc : asynqRetryDelayFunc ,
} ,
)
}
feat(models): cap background LLM concurrency per model
Background ingestion/enrichment stages (summary, question, graph,
multimodal) all target the same chat model, and asynq queue weights are
scheduling priority rather than throttling. A large upload could therefore
burst up to the entire worker pool of concurrent chat calls against a
single provider, unbounded across replicas, with no model-side rate limit.
Govern concurrency at the chat-client layer (the one place that sees every
task type), keyed by model ID:
- internal/models/limiter: Redis ZSET + Lua distributed semaphore with a
lease heartbeat, expired-lease reclaim for crashed holders, and fail-open
on any backend error or context cancellation.
- chat: concurrencyChat decorator (outermost in NewChat) acquires a
per-model slot only for background tasks; interactive chat is never gated.
- router/task: asynq middleware tags every worker execution as background.
- container: wire the Redis limiter with WEKNORA_MODEL_MAX_CONCURRENCY
(model.max_concurrency), default 8; enabled only when Redis is present.
Tested with miniredis: concurrency cap, expired-lease reclaim, per-key
isolation, and all fail-open paths (nil client, backend down, cancelled ctx).
2026-07-09 10:13:09 +00:00
// backgroundTaskMiddleware tags every task's context as a background worker
// execution (types.WithBackgroundTask) so the per-model chat concurrency
// governor applies to ingestion/enrichment LLM calls but not to interactive
// user-facing chat.
func backgroundTaskMiddleware ( ) asynq . MiddlewareFunc {
return func ( next asynq . Handler ) asynq . Handler {
return asynq . HandlerFunc ( func ( ctx context . Context , t * asynq . Task ) error {
return next . ProcessTask ( types . WithBackgroundTask ( ctx ) , t )
} )
}
}
2026-07-13 06:55:59 +00:00
func resolveWorkerPoolConcurrency ( svc interfaces . SystemSettingService ) types . WorkerPoolConcurrency {
if svc == nil {
return types . DefaultWorkerPoolConcurrency ( )
2026-05-27 05:17:08 +00:00
}
2026-07-13 06:55:59 +00:00
ctx := context . Background ( )
return types . ResolveWorkerPoolConcurrency ( func ( key , env string , fallback int ) int {
value := svc . GetInt ( ctx , key , env , int64 ( fallback ) )
return int ( value )
} )
2026-07-10 15:19:41 +00:00
}
2026-07-13 06:55:59 +00:00
// NewCoreAsynqServer runs document and manual parsing with guaranteed capacity.
2026-07-10 15:19:41 +00:00
func NewCoreAsynqServer ( svc interfaces . SystemSettingService ) * asynq . Server {
2026-07-13 06:55:59 +00:00
allocation := resolveWorkerPoolConcurrency ( svc )
2026-07-10 15:19:41 +00:00
log . Printf ( "asynq core-pool server starting with concurrency=%d total_upstream=%d redis_op_timeout=%dms" ,
2026-07-13 06:55:59 +00:00
allocation . Core , allocation . UpstreamTotal ( ) , readRedisOpTimeoutMs ( ) )
2026-07-10 15:19:41 +00:00
return newAsynqServer ( allocation . Core , types . QueueWeightsForPool ( types . WorkerPoolCore ) )
}
2026-07-13 06:55:59 +00:00
// NewPostProcessAsynqServer reserves capacity for the lightweight but
// latency-sensitive fan-out stage. It cannot be trapped behind a burst of
// long-running document parses in QueueDefault.
func NewPostProcessAsynqServer ( svc interfaces . SystemSettingService ) * asynq . Server {
allocation := resolveWorkerPoolConcurrency ( svc )
log . Printf ( "asynq postprocess-pool server starting with concurrency=%d total_upstream=%d" ,
allocation . PostProcess , allocation . UpstreamTotal ( ) )
return newAsynqServer ( allocation . PostProcess , types . QueueWeightsForPool ( types . WorkerPoolPostProcess ) )
}
2026-07-10 15:19:41 +00:00
// NewEnrichmentAsynqServer runs high-fanout summary, multimodal, graph, and
// question generation without consuming core parsing capacity.
func NewEnrichmentAsynqServer ( svc interfaces . SystemSettingService ) * asynq . Server {
2026-07-13 06:55:59 +00:00
allocation := resolveWorkerPoolConcurrency ( svc )
2026-07-10 15:19:41 +00:00
log . Printf ( "asynq enrichment-pool server starting with concurrency=%d total_upstream=%d" ,
2026-07-13 06:55:59 +00:00
allocation . Enrichment , allocation . UpstreamTotal ( ) )
2026-07-10 15:19:41 +00:00
return newAsynqServer ( allocation . Enrichment , types . QueueWeightsForPool ( types . WorkerPoolEnrichment ) )
}
// NewMaintenanceAsynqServer runs connector sync, cleanup, deletion, and batch
// dispatch work. QueueMaintenance keeps the legacy Redis name "low", so old
// tasks are drained safely during rolling upgrades.
func NewMaintenanceAsynqServer ( svc interfaces . SystemSettingService ) * asynq . Server {
2026-07-13 06:55:59 +00:00
allocation := resolveWorkerPoolConcurrency ( svc )
2026-07-10 15:19:41 +00:00
log . Printf ( "asynq maintenance-pool server starting with concurrency=%d total_upstream=%d" ,
2026-07-13 06:55:59 +00:00
allocation . Maintenance , allocation . UpstreamTotal ( ) )
2026-07-10 15:19:41 +00:00
return newAsynqServer ( allocation . Maintenance , types . QueueWeightsForPool ( types . WorkerPoolMaintenance ) )
2026-07-09 05:27:47 +00:00
}
2026-07-13 06:55:59 +00:00
// NewSharedAsynqServer is the elastic tier. Asynq dequeue is atomic, so it is
// safe for this server and the dedicated servers to subscribe to the same
// queues: every task is still executed by exactly one worker.
func NewSharedAsynqServer ( svc interfaces . SystemSettingService ) * asynq . Server {
allocation := resolveWorkerPoolConcurrency ( svc )
log . Printf ( "asynq shared-pool server starting with concurrency=%d total_upstream=%d" ,
allocation . Shared , allocation . UpstreamTotal ( ) )
return newAsynqServer ( allocation . Shared , types . QueueWeightsForSharedPool ( ) )
}
2026-07-10 15:19:41 +00:00
// NewWikiAsynqServer builds the dedicated wiki pool: QueueWiki only. It runs
// the shared handler mux but only ever pulls wiki tasks, so its concurrency
2026-07-13 06:55:59 +00:00
// budget (WEKNORA_WIKI_ASYNQ_CONCURRENCY, default 8) is spent exclusively on
2026-07-09 05:27:47 +00:00
// wiki generation. This is the hard capacity isolation that prevents the parse
// pipeline from starving wiki (and vice-versa) during concurrent uploads.
func NewWikiAsynqServer ( svc interfaces . SystemSettingService ) * asynq . Server {
2026-07-13 06:55:59 +00:00
concurrency := resolveWorkerPoolConcurrency ( svc ) . Wiki
2026-07-09 05:27:47 +00:00
log . Printf ( "asynq wiki-pool server starting with concurrency=%d" , concurrency )
2026-07-10 15:19:41 +00:00
return newAsynqServer ( concurrency , types . QueueWeightsForPool ( types . WorkerPoolWiki ) )
2025-09-24 04:15:17 +00:00
}
func RunAsynqServer ( params AsynqTaskParams ) * asynq . ServeMux {
// Create a new mux and register all handlers
mux := asynq . NewServeMux ( )
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
// Install the dead-letter middleware FIRST so it sees the raw error
// returned by the handler, before any other middleware that might
// transform it. The middleware records one task_dead_letters row per
// task that exhausts its retry budget — operators can then SQL-query
// failures by task type, scope, or tenant without scraping logs.
// Best-effort: a DB failure is logged and swallowed; the original task
// error always propagates upstream to asynq for retry/archival.
2026-05-27 05:17:08 +00:00
//
// The callback flips Knowledge.parse_status to "failed" the moment a
// document-related task exhausts its retry budget. Without this hook,
// a permanently-failing task left its parent knowledge stranded in
// "processing" until housekeeping cron caught it minutes later — the
// UI signal users actually see.
fix(knowledge): close root span on terminal state, enrich stage metadata
The root span created by OpenAttempt was never closed: PostProcess only
ended the postprocess stage, so the root row stayed at status=running
forever even after parse_status flipped to completed/failed. The
timeline rendered "进行中" indefinitely on the root, defeating the
whole "is the document done" question the timeline is meant to answer.
- SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg):
closes the root row idempotently. Re-closing a terminal root no-ops
so success / cascade-fail / dead-letter paths can fire without
coordination.
- PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess)
on the success path. Async downstream work (summary/question/wiki/
graph) still records its own spans; their completion extends the
trace's wall-clock end-time but doesn't reopen the root.
- FailSpan auto-closes the root when a MAIN pipeline stage fails
(docreader / chunking / embedding / multimodal / postprocess).
Cascade-cancelled siblings stay closed-with-the-cascade as before.
- Dead-letter callback (router/task.go) accepts the SpanTracker via
DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a
document-related task exhausts retries. The probe payload now
extracts the Attempt field that Document/Manual/PostProcess
payloads already thread through.
Stage spans were also being recorded with nil input/output, leaving
the new detail panel with timestamps only. Each Begin/End site now
emits useful work metrics:
- DocReader input: file_name, file_type, is_url, url
output: text_length, images_found, is_audio, pages
- Chunking input: chunks_planned
output: chunks_written, total_text_chars
- Embedding input: chunks_to_embed, model_id, dim
output: vectors_written, storage_bytes
- Multimodal input: image_count, enable_ocr, enable_caption
- PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph
i18n: add knowledgeStages.root ("Knowledge processing") so the UI
can render a localized name instead of the raw span identifier.
2026-05-27 08:54:09 +00:00
knowledgeFailer := newDeadLetterKnowledgeFailer ( params . KnowledgeService , params . SpanTracker )
2026-05-27 05:17:08 +00:00
mux . Use ( asynqdl . MiddlewareWithCallback ( params . DeadLetterRepo , knowledgeFailer ) )
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
feat(models): cap background LLM concurrency per model
Background ingestion/enrichment stages (summary, question, graph,
multimodal) all target the same chat model, and asynq queue weights are
scheduling priority rather than throttling. A large upload could therefore
burst up to the entire worker pool of concurrent chat calls against a
single provider, unbounded across replicas, with no model-side rate limit.
Govern concurrency at the chat-client layer (the one place that sees every
task type), keyed by model ID:
- internal/models/limiter: Redis ZSET + Lua distributed semaphore with a
lease heartbeat, expired-lease reclaim for crashed holders, and fail-open
on any backend error or context cancellation.
- chat: concurrencyChat decorator (outermost in NewChat) acquires a
per-model slot only for background tasks; interactive chat is never gated.
- router/task: asynq middleware tags every worker execution as background.
- container: wire the Redis limiter with WEKNORA_MODEL_MAX_CONCURRENCY
(model.max_concurrency), default 8; enabled only when Redis is present.
Tested with miniredis: concurrency cap, expired-lease reclaim, per-key
isolation, and all fail-open paths (nil client, backend down, cancelled ctx).
2026-07-09 10:13:09 +00:00
// Mark every asynq worker execution as a background task so the chat
// concurrency governor throttles ingestion/enrichment LLM traffic while
// leaving user-facing interactive chat ungated. Installed early so all
// downstream handlers (and their model calls) inherit the flag.
mux . Use ( backgroundTaskMiddleware ( ) )
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
// Install Langfuse middleware BEFORE handler registration so every task
// type is automatically wrapped. When Langfuse is disabled the middleware
// is a pass-through; when enabled it resumes the upstream HTTP trace (if
// the payload carries one) or opens a standalone trace, then wraps the
// handler execution in a SPAN so all child generations (embedding / VLM /
// chat / rerank / ASR) nest correctly in the Langfuse UI.
mux . Use ( langfuse . AsynqMiddleware ( ) )
2025-12-23 08:56:30 +00:00
// Register extract handlers - router will dispatch to appropriate handler
2026-02-06 03:55:46 +00:00
mux . HandleFunc ( types . TypeChunkExtract , params . ChunkExtractor . Handle )
2025-12-23 08:56:30 +00:00
mux . HandleFunc ( types . TypeDataTableSummary , params . DataTableSummary . Handle )
2025-09-24 04:15:17 +00:00
2025-11-23 16:21:42 +00:00
// Register document processing handler
mux . HandleFunc ( types . TypeDocumentProcess , params . KnowledgeService . ProcessDocument )
2026-07-16 06:48:20 +00:00
mux . HandleFunc ( types . TypeTemporaryDocumentProcess , params . TemporaryDocument . Process )
2025-11-23 16:21:42 +00:00
2026-03-17 11:26:29 +00:00
// Register manual knowledge processing handler (cleanup + re-indexing)
mux . HandleFunc ( types . TypeManualProcess , params . KnowledgeService . ProcessManualUpdate )
2026-01-06 07:17:08 +00:00
// Register FAQ import handler (includes dry run mode)
2025-11-23 16:21:42 +00:00
mux . HandleFunc ( types . TypeFAQImport , params . KnowledgeService . ProcessFAQImport )
2025-12-02 17:42:31 +00:00
// Register question generation handler
mux . HandleFunc ( types . TypeQuestionGeneration , params . KnowledgeService . ProcessQuestionGeneration )
// Register summary generation handler
mux . HandleFunc ( types . TypeSummaryGeneration , params . KnowledgeService . ProcessSummaryGeneration )
2025-12-16 09:38:28 +00:00
// Register KB clone handler
mux . HandleFunc ( types . TypeKBClone , params . KnowledgeService . ProcessKBClone )
2026-03-09 05:14:42 +00:00
// Register knowledge move handler
mux . HandleFunc ( types . TypeKnowledgeMove , params . KnowledgeService . ProcessKnowledgeMove )
2026-01-15 11:38:16 +00:00
// Register knowledge list delete handler
mux . HandleFunc ( types . TypeKnowledgeListDelete , params . KnowledgeService . ProcessKnowledgeListDelete )
2026-06-25 15:51:38 +00:00
// Register knowledge list reparse handler
mux . HandleFunc ( types . TypeKnowledgeListReparse , params . KnowledgeService . ProcessKnowledgeListReparse )
2025-12-25 07:35:57 +00:00
// Register index delete handler
mux . HandleFunc ( types . TypeIndexDelete , params . TagService . ProcessIndexDelete )
2025-12-25 11:33:58 +00:00
// Register KB delete handler
mux . HandleFunc ( types . TypeKBDelete , params . KnowledgeBaseService . ProcessKBDelete )
2026-02-28 05:22:07 +00:00
// Register image multimodal handler
mux . HandleFunc ( types . TypeImageMultimodal , params . ImageMultimodal . Handle )
2026-04-16 06:59:23 +00:00
// Register knowledge post process handler
mux . HandleFunc ( types . TypeKnowledgePostProcess , params . KnowledgePostProcess . Handle )
2026-03-27 07:02:40 +00:00
// Register data source sync handler
mux . HandleFunc ( types . TypeDataSourceSync , params . DataSourceService . ProcessSync )
2026-07-09 05:27:47 +00:00
// Register wiki ingest handler + the debounced KB-global finalize handler.
// Both route to the same dispatch (WikiIngest.Handle switches on task type)
// and both land on QueueWiki, so the dedicated wiki pool serves them.
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
mux . HandleFunc ( types . TypeWikiIngest , params . WikiIngest . Handle )
2026-07-09 05:27:47 +00:00
mux . HandleFunc ( types . TypeWikiFinalize , params . WikiIngest . Handle )
2026-07-13 06:55:59 +00:00
// Run the same mux on every pool. Shared and dedicated servers intentionally
// overlap, but Redis dequeue is atomic, so each task still executes once.
2026-07-09 05:27:47 +00:00
runPool := func ( name string , srv * asynq . Server ) {
go func ( ) {
if err := srv . Run ( mux ) ; err != nil {
log . Fatalf ( "could not run %s asynq server: %v" , name , err )
}
} ( )
}
2026-07-10 15:19:41 +00:00
runPool ( "core-pool" , params . CoreServer )
2026-07-13 06:55:59 +00:00
runPool ( "postprocess-pool" , params . PostProcessServer )
2026-07-10 15:19:41 +00:00
runPool ( "enrichment-pool" , params . EnrichmentServer )
runPool ( "maintenance-pool" , params . MaintenanceServer )
2026-07-13 06:55:59 +00:00
runPool ( "shared-pool" , params . SharedServer )
2026-07-09 05:27:47 +00:00
runPool ( "wiki-pool" , params . WikiServer )
2025-09-24 04:15:17 +00:00
return mux
}
2026-05-27 05:17:08 +00:00
// deadLetterKnowledgePayload extracts only the field we need from any
// document-related asynq payload. Kept narrow so we don't accidentally
// depend on the full payload schema and survive future field churn.
type deadLetterKnowledgePayload struct {
KnowledgeID string ` json:"knowledge_id,omitempty" `
fix(knowledge): close root span on terminal state, enrich stage metadata
The root span created by OpenAttempt was never closed: PostProcess only
ended the postprocess stage, so the root row stayed at status=running
forever even after parse_status flipped to completed/failed. The
timeline rendered "进行中" indefinitely on the root, defeating the
whole "is the document done" question the timeline is meant to answer.
- SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg):
closes the root row idempotently. Re-closing a terminal root no-ops
so success / cascade-fail / dead-letter paths can fire without
coordination.
- PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess)
on the success path. Async downstream work (summary/question/wiki/
graph) still records its own spans; their completion extends the
trace's wall-clock end-time but doesn't reopen the root.
- FailSpan auto-closes the root when a MAIN pipeline stage fails
(docreader / chunking / embedding / multimodal / postprocess).
Cascade-cancelled siblings stay closed-with-the-cascade as before.
- Dead-letter callback (router/task.go) accepts the SpanTracker via
DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a
document-related task exhausts retries. The probe payload now
extracts the Attempt field that Document/Manual/PostProcess
payloads already thread through.
Stage spans were also being recorded with nil input/output, leaving
the new detail panel with timestamps only. Each Begin/End site now
emits useful work metrics:
- DocReader input: file_name, file_type, is_url, url
output: text_length, images_found, is_audio, pages
- Chunking input: chunks_planned
output: chunks_written, total_text_chars
- Embedding input: chunks_to_embed, model_id, dim
output: vectors_written, storage_bytes
- Multimodal input: image_count, enable_ocr, enable_caption
- PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph
i18n: add knowledgeStages.root ("Knowledge processing") so the UI
can render a localized name instead of the raw span identifier.
2026-05-27 08:54:09 +00:00
// Attempt threads through DocumentProcess / ManualProcess /
// KnowledgePostProcess payloads (added when span tracking shipped)
// — extracted here so the dead-letter callback can also close the
// matching root span as failed. Older in-flight payloads without
// this field decode as 0 and the tracker call no-ops.
Attempt int ` json:"attempt,omitempty" `
2026-05-27 05:17:08 +00:00
}
// taskTypesAffectingKnowledgeStatus enumerates the asynq task types whose
// dead-letter event should flip the parent Knowledge to "failed". Only
// terminal task types are listed here:
//
// - TypeDocumentProcess: the entry point of the parsing pipeline.
// - TypeImageMultimodal: a single image hitting dead-letter would have
// been counted by isFinalAsynqAttempt (see image_multimodal.go), so
// the parent might still complete via remaining images. We DO NOT mark
// the parent failed for this case — finalize-on-last-attempt already
// ensures progress.
// - TypeKnowledgePostProcess: terminal stage; failure here strands the
// knowledge in "processing".
// - TypeManualProcess: same shape as DocumentProcess for re-indexing.
//
// Question/Summary generation are NOT included: they run after parse_status
// has already become "completed" and have their own status fields.
var taskTypesAffectingKnowledgeStatus = map [ string ] struct { } {
types . TypeDocumentProcess : { } ,
types . TypeKnowledgePostProcess : { } ,
types . TypeManualProcess : { } ,
}
2026-06-16 04:08:00 +00:00
type deadLetterKnowledgeListDeletePayload struct {
KnowledgeIDs [ ] string ` json:"knowledge_ids,omitempty" `
}
2026-05-27 05:17:08 +00:00
// newDeadLetterKnowledgeFailer returns the callback wired into the asynq
// dead-letter middleware. When a document-related task exhausts its retry
// budget, this callback marks the corresponding Knowledge row as failed so
// the UI surfaces the error instead of a perpetual spinner.
//
// All work is best-effort: missing payload, missing knowledge_id, or DB
// errors are logged and swallowed. The dead-letter record is the source of
// truth — this is purely a UX shortcut so users don't wait for the
// housekeeping cron's next sweep.
fix(knowledge): close root span on terminal state, enrich stage metadata
The root span created by OpenAttempt was never closed: PostProcess only
ended the postprocess stage, so the root row stayed at status=running
forever even after parse_status flipped to completed/failed. The
timeline rendered "进行中" indefinitely on the root, defeating the
whole "is the document done" question the timeline is meant to answer.
- SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg):
closes the root row idempotently. Re-closing a terminal root no-ops
so success / cascade-fail / dead-letter paths can fire without
coordination.
- PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess)
on the success path. Async downstream work (summary/question/wiki/
graph) still records its own spans; their completion extends the
trace's wall-clock end-time but doesn't reopen the root.
- FailSpan auto-closes the root when a MAIN pipeline stage fails
(docreader / chunking / embedding / multimodal / postprocess).
Cascade-cancelled siblings stay closed-with-the-cascade as before.
- Dead-letter callback (router/task.go) accepts the SpanTracker via
DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a
document-related task exhausts retries. The probe payload now
extracts the Attempt field that Document/Manual/PostProcess
payloads already thread through.
Stage spans were also being recorded with nil input/output, leaving
the new detail panel with timestamps only. Each Begin/End site now
emits useful work metrics:
- DocReader input: file_name, file_type, is_url, url
output: text_length, images_found, is_audio, pages
- Chunking input: chunks_planned
output: chunks_written, total_text_chars
- Embedding input: chunks_to_embed, model_id, dim
output: vectors_written, storage_bytes
- Multimodal input: image_count, enable_ocr, enable_caption
- PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph
i18n: add knowledgeStages.root ("Knowledge processing") so the UI
can render a localized name instead of the raw span identifier.
2026-05-27 08:54:09 +00:00
func newDeadLetterKnowledgeFailer ( ks interfaces . KnowledgeService , tracker service . SpanTracker ) asynqdl . OnDeadLetter {
2026-05-27 05:17:08 +00:00
if ks == nil {
return nil
}
repo := ks . GetRepository ( )
if repo == nil {
return nil
}
return func ( ctx context . Context , t * asynq . Task , taskErr error ) {
if t == nil {
return
}
2026-06-16 04:08:00 +00:00
if t . Type ( ) == types . TypeKnowledgeListDelete {
markKnowledgeListDeleteFailed ( ctx , repo , t , taskErr )
return
}
2026-05-27 05:17:08 +00:00
if _ , ok := taskTypesAffectingKnowledgeStatus [ t . Type ( ) ] ; ! ok {
return
}
var probe deadLetterKnowledgePayload
if err := json . Unmarshal ( t . Payload ( ) , & probe ) ; err != nil || probe . KnowledgeID == "" {
return
}
errMsg := "task " + t . Type ( ) + " exhausted retries: " + taskErr . Error ( )
// 8KB is the same cap the dead-letter row uses for last_error.
if len ( errMsg ) > 8192 {
errMsg = errMsg [ : 8192 ]
}
2026-05-27 07:31:32 +00:00
// Single UPDATE so we never end up with parse_status=failed but
// stale error_message (or vice versa) when the second write
// fails.
if err := repo . UpdateKnowledgeColumns ( ctx , probe . KnowledgeID , map [ string ] interface { } {
"parse_status" : types . ParseStatusFailed ,
"error_message" : errMsg ,
} ) ; err != nil {
logger . Warnf ( ctx , "dead-letter callback: failed to mark knowledge %s as failed: %v" , probe . KnowledgeID , err )
2026-05-27 05:17:08 +00:00
return
}
fix(knowledge): close root span on terminal state, enrich stage metadata
The root span created by OpenAttempt was never closed: PostProcess only
ended the postprocess stage, so the root row stayed at status=running
forever even after parse_status flipped to completed/failed. The
timeline rendered "进行中" indefinitely on the root, defeating the
whole "is the document done" question the timeline is meant to answer.
- SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg):
closes the root row idempotently. Re-closing a terminal root no-ops
so success / cascade-fail / dead-letter paths can fire without
coordination.
- PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess)
on the success path. Async downstream work (summary/question/wiki/
graph) still records its own spans; their completion extends the
trace's wall-clock end-time but doesn't reopen the root.
- FailSpan auto-closes the root when a MAIN pipeline stage fails
(docreader / chunking / embedding / multimodal / postprocess).
Cascade-cancelled siblings stay closed-with-the-cascade as before.
- Dead-letter callback (router/task.go) accepts the SpanTracker via
DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a
document-related task exhausts retries. The probe payload now
extracts the Attempt field that Document/Manual/PostProcess
payloads already thread through.
Stage spans were also being recorded with nil input/output, leaving
the new detail panel with timestamps only. Each Begin/End site now
emits useful work metrics:
- DocReader input: file_name, file_type, is_url, url
output: text_length, images_found, is_audio, pages
- Chunking input: chunks_planned
output: chunks_written, total_text_chars
- Embedding input: chunks_to_embed, model_id, dim
output: vectors_written, storage_bytes
- Multimodal input: image_count, enable_ocr, enable_caption
- PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph
i18n: add knowledgeStages.root ("Knowledge processing") so the UI
can render a localized name instead of the raw span identifier.
2026-05-27 08:54:09 +00:00
// Close the matching root span so the timeline stops showing
// "进行中" after dead-letter exhaustion. Best-effort: nil
// tracker / missing attempt / missing root all no-op cleanly.
if tracker != nil && probe . Attempt > 0 {
tracker . FinalizeAttempt ( ctx , probe . KnowledgeID , probe . Attempt ,
types . SpanStatusFailed , nil , "TASK_TIMEOUT" , errMsg )
}
2026-05-27 05:17:08 +00:00
logger . Infof ( ctx , "dead-letter callback: marked knowledge %s as failed (task=%s)" , probe . KnowledgeID , t . Type ( ) )
}
}
2026-06-16 04:08:00 +00:00
func markKnowledgeListDeleteFailed (
ctx context . Context ,
repo interfaces . KnowledgeRepository ,
t * asynq . Task ,
taskErr error ,
) {
var payload deadLetterKnowledgeListDeletePayload
if err := json . Unmarshal ( t . Payload ( ) , & payload ) ; err != nil || len ( payload . KnowledgeIDs ) == 0 {
return
}
errMsg := "delete task exhausted retries: " + taskErr . Error ( )
if len ( errMsg ) > 8192 {
errMsg = errMsg [ : 8192 ]
}
for _ , knowledgeID := range payload . KnowledgeIDs {
if knowledgeID == "" {
continue
}
updated , err := repo . UpdateActiveDeletingKnowledgeColumns ( ctx , knowledgeID , map [ string ] interface { } {
"parse_status" : types . ParseStatusFailed ,
"error_message" : errMsg ,
} )
if err != nil {
logger . Warnf ( ctx , "dead-letter callback: failed to mark delete failure for knowledge %s: %v" , knowledgeID , err )
continue
}
if ! updated {
logger . Infof ( ctx , "dead-letter callback: skipped marking knowledge %s after delete task exhaustion because it is no longer active deleting" , knowledgeID )
continue
}
logger . Infof ( ctx , "dead-letter callback: marked knowledge %s as failed after delete task exhausted retries" , knowledgeID )
}
}