feat(configuration): update asynq concurrency settings and enhance FAQ handling

- Increased the default worker pool size for the asynq server from 16 to 32 to improve performance during concurrent uploads.
- Updated the .env.example and docker-compose.yml files to reflect the new default concurrency setting.
- Enhanced the handling of FAQ entries in the tool results, ensuring distinct identification through standard questions, improving user experience and clarity in the output.
- Refactored related components to utilize the new FAQ attributes, ensuring consistent display and interaction across the application.
This commit is contained in:
wizardchen
2026-06-04 14:21:50 +08:00
committed by lyingbug
parent 8a3e21cd46
commit 035093dc35
14 changed files with 330 additions and 28 deletions
+13 -1
View File
@@ -1566,7 +1566,7 @@ func (s *knowledgeService) ensureFAQKnowledge(
KnowledgeBaseID: kb.ID,
Type: types.KnowledgeTypeFAQ,
Channel: types.ChannelWeb,
Title: fmt.Sprintf("%s - FAQ", kb.Name),
Title: buildFAQKnowledgeTitle(kb.Name),
Description: "FAQ 条目容器",
Source: types.KnowledgeTypeFAQ,
ParseStatus: "completed",
@@ -1581,6 +1581,18 @@ func (s *knowledgeService) ensureFAQKnowledge(
return knowledge, nil
}
// buildFAQKnowledgeTitle derives the display title for the FAQ container
// knowledge. The title is simply the knowledge base name (falling back to "FAQ"
// when empty) — no suffix is appended, so a KB named "FAQ" stays "FAQ" instead
// of becoming the redundant "FAQ - FAQ".
func buildFAQKnowledgeTitle(kbName string) string {
name := strings.TrimSpace(kbName)
if name == "" {
return "FAQ"
}
return name
}
func (s *knowledgeService) chunkToFAQEntry(chunk *types.Chunk, kb *types.KnowledgeBase, tagSeqIDMap map[string]int64) (*types.FAQEntry, error) {
meta, err := chunk.FAQMetadata()
if err != nil {
@@ -28,6 +28,7 @@ import (
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/robfig/cron/v3"
"gorm.io/gorm"
)
@@ -38,6 +39,13 @@ type HousekeepingService struct {
cfg *config.Config
cron *cron.Cron
// inspector lets the sweep distinguish a genuinely orphaned row from
// one whose enrichment subtasks are merely backlogged behind a busy
// queue (no span heartbeat yet because no worker has picked them up).
// nil-safe — a nil inspector disables the queue check and the sweep
// falls back to the span/updated_at heuristics alone.
inspector interfaces.TaskInspector
mu sync.Mutex
started bool
}
@@ -45,10 +53,13 @@ type HousekeepingService struct {
// NewHousekeepingService constructs a HousekeepingService. It does NOT start
// the cron — call Start in the application bootstrap so a misconfigured
// cron schedule cannot prevent the rest of the service from coming up.
func NewHousekeepingService(db *gorm.DB, cfg *config.Config) *HousekeepingService {
func NewHousekeepingService(
db *gorm.DB, cfg *config.Config, inspector interfaces.TaskInspector,
) *HousekeepingService {
return &HousekeepingService{
db: db,
cfg: cfg,
db: db,
cfg: cfg,
inspector: inspector,
cron: cron.New(cron.WithSeconds(), cron.WithChain(
cron.Recover(cron.DefaultLogger),
)),
@@ -132,6 +143,18 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
}
stuck := h.filterByLastSpanActivity(ctx, candidates, cutoff)
spanSkipped := len(candidates) - len(stuck)
// Second-stage gate: a row can have a stale span heartbeat yet still
// be perfectly healthy when its enrichment subtasks (summary /
// question / graph / wiki) are merely backlogged behind a busy queue
// — no worker has picked them up, so no span has been written since
// post-process fanned them out. Killing such a row is the false-
// positive users hit under heavy upload bursts. Drop any candidate
// that still has a queued/active task referencing it; only rows with
// nothing left in the queue are treated as genuinely orphaned.
stuck, queueSkipped := h.filterOutQueued(ctx, stuck)
if len(stuck) > 0 {
stuckIDs := make([]string, 0, len(stuck))
for _, k := range stuck {
@@ -152,13 +175,22 @@ func (h *HousekeepingService) runSweep(ctx context.Context) {
res.RowsAffected, threshold)
}
}
if active := len(candidates) - len(stuck); active > 0 {
if spanSkipped > 0 {
// Visibility into "we considered killing N rows but their
// span tree showed they're still progressing". Ops can grep
// for this if they suspect housekeeping over- or under-fires.
logger.Infof(ctx,
"[Housekeeping] %d candidate(s) skipped — span heartbeat within threshold",
active)
spanSkipped)
}
if queueSkipped > 0 {
// Visibility into "stale span heartbeat but tasks still queued"
// — i.e. backpressure, not a stuck row. Persistent counts here
// mean the queue is the bottleneck (raise WEKNORA_ASYNQ_CONCURRENCY
// or document_process_timeout), not that housekeeping misfires.
logger.Infof(ctx,
"[Housekeeping] %d candidate(s) skipped — tasks still queued (backpressure, not stuck)",
queueSkipped)
}
// Sweep B: knowledge summary stuck. Summary is post-parse; threshold
@@ -233,6 +265,39 @@ func (h *HousekeepingService) filterByLastSpanActivity(ctx context.Context, cand
return out
}
// filterOutQueued returns the subset of candidates that have NO task left
// in the queue backend, plus a count of how many were dropped because a
// task still references them. A dropped candidate is "backlogged, not
// orphaned" — its enrichment subtasks are waiting for a worker, so the
// missing span heartbeat is expected and recovering it would be a false
// positive. When no inspector is wired (nil) the gate is a pass-through
// so behaviour matches the pre-existing span-only sweep. On inspector
// error we fail safe by KEEPING the candidate as stuck (recover it),
// matching the span heartbeat query's fail-safe direction.
func (h *HousekeepingService) filterOutQueued(
ctx context.Context, candidates []types.Knowledge,
) (kept []types.Knowledge, skipped int) {
if h.inspector == nil || len(candidates) == 0 {
return candidates, 0
}
out := candidates[:0]
for _, k := range candidates {
queued, err := h.inspector.HasQueuedTasksForKnowledge(ctx, k.ID)
if err != nil {
logger.Warnf(ctx,
"[Housekeeping] queue probe failed for %s: %v (will fail safe and treat as stuck)", k.ID, err)
out = append(out, k)
continue
}
if queued {
skipped++
continue
}
out = append(out, k)
}
return out, skipped
}
// parseHeartbeatTime accepts the timestamp formats Postgres and SQLite
// emit for a TIMESTAMP column read back through MAX(). Returns false if
// none parse — the caller treats unparseable rows as "no heartbeat",
@@ -2,11 +2,13 @@ package service
import (
"context"
"errors"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
@@ -95,14 +97,41 @@ func insertSpan(t *testing.T, db *gorm.DB, kid string, attempt int, spanID, stat
).Error)
}
// fakeTaskInspector is a controllable TaskInspector for the housekeeping
// suite. queued maps knowledge_id → "still has a queued task"; err forces
// the probe to fail so the fail-safe branch can be exercised.
type fakeTaskInspector struct {
queued map[string]bool
err error
}
func (f fakeTaskInspector) CancelTasksForKnowledge(
_ context.Context, _ string,
) (int, int, error) {
return 0, 0, nil
}
func (f fakeTaskInspector) HasQueuedTasksForKnowledge(
_ context.Context, knowledgeID string,
) (bool, error) {
if f.err != nil {
return false, f.err
}
return f.queued[knowledgeID], nil
}
func newHousekeepingSvcForTest(db *gorm.DB) *HousekeepingService {
return newHousekeepingSvcWithInspector(db, fakeTaskInspector{})
}
func newHousekeepingSvcWithInspector(db *gorm.DB, inspector interfaces.TaskInspector) *HousekeepingService {
cfg := &config.Config{KnowledgeBase: &config.KnowledgeBaseConfig{
// 1h floor + 10min buffer = 70min cutoff. Tight enough to keep
// the test's relative timestamps in seconds; the production
// default of 2h+10min is just a constant scale factor.
DocumentProcessTimeout: 1 * time.Hour,
}}
return NewHousekeepingService(db, cfg)
return NewHousekeepingService(db, cfg, inspector)
}
// TestHousekeeping_RecoversAbandoned exercises the happy path: a
@@ -170,6 +199,52 @@ func TestHousekeeping_NoFalseKill_StaleSpanRecovers(t *testing.T) {
"genuinely stuck knowledge (knowledge AND spans both stale) must still be recovered")
}
// TestHousekeeping_NoFalseKill_TasksStillQueued is the regression test
// for the backpressure case: a finalizing row whose span heartbeat has
// gone stale (enrichment subtasks fanned out but no worker has picked
// them up yet) must NOT be killed while its tasks are still queued.
func TestHousekeeping_NoFalseKill_TasksStillQueued(t *testing.T) {
db := setupHousekeepingDB(t)
svc := newHousekeepingSvcWithInspector(db, fakeTaskInspector{
queued: map[string]bool{"kid-backlogged": true},
})
stale := time.Now().Add(-3 * time.Hour)
// finalizing + stale knowledge + stale span: span-only heuristics
// would flag this as stuck, but the queue still holds its subtasks.
insertKnowledge(t, db, "kid-backlogged", types.ParseStatusFinalizing, stale)
insertSpan(t, db, "kid-backlogged", 1, "post-1", types.SpanStatusRunning, stale)
svc.runSweep(context.Background())
var status string
require.NoError(t, db.Raw(
`SELECT parse_status FROM knowledges WHERE id = ?`, "kid-backlogged",
).Row().Scan(&status))
assert.Equal(t, types.ParseStatusFinalizing, status,
"finalizing row with tasks still queued must NOT be flipped to failed")
}
// TestHousekeeping_QueueProbeError_FailsSafe confirms the fail-safe
// direction: when the queue probe errors we still recover the row rather
// than leaving it stranded forever.
func TestHousekeeping_QueueProbeError_FailsSafe(t *testing.T) {
db := setupHousekeepingDB(t)
svc := newHousekeepingSvcWithInspector(db, fakeTaskInspector{
err: errors.New("redis unavailable"),
})
stale := time.Now().Add(-3 * time.Hour)
insertKnowledge(t, db, "kid-probeerr", types.ParseStatusProcessing, stale)
svc.runSweep(context.Background())
var status string
require.NoError(t, db.Raw(
`SELECT parse_status FROM knowledges WHERE id = ?`, "kid-probeerr",
).Row().Scan(&status))
assert.Equal(t, types.ParseStatusFailed, status,
"queue probe error must fail safe and still recover the stuck row")
}
// TestHousekeeping_PreservesRecentlyTouched: any knowledge whose
// updated_at is within the cutoff is left alone — that's the cheap
// fast path that doesn't even consult the spans table.
@@ -168,11 +168,11 @@ var registry = map[string]settingSpec{
// asynq.concurrency is the asynq worker pool size (parallel in-flight
// tasks). Read once when the asynq server starts — changing it in the
// UI requires a process restart to take effect. Mirrors
// WEKNORA_ASYNQ_CONCURRENCY (default 16).
// WEKNORA_ASYNQ_CONCURRENCY (default 32).
"asynq.concurrency": {
Type: "int",
EnvName: "WEKNORA_ASYNQ_CONCURRENCY",
Default: int64(16),
Default: int64(32),
Category: "worker",
RequiresRestart: true,
Description: "异步任务 worker 并发数(asynq 线程池大小)。" +