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).
This commit is contained in:
wizardchen
2026-07-09 18:13:09 +08:00
committed by lyingbug
parent 76a8092483
commit 63198c5d9f
10 changed files with 516 additions and 3 deletions
+29
View File
@@ -78,6 +78,7 @@ import (
"github.com/Tencent/WeKnora/internal/mcp"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/models/limiter"
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
"github.com/Tencent/WeKnora/internal/router"
"github.com/Tencent/WeKnora/internal/stream"
@@ -274,6 +275,10 @@ func BuildContainer(container *dig.Container) *dig.Container {
// dequeue of pending/scheduled/retry tasks + active-task cancel).
must(container.Provide(router.NewAsynqInspector))
must(container.Provide(router.NewAsynqTaskInspector))
// Install the distributed per-model chat concurrency governor. Only
// available with Redis (the shared semaphore backend); Lite mode is
// single-process and low-volume, so it runs ungated.
must(container.Invoke(registerModelConcurrencyLimiter))
} else {
syncExec := router.NewSyncTaskExecutor()
must(container.Provide(func() interfaces.TaskEnqueuer { return syncExec }))
@@ -436,6 +441,30 @@ func initLangfuse() (*langfuse.Manager, error) {
return langfuse.Init(cfg)
}
// defaultModelMaxConcurrency is the per-model cap on concurrent background
// (ingestion/enrichment) chat calls when WEKNORA_MODEL_MAX_CONCURRENCY /
// model.max_concurrency is unset. summary / question / graph enrichment all
// share the same model, so this bounds their combined pressure on one provider
// across every replica. Interactive chat is never gated.
const defaultModelMaxConcurrency = 8
// registerModelConcurrencyLimiter builds the Redis-backed per-model chat
// concurrency governor and installs it into the chat package. The limit is
// resolved from system settings / env, defaulting to defaultModelMaxConcurrency.
func registerModelConcurrencyLimiter(rdb *redis.Client, ss interfaces.SystemSettingService) {
limit := defaultModelMaxConcurrency
if ss != nil {
n := ss.GetInt(context.Background(), "model.max_concurrency",
"WEKNORA_MODEL_MAX_CONCURRENCY", int64(defaultModelMaxConcurrency))
if n > 0 {
limit = int(n)
}
}
chat.SetConcurrencyLimiter(limiter.NewRedisLimiter(rdb), limit)
logger.Infof(context.Background(),
"[ModelLimiter] background chat concurrency governed per-model, limit=%d (distributed via redis)", limit)
}
func initRedisClient() (*redis.Client, error) {
redisAddr := os.Getenv("REDIS_ADDR")
if redisAddr == "" {