feat(system): expose model concurrency stats on runtime queues dashboard

Surface per-model active/waiting/limit from the background task limiter so admins can distinguish task scheduling from model-service throttling, with full i18n coverage.
This commit is contained in:
wizardchen
2026-07-11 07:14:35 +08:00
committed by lyingbug
parent 80556fbaa7
commit b9cccc7bee
12 changed files with 286 additions and 22 deletions
+2 -2
View File
@@ -35,13 +35,13 @@ func (w *concurrencyChat) GetModelName() string { return w.inner.GetModelName()
func (w *concurrencyChat) GetModelID() string { return w.inner.GetModelID() }
func (w *concurrencyChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) {
release := limiter.GateN(ctx, w.inner.GetModelID(), w.limit)
release := limiter.GateNamedN(ctx, w.inner.GetModelID(), w.inner.GetModelName(), w.limit)
defer release()
return w.inner.Chat(ctx, messages, opts)
}
func (w *concurrencyChat) ChatStream(ctx context.Context, messages []Message, opts *ChatOptions) (<-chan types.StreamResponse, error) {
release := limiter.GateN(ctx, w.inner.GetModelID(), w.limit)
release := limiter.GateNamedN(ctx, w.inner.GetModelID(), w.inner.GetModelName(), w.limit)
ch, err := w.inner.ChatStream(ctx, messages, opts)
if err != nil || ch == nil {
release()
@@ -30,13 +30,13 @@ type concurrencyEmbedder struct {
}
func (w *concurrencyEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
release := limiter.GateN(ctx, w.inner.GetModelID(), w.limit)
release := limiter.GateNamedN(ctx, w.inner.GetModelID(), w.inner.GetModelName(), w.limit)
defer release()
return w.inner.Embed(ctx, text)
}
func (w *concurrencyEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
release := limiter.GateN(ctx, w.inner.GetModelID(), w.limit)
release := limiter.GateNamedN(ctx, w.inner.GetModelID(), w.inner.GetModelName(), w.limit)
defer release()
return w.inner.BatchEmbed(ctx, texts)
}
+65 -3
View File
@@ -2,6 +2,7 @@ package limiter
import (
"context"
"sort"
"sync"
"github.com/Tencent/WeKnora/internal/types"
@@ -53,6 +54,10 @@ func Gate(ctx context.Context, modelID string) func() {
// blocks a call permanently — a limiter/Redis outage or a cancelled context
// fails open.
func GateN(ctx context.Context, modelID string, modelLimit int) func() {
return GateNamedN(ctx, modelID, "", modelLimit)
}
func GateNamedN(ctx context.Context, modelID, modelName string, modelLimit int) func() {
governorMu.RLock()
l, defaultLimit := governor, governorN
governorMu.RUnlock()
@@ -64,6 +69,9 @@ func GateN(ctx context.Context, modelID string, modelLimit int) func() {
if l == nil || limit <= 0 || !types.IsBackgroundTask(ctx) {
return noop
}
if named, ok := l.(interface{ SetModelName(string, string) }); ok {
named.SetModelName(modelID, modelName)
}
release, err := l.Acquire(ctx, modelID, limit)
if err != nil || release == nil {
return noop
@@ -71,19 +79,38 @@ func GateN(ctx context.Context, modelID string, modelLimit int) func() {
return release
}
// RuntimeStats returns the semaphores observed by this process. Redis-backed
// limiters report cluster-wide active holders; waiting callers remain local to
// this instance by design.
func RuntimeStats(ctx context.Context) ([]RuntimeStat, bool, error) {
governorMu.RLock()
l := governor
governorMu.RUnlock()
inspector, ok := l.(runtimeInspectable)
if !ok || inspector == nil {
return []RuntimeStat{}, false, nil
}
stats, err := inspector.RuntimeStats(ctx)
if stats == nil {
stats = []RuntimeStat{}
}
return stats, true, err
}
// localLimiter is an in-process (single-node) counting semaphore keyed by
// model ID. It is the Lite-mode counterpart to the Redis limiter: Lite runs a
// single process with no Redis, so a shared distributed semaphore is neither
// available nor needed — but background ingestion can still burst the whole
// worker pool against one provider, so we still cap concurrency locally.
type localLimiter struct {
mu sync.Mutex
sems map[string]chan struct{}
mu sync.Mutex
sems map[string]chan struct{}
tracked map[string]*trackedSemaphore
}
// NewLocalLimiter builds an in-process per-key concurrency limiter.
func NewLocalLimiter() ModelConcurrencyLimiter {
return &localLimiter{sems: make(map[string]chan struct{})}
return &localLimiter{sems: make(map[string]chan struct{}), tracked: make(map[string]*trackedSemaphore)}
}
func (l *localLimiter) Acquire(ctx context.Context, key string, limit int) (func(), error) {
@@ -93,6 +120,12 @@ func (l *localLimiter) Acquire(ctx context.Context, key string, limit int) (func
l.mu.Lock()
sem, ok := l.sems[key]
tracked := l.tracked[key]
if tracked == nil {
tracked = &trackedSemaphore{}
l.tracked[key] = tracked
}
tracked.limit.Store(int64(limit))
if !ok {
// Capacity is fixed at first use for a key; the limit is a
// process-wide constant, so it never changes across acquires.
@@ -100,6 +133,8 @@ func (l *localLimiter) Acquire(ctx context.Context, key string, limit int) (func
l.sems[key] = sem
}
l.mu.Unlock()
tracked.waiting.Add(1)
defer tracked.waiting.Add(-1)
select {
case sem <- struct{}{}:
@@ -110,3 +145,30 @@ func (l *localLimiter) Acquire(ctx context.Context, key string, limit int) (func
return noop, nil
}
}
func (l *localLimiter) RuntimeStats(_ context.Context) ([]RuntimeStat, error) {
l.mu.Lock()
defer l.mu.Unlock()
stats := make([]RuntimeStat, 0, len(l.sems))
for modelID, sem := range l.sems {
tracked := l.tracked[modelID]
name, _ := tracked.name.Load().(string)
stats = append(stats, RuntimeStat{ModelID: modelID, Name: name, Active: int64(len(sem)), Waiting: tracked.waiting.Load(), Limit: int(tracked.limit.Load())})
}
sort.Slice(stats, func(i, j int) bool { return stats[i].ModelID < stats[j].ModelID })
return stats, nil
}
func (l *localLimiter) SetModelName(modelID, name string) {
if modelID == "" || name == "" {
return
}
l.mu.Lock()
tracked := l.tracked[modelID]
if tracked == nil {
tracked = &trackedSemaphore{}
l.tracked[modelID] = tracked
}
l.mu.Unlock()
tracked.name.Store(name)
}
+70 -5
View File
@@ -15,7 +15,10 @@ package limiter
import (
"context"
"sort"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/Tencent/WeKnora/internal/logger"
@@ -34,15 +37,38 @@ type ModelConcurrencyLimiter interface {
Acquire(ctx context.Context, key string, limit int) (release func(), err error)
}
// RuntimeStat is a point-in-time view of a model semaphore. Active is
// cluster-wide for the Redis backend and process-local in Lite mode. Waiting is
// deliberately process-local: waiters block in application processes and are
// not represented in Redis.
type RuntimeStat struct {
ModelID string `json:"model_id"`
Name string `json:"name"`
Active int64 `json:"active"`
Waiting int64 `json:"waiting"`
Limit int `json:"limit"`
}
type runtimeInspectable interface {
RuntimeStats(context.Context) ([]RuntimeStat, error)
}
type trackedSemaphore struct {
limit atomic.Int64
waiting atomic.Int64
name atomic.Value // string
}
// noop is the release returned on the fail-open / passthrough paths.
func noop() {}
const (
// defaultLeaseTTL is how long a held slot survives without a heartbeat
// before another acquirer may reclaim it. Sized well above a typical
// enrichment LLM call so a slow provider never loses its slot mid-call;
// the heartbeat refreshes it for genuinely long calls.
defaultLeaseTTL = 5 * time.Minute
// defaultLeaseTTL is the crash-recovery window, not a request timeout.
// Live calls refresh their lease every ttl/3, so even a very long provider
// request keeps its slot. Keeping this short prevents an app/container
// restart from leaving an entire model budget apparently occupied for
// minutes while the replacement workers are blocked behind dead holders.
defaultLeaseTTL = 30 * time.Second
// defaultPollInterval is how often a waiting acquirer re-checks for a free
// slot. Small enough to stay responsive, large enough to avoid hammering
// Redis under contention.
@@ -75,6 +101,7 @@ type redisLimiter struct {
rdb *redis.Client
ttl time.Duration
pollInterval time.Duration
tracked sync.Map // model ID -> *trackedSemaphore
}
// NewRedisLimiter builds a distributed limiter backed by rdb. A nil client
@@ -93,6 +120,11 @@ func (l *redisLimiter) Acquire(ctx context.Context, key string, limit int) (func
}
zkey := keyPrefix + key
entry, _ := l.tracked.LoadOrStore(key, &trackedSemaphore{})
tracked := entry.(*trackedSemaphore)
tracked.limit.Store(int64(limit))
tracked.waiting.Add(1)
defer tracked.waiting.Add(-1)
token := uuid.NewString()
ttlMs := l.ttl.Milliseconds()
@@ -131,6 +163,39 @@ func (l *redisLimiter) Acquire(ctx context.Context, key string, limit int) (func
}
}
func (l *redisLimiter) RuntimeStats(ctx context.Context) ([]RuntimeStat, error) {
stats := make([]RuntimeStat, 0)
if l == nil || l.rdb == nil {
return stats, nil
}
var firstErr error
now := time.Now().UnixMilli()
l.tracked.Range(func(rawKey, rawValue any) bool {
modelID := rawKey.(string)
tracked := rawValue.(*trackedSemaphore)
active, err := l.rdb.ZCount(ctx, keyPrefix+modelID, strconv.FormatInt(now+1, 10), "+inf").Result()
if err != nil {
if firstErr == nil {
firstErr = err
}
return true
}
name, _ := tracked.name.Load().(string)
stats = append(stats, RuntimeStat{ModelID: modelID, Name: name, Active: active, Waiting: tracked.waiting.Load(), Limit: int(tracked.limit.Load())})
return true
})
sort.Slice(stats, func(i, j int) bool { return stats[i].ModelID < stats[j].ModelID })
return stats, firstErr
}
func (l *redisLimiter) SetModelName(modelID, name string) {
if modelID == "" || name == "" {
return
}
entry, _ := l.tracked.LoadOrStore(modelID, &trackedSemaphore{})
entry.(*trackedSemaphore).name.Store(name)
}
// hold starts a heartbeat that refreshes the lease and returns an idempotent
// release that stops the heartbeat and drops the slot.
func (l *redisLimiter) hold(zkey, token string) func() {
+1 -1
View File
@@ -22,7 +22,7 @@ func (w *concurrencyVLM) GetModelName() string { return w.inner.GetModelName() }
func (w *concurrencyVLM) GetModelID() string { return w.inner.GetModelID() }
func (w *concurrencyVLM) Predict(ctx context.Context, imgBytes [][]byte, prompt string) (string, error) {
release := limiter.GateN(ctx, w.inner.GetModelID(), w.limit)
release := limiter.GateNamedN(ctx, w.inner.GetModelID(), w.inner.GetModelName(), w.limit)
defer release()
return w.inner.Predict(ctx, imgBytes, prompt)
}