From fe72ddf1ae7e027958ca0724f48fbcf64e037987 Mon Sep 17 00:00:00 2001 From: bin-bash-dev <205939566+bin-bash-dev@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:56:32 +0800 Subject: [PATCH] fix(moderation): allocate async moderation queue on demand MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 问题:NewContentModerationService 在构造时就执行 make(chan contentModerationTask, maxContentModerationQueueSize)。 maxContentModerationQueueSize=100000,单个任务 288 字节,因此每个实例一 构造就常驻约 28.8MB,与是否启用异步审核、是否有流量都无关。service 包测 试会创建数百个短生命周期实例,测试进程的提交内存随之涨到 GiB 级;生产上 任何额外构造的实例也要白白付出同样的代价。 根因:队列深度按允许的最大值预分配,而真正的丢弃判据 len(queue) >= cfg.QueueSize 只依赖运行期配置,并不需要预先占满容量。 修法: - 构造函数不再创建队列,只标记 asyncQueueLazy;首次入队时按 min(64, QueueSize) 创建,满且仍低于 QueueSize 时按 2 倍扩容(上限 QueueSize),迁移已排队任务;运行期调大 QueueSize 也能继续扩容。 - 丢弃判据仍是 len >= QueueSize,丢弃计数与告警日志保持不变。 - 未经构造函数创建的零值服务入队仍是 no-op(不计数、不告警)。 - 队列创建/扩容时关闭并替换 asyncWake 广播唤醒 worker,阻塞在旧 channel 上的 worker 会重新读取新队列,不空转、不漏取任务。 - GetStatus 与日志读取队列长度改为加锁读取,不会触发分配。 测试: - content_moderation_queue_contract_test.go 只使用既有接口:构造后不预 留队列;在独立子进程中测量 64 个空闲实例的堆增量(旧实现约 28,803,490 字节/实例,修复后约 451 字节/实例,阈值 64KiB); QueueSize=8 时收 8 丢 12、记录路径同样受限、4096 全收且调大到 8192 后继续接收;零值服务 no-op;真实 worker 并发消费 400 条记录不丢不重。 结构与内存用例在修复前失败,其余语义用例修复前后均通过。 - content_moderation_queue_lazy_test.go 用 synctest 覆盖初始容量与扩容 上限、多生产者/消费者恰好一次投递、扩容期间消费者持续读取、首次创建 与替换队列时的唤醒、取消与空闲超时。 --- .../internal/service/content_moderation.go | 236 +++++++-- .../content_moderation_queue_contract_test.go | 213 ++++++++ .../content_moderation_queue_lazy_test.go | 496 ++++++++++++++++++ 3 files changed, 894 insertions(+), 51 deletions(-) create mode 100644 backend/internal/service/content_moderation_queue_contract_test.go create mode 100644 backend/internal/service/content_moderation_queue_lazy_test.go diff --git a/backend/internal/service/content_moderation.go b/backend/internal/service/content_moderation.go index 95bbfdaf9c..d045a55cd7 100644 --- a/backend/internal/service/content_moderation.go +++ b/backend/internal/service/content_moderation.go @@ -521,7 +521,10 @@ type ContentModerationService struct { emailService *EmailService httpClient *http.Client moderationProxyCache atomic.Pointer[moderationProxyURLCacheEntry] + asyncQueueMu sync.RWMutex asyncQueue chan contentModerationTask + asyncWake chan struct{} + asyncQueueLazy bool workerCount int apiKeyCursor atomic.Uint64 asyncActive atomic.Int64 @@ -605,7 +608,8 @@ func NewContentModerationService( emailService: emailService, httpClient: servertiming.InstrumentClient(nil), workerCount: maxContentModerationWorkerCount, - asyncQueue: make(chan contentModerationTask, maxContentModerationQueueSize), + asyncQueueLazy: true, + asyncWake: make(chan struct{}), keyHealth: make(map[string]*contentModerationKeyHealth), } if settingRepo != nil && repo != nil { @@ -1064,7 +1068,7 @@ func (s *ContentModerationService) Check(ctx context.Context, input ContentModer "group_id", contentModerationLogGroupID(input.GroupID), "endpoint", input.Endpoint, "protocol", input.Protocol, - "queue_len", len(s.asyncQueue)) + "queue_len", len(s.asyncQueueOf())) s.enqueueAsync(input, cfg, content, hashText) return allow, nil } @@ -1187,17 +1191,133 @@ func (s *ContentModerationService) recordPreBlockSyncMetric(latencyMS int, actio } } -func (s *ContentModerationService) enqueueAsync(input ContentModerationCheckInput, cfg *ContentModerationConfig, content ContentModerationInput, hashText string) { - if s == nil || s.asyncQueue == nil { +// contentModerationInitialQueueCapacity is the starting depth of the worker +// queue. The queue grows on demand up to the configured QueueSize, so a service +// that never sees a burst does not reserve the whole configured depth. +const contentModerationInitialQueueCapacity = 64 + +// asyncQueueOf returns the current worker queue without allocating it. Callers +// that only inspect len/cap (status, logging) use this so reading the queue +// never forces the backing array into existence. +func (s *ContentModerationService) asyncQueueOf() chan contentModerationTask { + if s == nil { + return nil + } + s.asyncQueueMu.RLock() + queue := s.asyncQueue + s.asyncQueueMu.RUnlock() + return queue +} + +// queueDropThreshold reports how many pending tasks the configuration allows. +// This is the threshold the enqueue paths have always compared len() against. +func queueDropThreshold(cfg *ContentModerationConfig) int { + threshold := defaultContentModerationQueueSize + if cfg != nil && cfg.QueueSize > 0 { + threshold = cfg.QueueSize + } + if threshold > maxContentModerationQueueSize { + threshold = maxContentModerationQueueSize + } + if threshold < 1 { + threshold = 1 + } + return threshold +} + +// wakeWorkersLocked broadcasts to every waiting worker that the queue object +// changed (grown or replaced). Closing the channel wakes all current waiters; +// a fresh channel is installed for the next round. Callers must hold +// asyncQueueMu for writing. +func (s *ContentModerationService) wakeWorkersLocked() { + if s.asyncWake == nil { + s.asyncWake = make(chan struct{}) return } - queueSize := defaultContentModerationQueueSize - if cfg != nil && cfg.QueueSize > 0 { - queueSize = cfg.QueueSize + close(s.asyncWake) + s.asyncWake = make(chan struct{}) +} + +// growAsyncQueueLocked doubles the channel capacity, capped at the configured +// drop threshold, and moves the pending tasks across. Callers must hold +// asyncQueueMu for writing. +func (s *ContentModerationService) growAsyncQueueLocked(threshold int) { + current := s.asyncQueue + next := cap(current) * 2 + if next < contentModerationInitialQueueCapacity { + next = contentModerationInitialQueueCapacity } - if len(s.asyncQueue) >= queueSize { - slog.Warn("content_moderation.async_queue_full", "user_id", input.UserID, "endpoint", input.Endpoint, "queue_size", queueSize) - s.asyncDropped.Add(1) + if next > threshold { + next = threshold + } + if next <= cap(current) { + return + } + grown := make(chan contentModerationTask, next) + for { + select { + case task := <-current: + grown <- task + default: + s.asyncQueue = grown + s.wakeWorkersLocked() + return + } + } +} + +// queueDisabled reports whether this service can never accept asynchronous +// work. A zero-value ContentModerationService has no queue and no lazy flag, so +// enqueues are ignored exactly as they were before the queue became lazy: no +// warning, no drop counter. +func (s *ContentModerationService) queueDisabled() bool { + if s == nil { + return true + } + s.asyncQueueMu.RLock() + defer s.asyncQueueMu.RUnlock() + return s.asyncQueue == nil && !s.asyncQueueLazy +} + +// enqueueTask appends one task when the queue is below the configured threshold. +// A zero-value ContentModerationService keeps the historical behaviour of +// silently ignoring enqueues (its channel was never initialised); services built +// by NewContentModerationService allocate their channel on first use and grow it +// on demand. +func (s *ContentModerationService) enqueueTask(cfg *ContentModerationConfig, task contentModerationTask) (bool, int) { + if s == nil { + return false, 0 + } + threshold := queueDropThreshold(cfg) + s.asyncQueueMu.Lock() + defer s.asyncQueueMu.Unlock() + if s.asyncQueue == nil { + if !s.asyncQueueLazy { + return false, threshold + } + initial := contentModerationInitialQueueCapacity + if initial > threshold { + initial = threshold + } + s.asyncQueue = make(chan contentModerationTask, initial) + s.wakeWorkersLocked() + } + if len(s.asyncQueue) >= threshold { + return false, threshold + } + if len(s.asyncQueue) >= cap(s.asyncQueue) { + s.growAsyncQueueLocked(threshold) + } + select { + case s.asyncQueue <- task: + return true, threshold + default: + return false, threshold + } +} + +func (s *ContentModerationService) enqueueAsync(input ContentModerationCheckInput, cfg *ContentModerationConfig, content ContentModerationInput, hashText string) { + if s.queueDisabled() { return } task := contentModerationTask{ @@ -1206,33 +1326,20 @@ func (s *ContentModerationService) enqueueAsync(input ContentModerationCheckInpu inputHash: hashText, enqueuedAt: time.Now(), } - select { - case s.asyncQueue <- task: + accepted, queueSize := s.enqueueTask(cfg, task) + if accepted { s.asyncEnqueued.Add(1) - default: - slog.Warn("content_moderation.async_queue_full", "user_id", input.UserID, "endpoint", input.Endpoint) - s.asyncDropped.Add(1) + return } + slog.Warn("content_moderation.async_queue_full", "user_id", input.UserID, "endpoint", input.Endpoint, "queue_size", queueSize) + s.asyncDropped.Add(1) } func (s *ContentModerationService) enqueueRecord(input ContentModerationCheckInput, cfg *ContentModerationConfig, log *ContentModerationLog, inputHash string, recordHash bool, applySideEffects bool) { - if s == nil || s.asyncQueue == nil || log == nil { + if log == nil || s.queueDisabled() { return } - queueSize := defaultContentModerationQueueSize - if cfg != nil && cfg.QueueSize > 0 { - queueSize = cfg.QueueSize - } - if len(s.asyncQueue) >= queueSize { - slog.Warn("content_moderation.record_queue_full", - "user_id", input.UserID, - "endpoint", input.Endpoint, - "action", log.Action, - "queue_size", queueSize) - s.asyncDropped.Add(1) - return - } - task := contentModerationTask{ + accepted, queueSize := s.enqueueTask(cfg, contentModerationTask{ input: input, inputHash: inputHash, log: log, @@ -1240,17 +1347,17 @@ func (s *ContentModerationService) enqueueRecord(input ContentModerationCheckInp recordHash: recordHash, applySideEffects: applySideEffects, enqueuedAt: time.Now(), - } - select { - case s.asyncQueue <- task: + }) + if accepted { s.asyncEnqueued.Add(1) - default: - slog.Warn("content_moderation.record_queue_full", - "user_id", input.UserID, - "endpoint", input.Endpoint, - "action", log.Action) - s.asyncDropped.Add(1) + return } + slog.Warn("content_moderation.record_queue_full", + "user_id", input.UserID, + "endpoint", input.Endpoint, + "action", log.Action, + "queue_size", queueSize) + s.asyncDropped.Add(1) } func (s *ContentModerationService) worker(id int) { @@ -1308,21 +1415,48 @@ func (s *ContentModerationService) worker(id int) { func (s *ContentModerationService) dequeueAsyncTask(ctx context.Context, idleWait time.Duration) (contentModerationTask, bool) { var zero contentModerationTask - if s == nil || s.asyncQueue == nil { + if s == nil { return zero, false } if idleWait <= 0 { idleWait = time.Second } - timer := time.NewTimer(idleWait) - defer timer.Stop() - select { - case task, ok := <-s.asyncQueue: - return task, ok - case <-ctx.Done(): - return zero, false - case <-timer.C: - return zero, false + for { + timer := time.NewTimer(idleWait) + s.asyncQueueMu.RLock() + queue := s.asyncQueue + wake := s.asyncWake + s.asyncQueueMu.RUnlock() + + if queue == nil { + // Nothing was enqueued yet. Wait for the first enqueue instead of + // spinning; the timer keeps shutdown paths bounded. + select { + case <-wake: + timer.Stop() + continue + case <-ctx.Done(): + timer.Stop() + return zero, false + case <-timer.C: + return zero, false + } + } + + select { + case task, ok := <-queue: + timer.Stop() + return task, ok + case <-wake: + // The queue object was created, grown or replaced; re-read it. + timer.Stop() + continue + case <-ctx.Done(): + timer.Stop() + return zero, false + case <-timer.C: + return zero, false + } } } @@ -1427,8 +1561,8 @@ func (s *ContentModerationService) GetStatus(ctx context.Context) (*ContentModer preBlockAvgLatency = s.preBlockLatencyTotalMS.Load() / preBlockChecked } queueLength := 0 - if s.asyncQueue != nil { - queueLength = len(s.asyncQueue) + if queue := s.asyncQueueOf(); queue != nil { + queueLength = len(queue) } queueUsage := 0.0 if cfg.QueueSize > 0 { diff --git a/backend/internal/service/content_moderation_queue_contract_test.go b/backend/internal/service/content_moderation_queue_contract_test.go new file mode 100644 index 0000000000..cbd36e4234 --- /dev/null +++ b/backend/internal/service/content_moderation_queue_contract_test.go @@ -0,0 +1,213 @@ +package service + +import ( + "context" + "fmt" + "os" + "os/exec" + "runtime" + "strings" + "sync" + "testing" + "time" + "unsafe" +) + +// 本文件只使用构造函数、enqueueAsync/enqueueRecord、计数器与真实 worker 等既有接口, +// 用来钉住异步审核队列对外可见的契约:空闲实例不得预留整条队列,QueueSize 仍是 +// 丢弃阈值,零值服务入队仍是 no-op,真实 worker 消费不丢不重。 + +const contentModerationQueueChildProcessEnv = "SUB2API_CONTENT_MODERATION_QUEUE_CHILD" + +// TestContentModerationIdleServiceDoesNotReserveQueue 是确定性的结构断言: +// 构造后、首次入队前不得已分配任务队列。旧实现在构造时就创建 +// maxContentModerationQueueSize 深度的 channel。 +func TestContentModerationIdleServiceDoesNotReserveQueue(t *testing.T) { + svc := NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil) + if reserved := cap(svc.asyncQueue); reserved != 0 { + t.Fatalf("new ContentModerationService reserved a %d-slot task queue (%d bytes) before any enqueue, want none", + reserved, reserved*int(unsafe.Sizeof(contentModerationTask{}))) + } +} + +// TestContentModerationIdleServiceMemoryIsBounded 测量空闲实例的常驻堆增量。 +// +// 旧实现每个实例构造时占用 sizeof(contentModerationTask) * maxContentModerationQueueSize +// (约 28.8 MB),与是否启用异步审核无关。HeapAlloc 是进程级计数,而本包其它测试会留下 +// 常驻的审核 worker,因此测量放在只运行本用例的子进程里完成,父进程只传播结果。 +func TestContentModerationIdleServiceMemoryIsBounded(t *testing.T) { + if os.Getenv(contentModerationQueueChildProcessEnv) != "1" { + runContentModerationQueueTestInChildProcess(t, "TestContentModerationIdleServiceMemoryIsBounded") + return + } + + const instances = 64 + // 旧实现约 28.8 MB/实例;64 KiB 给分配器噪声留足余量,同时仍能识别任何预分配。 + const maxIdleBytesPerInstance = 64 * 1024 + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + services := make([]*ContentModerationService, 0, instances) + for range instances { + services = append(services, NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil)) + } + runtime.GC() + runtime.ReadMemStats(&after) + runtime.KeepAlive(services) + + perInstance := int64(0) + if after.HeapAlloc > before.HeapAlloc { + perInstance = int64(after.HeapAlloc-before.HeapAlloc) / instances + } + t.Logf("idle ContentModerationService retains %d heap bytes/instance over %d instances", perInstance, instances) + if perInstance > maxIdleBytesPerInstance { + t.Fatalf("idle ContentModerationService retains %d bytes/instance, want <= %d (a preallocated %d-slot queue is %d bytes)", + perInstance, maxIdleBytesPerInstance, maxContentModerationQueueSize, + maxContentModerationQueueSize*int(unsafe.Sizeof(contentModerationTask{}))) + } +} + +// runContentModerationQueueTestInChildProcess 在新的测试进程里只运行 name 指定的用例, +// 子进程失败或超时都会让父用例失败。 +func runContentModerationQueueTestInChildProcess(t *testing.T, name string) { + t.Helper() + executable, err := os.Executable() + if err != nil { + t.Fatalf("locate test binary: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, executable, "-test.run=^"+name+"$", "-test.count=1", "-test.v") + cmd.Env = append(os.Environ(), contentModerationQueueChildProcessEnv+"=1") + output, runErr := cmd.CombinedOutput() + if runErr != nil { + t.Fatalf("isolated %s failed: %v\n%s", name, runErr, output) + } + if !strings.Contains(string(output), "--- PASS: "+name) { + t.Fatalf("isolated child did not run %s\n%s", name, output) + } + t.Logf("isolated child output:\n%s", output) +} + +// TestContentModerationQueueSizeStillBoundsPendingTasks 钉住丢弃语义:待处理任务数达到 +// QueueSize 即丢弃并计数;配置调大后可以继续接收;零值服务(未经构造函数)入队仍被忽略。 +func TestContentModerationQueueSizeStillBoundsPendingTasks(t *testing.T) { + cfg := defaultContentModerationConfig() + cfg.QueueSize = 8 + svc := NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil) + for i := range 20 { + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, fmt.Sprintf("bounded-%d", i)) + } + if got := svc.asyncEnqueued.Load(); got != 8 { + t.Fatalf("asyncEnqueued = %d for QueueSize=8, want 8", got) + } + if got := svc.asyncDropped.Load(); got != 12 { + t.Fatalf("asyncDropped = %d for QueueSize=8, want 12", got) + } + if got := len(svc.asyncQueue); got != 8 { + t.Fatalf("pending tasks = %d, want 8", got) + } + svc.enqueueRecord(ContentModerationCheckInput{}, cfg, &ContentModerationLog{RequestID: "record-over-limit"}, "", false, false) + if got := svc.asyncDropped.Load(); got != 13 { + t.Fatalf("asyncDropped = %d after a record enqueue on a full queue, want 13", got) + } + + large := defaultContentModerationConfig() + large.QueueSize = 4096 + grown := NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil) + for i := range 4096 { + grown.enqueueAsync(ContentModerationCheckInput{}, large, ContentModerationInput{}, fmt.Sprintf("large-%d", i)) + } + if got := grown.asyncEnqueued.Load(); got != 4096 { + t.Fatalf("asyncEnqueued = %d for QueueSize=4096, want 4096", got) + } + if got := grown.asyncDropped.Load(); got != 0 { + t.Fatalf("asyncDropped = %d below QueueSize=4096, want 0", got) + } + + // 运行期调大 QueueSize 后,已到达旧上限的队列必须能继续接收。 + raised := defaultContentModerationConfig() + raised.QueueSize = 8192 + for i := range 4096 { + grown.enqueueAsync(ContentModerationCheckInput{}, raised, ContentModerationInput{}, fmt.Sprintf("raised-%d", i)) + } + grown.enqueueAsync(ContentModerationCheckInput{}, raised, ContentModerationInput{}, "raised-over-limit") + if got := grown.asyncEnqueued.Load(); got != 8192 { + t.Fatalf("asyncEnqueued = %d after raising QueueSize to 8192, want 8192", got) + } + if got := grown.asyncDropped.Load(); got != 1 { + t.Fatalf("asyncDropped = %d after exceeding QueueSize=8192, want 1", got) + } + if got := len(grown.asyncQueue); got != 8192 { + t.Fatalf("pending tasks = %d, want 8192", got) + } + + zero := &ContentModerationService{} + zero.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, "zero") + zero.enqueueRecord(ContentModerationCheckInput{}, cfg, &ContentModerationLog{RequestID: "zero"}, "", false, false) + if zero.asyncEnqueued.Load() != 0 || zero.asyncDropped.Load() != 0 || zero.asyncQueue != nil { + t.Fatalf("zero-value service must ignore enqueues: enqueued=%d dropped=%d queue=%v", + zero.asyncEnqueued.Load(), zero.asyncDropped.Load(), zero.asyncQueue != nil) + } +} + +// TestContentModerationWorkerConsumesConcurrentQueue 走构造函数启动的真实 worker: +// 4 个生产者并发写入 400 条记录任务,每条必须恰好落库一次,队列最终清空。 +func TestContentModerationWorkerConsumesConcurrentQueue(t *testing.T) { + cfg := defaultContentModerationConfig() + cfg.Enabled = true + cfg.Mode = ContentModerationModePreBlock + cfg.WorkerCount = 4 + cfg.QueueSize = 4096 + svc, repo := newContentModerationModelFilterTestService(t, cfg) + + const producers = 4 + const perProducer = 100 + const total = producers * perProducer + var group sync.WaitGroup + for p := range producers { + group.Add(1) + go func(producer int) { + defer group.Done() + for i := range perProducer { + svc.enqueueRecord( + ContentModerationCheckInput{}, + cfg, + &ContentModerationLog{ + RequestID: fmt.Sprintf("worker-%d-%d", producer, i), + Mode: ContentModerationModePreBlock, + Action: ContentModerationActionAllow, + }, + "", + false, + false, + ) + } + }(p) + } + group.Wait() + + deadline := time.Now().Add(10 * time.Second) + for svc.asyncProcessed.Load() < total && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + + if got := svc.asyncEnqueued.Load(); got != total { + t.Fatalf("asyncEnqueued = %d, want %d", got, total) + } + if got := svc.asyncProcessed.Load(); got != total { + t.Fatalf("asyncProcessed = %d, want %d", got, total) + } + logs := repo.snapshotLogs() + if len(logs) != total { + t.Fatalf("persisted logs = %d, want %d", len(logs), total) + } + seen := make(map[string]struct{}, len(logs)) + for _, log := range logs { + if _, exists := seen[log.RequestID]; exists { + t.Fatalf("duplicate persisted request id %q", log.RequestID) + } + seen[log.RequestID] = struct{}{} + } +} diff --git a/backend/internal/service/content_moderation_queue_lazy_test.go b/backend/internal/service/content_moderation_queue_lazy_test.go new file mode 100644 index 0000000000..c0598ce280 --- /dev/null +++ b/backend/internal/service/content_moderation_queue_lazy_test.go @@ -0,0 +1,496 @@ +package service + +import ( + "context" + "fmt" + "sync" + "sync/atomic" + "testing" + "testing/synctest" + "time" +) + +// TestContentModerationQueueStartsSmallAndGrowsToQueueSize pins the lazy +// allocation shape: the first enqueue creates min(initial, QueueSize) slots, +// growth doubles the capacity, and capacity never exceeds the configured +// QueueSize drop threshold. +func TestContentModerationQueueStartsSmallAndGrowsToQueueSize(t *testing.T) { + small := defaultContentModerationConfig() + small.QueueSize = 8 + svc := NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil) + if svc.asyncQueueOf() != nil { + t.Fatal("new service must start without an allocated queue") + } + svc.enqueueAsync(ContentModerationCheckInput{}, small, ContentModerationInput{}, "small") + if got := cap(svc.asyncQueueOf()); got != 8 { + t.Fatalf("first queue capacity for QueueSize=8 = %d, want 8", got) + } + + cfg := defaultContentModerationConfig() + cfg.QueueSize = 100 + grown := NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil) + for i := 0; i < contentModerationInitialQueueCapacity; i++ { + grown.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, fmt.Sprintf("fill-%d", i)) + } + if got := cap(grown.asyncQueueOf()); got != contentModerationInitialQueueCapacity { + t.Fatalf("queue capacity before growth = %d, want %d", got, contentModerationInitialQueueCapacity) + } + grown.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, "grow") + if got := cap(grown.asyncQueueOf()); got != 100 { + t.Fatalf("queue capacity after growth = %d, want doubling capped at QueueSize=100", got) + } + if got := len(grown.asyncQueueOf()); got != contentModerationInitialQueueCapacity+1 { + t.Fatalf("pending tasks after growth = %d, want %d (growth must keep queued tasks)", got, contentModerationInitialQueueCapacity+1) + } +} + +// newConcurrentQueueTestService returns a constructor-built service with no +// setting repository, so it has the lazy queue but starts no worker goroutines. +// The queue tests drive dequeueAsyncTask directly, which is the exact call the +// worker loop makes. A real worker() cannot be used inside synctest because it +// has no stop handle; TestContentModerationWorkerConsumesConcurrentQueue covers +// the real worker loop separately. +func newConcurrentQueueTestService() *ContentModerationService { + return NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil) +} + +// TestContentModerationQueueConcurrentProducersAndConsumersExactlyOnce forces +// the lazy queue through several growth steps while four consumers are already +// parked, then releases them. It proves the properties the old single-producer +// test could not see: every unique task is consumed exactly once, growth does +// not drop or duplicate a task, no task is stranded after the consumers drain, +// and the queue actually grew beyond its initial 64-slot allocation. +func TestContentModerationQueueConcurrentProducersAndConsumersExactlyOnce(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + svc := newConcurrentQueueTestService() + cfg := defaultContentModerationConfig() + cfg.QueueSize = 4096 + + const producerCount = 8 + const perProducer = 200 + const consumerCount = 4 + const total = producerCount * perProducer + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + var mu sync.Mutex + received := make(map[string]int, total) + consumersDone := make(chan struct{}, consumerCount) + release := make(chan struct{}) + + for i := 0; i < consumerCount; i++ { + go func() { + defer func() { consumersDone <- struct{}{} }() + <-release + for { + task, ok := svc.dequeueAsyncTask(ctx, time.Minute) + if !ok { + return + } + mu.Lock() + received[task.inputHash]++ + mu.Unlock() + } + }() + } + synctest.Wait() // every consumer is durably parked on release + + var producers sync.WaitGroup + for p := 0; p < producerCount; p++ { + producers.Add(1) + go func(producer int) { + defer producers.Done() + for i := 0; i < perProducer; i++ { + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, fmt.Sprintf("p%d-%d", producer, i)) + } + }(p) + } + producers.Wait() + + if got := svc.asyncEnqueued.Load(); got != total { + t.Fatalf("asyncEnqueued = %d, want %d", got, total) + } + if got := svc.asyncDropped.Load(); got != 0 { + t.Fatalf("asyncDropped = %d, want 0 below the configured threshold", got) + } + if got := cap(svc.asyncQueueOf()); got <= contentModerationInitialQueueCapacity { + t.Fatalf("queue capacity = %d, want growth beyond the initial %d", got, contentModerationInitialQueueCapacity) + } + if got := len(svc.asyncQueueOf()); got != total { + t.Fatalf("queued before consumers released = %d, want %d", got, total) + } + + close(release) + synctest.Wait() + + mu.Lock() + unique := 0 + duplicates := 0 + emptyID := false + for id, count := range received { + if id == "" { + emptyID = true + } + unique++ + if count > 1 { + duplicates += count - 1 + } + } + mu.Unlock() + if emptyID { + t.Fatal("consumer received a task without an input hash") + } + if unique != total { + t.Fatalf("unique task ids consumed = %d, want %d", unique, total) + } + if duplicates != 0 { + t.Fatalf("duplicate deliveries = %d, want 0", duplicates) + } + if got := len(svc.asyncQueueOf()); got != 0 { + t.Fatalf("queue length after consumers drained = %d, want 0 (stranded tasks)", got) + } + + cancel() + for i := 0; i < consumerCount; i++ { + <-consumersDone + } + }) +} + +// TestContentModerationQueueConsumerOverlapsGrowth proves the missing overlap +// property directly, using the same dequeueAsyncTask call the real worker loop +// makes: +// +// 1. A seed phase consumes 20 tasks, proving the consumer entered its loop and +// made progress before any growth. +// 2. The consumer then blocks INSIDE dequeueAsyncTask on the empty 64-slot +// queue. A producer burst of 500 tasks grows the channel 64->128->256->512 +// while that read is in flight; growAsyncQueueLocked replaces the channel +// and wakes the parked read. Capacity growth, the in-flight read, and the +// consumer's +1 progress are all asserted explicitly. +// 3. A sustained phase keeps both loops progressing in the same window: each +// round writes 50 tasks, releases 50 permits, and waits for only 25 reads, +// so permits stay outstanding while the next round is being written. Reads +// taken while the producer has not finished writing are counted, which +// proves reads and writes interleave instead of running in two disjoint +// phases. +// +// A final drain proves every task is consumed exactly once with no stranded +// queue entries. synctest makes every phase deterministic and instant. +func TestContentModerationQueueConsumerOverlapsGrowth(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + svc := newConcurrentQueueTestService() + cfg := defaultContentModerationConfig() + cfg.QueueSize = 4096 + + const seedTasks = 20 + const growthBurst = 500 + const overlapRounds = 6 + const overlapWritePerHalf = 25 + const overlapPermitsPerHalf = 10 + const overlapMinReadsPerHalf = 5 + const overlapTasks = overlapRounds * 2 * overlapWritePerHalf + const total = seedTasks + growthBurst + overlapTasks + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + permits := make(chan struct{}, total+1) + consumedSignal := make(chan struct{}, total+1) + consumerDone := make(chan struct{}) + producerDone := make(chan struct{}) + var producerActive atomic.Bool + var phaseWritten atomic.Int64 + var consumerInDequeue atomic.Int64 + var consumed atomic.Int64 + var overlapReads atomic.Int64 + var midPhaseReads atomic.Int64 + var mu sync.Mutex + received := make(map[string]int, total) + + go func() { + defer close(consumerDone) + for { + select { + case <-ctx.Done(): + return + case _, ok := <-permits: + if !ok { + return + } + } + consumerInDequeue.Add(1) + task, ok := svc.dequeueAsyncTask(ctx, time.Minute) + consumerInDequeue.Add(-1) + if !ok { + return + } + mu.Lock() + received[task.inputHash]++ + mu.Unlock() + if producerActive.Load() { + overlapReads.Add(1) + if phaseWritten.Load() < overlapTasks { + midPhaseReads.Add(1) + } + } + consumed.Add(1) + consumedSignal <- struct{}{} + } + }() + + // Phase 1: progress before growth. + for i := 0; i < seedTasks; i++ { + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, fmt.Sprintf("seed-%d", i)) + } + for i := 0; i < seedTasks; i++ { + permits <- struct{}{} + } + for i := 0; i < seedTasks; i++ { + <-consumedSignal + } + if got := consumed.Load(); got != seedTasks { + t.Fatalf("consumer progress before growth = %d, want %d", got, seedTasks) + } + if got := len(svc.asyncQueueOf()); got != 0 { + t.Fatalf("queue length after seed drain = %d, want 0", got) + } + capBefore := cap(svc.asyncQueueOf()) + if capBefore != contentModerationInitialQueueCapacity { + t.Fatalf("initial queue capacity = %d, want %d", capBefore, contentModerationInitialQueueCapacity) + } + consumedBeforeGrowth := consumed.Load() + + // Phase 2: one read is in flight while the producer burst grows the queue. + permits <- struct{}{} + synctest.Wait() // consumer is durably blocked inside dequeueAsyncTask + if got := consumerInDequeue.Load(); got != 1 { + t.Fatalf("consumer in-flight dequeue count = %d before growth burst, want 1", got) + } + for i := 0; i < growthBurst; i++ { + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, fmt.Sprintf("grow-%d", i)) + } + synctest.Wait() + capAfterGrowth := cap(svc.asyncQueueOf()) + if capAfterGrowth <= contentModerationInitialQueueCapacity { + t.Fatalf("queue capacity after growth burst = %d, want more than initial %d", capAfterGrowth, contentModerationInitialQueueCapacity) + } + if capAfterGrowth < 512 { + t.Fatalf("queue capacity after %d growth tasks = %d, want at least 512", growthBurst, capAfterGrowth) + } + if got := consumed.Load(); got != consumedBeforeGrowth+1 { + t.Fatalf("consumer progress across queue growth = %d, want %d", got, consumedBeforeGrowth+1) + } + if got := svc.asyncDropped.Load(); got != 0 { + t.Fatalf("asyncDropped during growth = %d, want 0", got) + } + + // Phase 3: sustained interleaving. Every half-round writes 25 tasks and + // then releases 10 permits, waiting for 5 reads before writing the next + // 25. The producer therefore yields mid-round with reads still + // outstanding, so reads land between writes instead of after the whole + // burst. The queue is above 512 in round 0, proving a second observed + // growth while the consumer loops. + producerActive.Store(true) + go func() { + defer close(producerDone) + for round := 0; round < overlapRounds; round++ { + for half := 0; half < 2; half++ { + target := consumed.Load() + overlapMinReadsPerHalf + for i := 0; i < overlapWritePerHalf; i++ { + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, + fmt.Sprintf("overlap-%d-%d-%d", round, half, i)) + phaseWritten.Add(1) + } + for i := 0; i < overlapPermitsPerHalf; i++ { + permits <- struct{}{} + } + for consumed.Load() < target { + <-consumedSignal + } + } + } + producerActive.Store(false) + }() + + <-producerDone + capAfterOverlap := cap(svc.asyncQueueOf()) + if capAfterOverlap < 1024 { + t.Fatalf("queue capacity after overlap phase = %d, want at least 1024", capAfterOverlap) + } + if got := overlapReads.Load(); got < int64(overlapRounds*2*overlapMinReadsPerHalf) { + t.Fatalf("consumer reads while producer phase was active = %d, want at least %d", got, overlapRounds*2*overlapMinReadsPerHalf) + } + if got := midPhaseReads.Load(); got < int64(overlapRounds*2*overlapMinReadsPerHalf) { + t.Fatalf("consumer reads before the producer finished writing = %d, want at least %d", got, overlapRounds*2*overlapMinReadsPerHalf) + } + if got := consumed.Load(); got <= consumedBeforeGrowth { + t.Fatalf("consumer progress across growth = %d, want more than %d", got, consumedBeforeGrowth) + } + if got := svc.asyncDropped.Load(); got != 0 { + t.Fatalf("asyncDropped during overlap = %d, want 0", got) + } + + // Drain the remaining backlog; every task is already queued, so the + // consumer never waits on an empty queue during this pass. + remaining := total - int(consumed.Load()) + for i := 0; i < remaining; i++ { + permits <- struct{}{} + } + for consumed.Load() < total { + <-consumedSignal + } + close(permits) + <-consumerDone + + if got := svc.asyncEnqueued.Load(); got != total { + t.Fatalf("asyncEnqueued = %d, want %d", got, total) + } + if got := svc.asyncDropped.Load(); got != 0 { + t.Fatalf("asyncDropped = %d, want 0 below the configured threshold", got) + } + if got := len(svc.asyncQueueOf()); got != 0 { + t.Fatalf("queue length after all consumers stopped = %d, want 0 (stranded tasks)", got) + } + if got := consumed.Load(); got != total { + t.Fatalf("consumer progress = %d, want %d", got, total) + } + + mu.Lock() + unique := 0 + duplicates := 0 + emptyID := false + for id, count := range received { + if id == "" { + emptyID = true + } + unique++ + if count > 1 { + duplicates += count - 1 + } + } + mu.Unlock() + if emptyID { + t.Fatal("consumer received a task without an input hash") + } + if unique != total { + t.Fatalf("unique task ids consumed = %d, want %d", unique, total) + } + if duplicates != 0 { + t.Fatalf("duplicate deliveries = %d, want 0", duplicates) + } + }) +} + +// TestContentModerationDequeueWakesOnFirstLazyQueue pins the first-enqueue wake: +// a consumer parked while the queue is still nil must be released by the +// enqueue that lazily creates the channel, not by its idle timer. +func TestContentModerationDequeueWakesOnFirstLazyQueue(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + svc := newConcurrentQueueTestService() + if svc.asyncQueueOf() != nil { + t.Fatal("new service must start without an allocated queue") + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + result := make(chan contentModerationTask, 1) + go func() { + task, ok := svc.dequeueAsyncTask(ctx, time.Hour) + if ok { + result <- task + } + close(result) + }() + synctest.Wait() // consumer is durably parked on the nil queue + + cfg := defaultContentModerationConfig() + cfg.QueueSize = 8 + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, "first") + synctest.Wait() + + task, ok := <-result + if !ok { + t.Fatal("consumer did not receive the first task") + } + if task.inputHash != "first" { + t.Fatalf("consumer received %q, want the first task", task.inputHash) + } + }) +} + +// TestContentModerationDequeueWakesWhenQueueReplaced pins the old-waiting-queue +// to new-queue hand-off. growAsyncQueueLocked swaps the channel and calls +// wakeWorkersLocked; a consumer already blocked on the old channel must re-read +// the new channel instead of waiting for its one-second idle timer. The swap is +// performed directly under asyncQueueMu because a real grow can only happen +// while the old queue is full, which would let the consumer receive from the old +// channel instead of exercising the blocked hand-off. +func TestContentModerationDequeueWakesWhenQueueReplaced(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + svc := newConcurrentQueueTestService() + cfg := defaultContentModerationConfig() + cfg.QueueSize = 8 + svc.enqueueAsync(ContentModerationCheckInput{}, cfg, ContentModerationInput{}, "seed") + seed, ok := svc.dequeueAsyncTask(context.Background(), time.Second) + if !ok || seed.inputHash != "seed" { + t.Fatalf("seed dequeue = %q, %v", seed.inputHash, ok) + } + if got := len(svc.asyncQueueOf()); got != 0 { + t.Fatalf("queue length before replacement = %d, want 0", got) + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + result := make(chan contentModerationTask, 1) + go func() { + task, ok := svc.dequeueAsyncTask(ctx, time.Hour) + if ok { + result <- task + } + close(result) + }() + synctest.Wait() // consumer is durably parked on the old empty channel + + svc.asyncQueueMu.Lock() + grown := make(chan contentModerationTask, 128) + grown <- contentModerationTask{inputHash: "replacement"} + svc.asyncQueue = grown + svc.wakeWorkersLocked() + svc.asyncQueueMu.Unlock() + + synctest.Wait() + task, ok := <-result + if !ok { + t.Fatal("consumer did not wake after the queue was replaced") + } + if task.inputHash != "replacement" { + t.Fatalf("consumer received %q, want the replacement task", task.inputHash) + } + }) +} + +// TestContentModerationDequeueHonorsCancellationAndIdleTimeout covers both exit +// paths of dequeueAsyncTask: a cancelled context returns immediately and an +// empty idle queue returns false when the idle timer fires. It must not spin or +// return a zero-value task as if it were real work. +func TestContentModerationDequeueHonorsCancellationAndIdleTimeout(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + svc := newConcurrentQueueTestService() + + cancelled, cancel := context.WithCancel(context.Background()) + cancel() + if _, ok := svc.dequeueAsyncTask(cancelled, time.Second); ok { + t.Fatal("cancelled context must not dequeue a task") + } + + start := time.Now() + if _, ok := svc.dequeueAsyncTask(context.Background(), 10*time.Second); ok { + t.Fatal("idle queue must not dequeue a task") + } + if elapsed := time.Since(start); elapsed != 10*time.Second { + t.Fatalf("idle wait = %s, want 10s", elapsed) + } + }) +}