diff --git a/backend/internal/service/content_moderation.go b/backend/internal/service/content_moderation.go index d045a55cd7..54ef147cb4 100644 --- a/backend/internal/service/content_moderation.go +++ b/backend/internal/service/content_moderation.go @@ -547,6 +547,11 @@ type ContentModerationService struct { runtimeRefreshRetryAt atomic.Int64 keyHealthMu sync.Mutex keyHealth map[string]*contentModerationKeyHealth + // stopCh is closed by Stop; workers tracks the goroutines started by + // NewContentModerationService so Stop can wait for them to exit. + stopCh chan struct{} + stopOnce sync.Once + workers sync.WaitGroup } type contentModerationRuntimeSnapshot struct { @@ -611,16 +616,68 @@ func NewContentModerationService( asyncQueueLazy: true, asyncWake: make(chan struct{}), keyHealth: make(map[string]*contentModerationKeyHealth), + stopCh: make(chan struct{}), } if settingRepo != nil && repo != nil { + svc.workers.Add(svc.workerCount + 1) for i := 0; i < svc.workerCount; i++ { - go svc.worker(i) + go func(id int) { + defer svc.workers.Done() + svc.worker(id) + }(i) } - go svc.cleanupWorker() + go func() { + defer svc.workers.Done() + svc.cleanupWorker() + }() } return svc } +// Stop stops the background goroutines started by NewContentModerationService +// and waits for them to exit, then waits for an in-flight runtime snapshot +// refresh. A worker finishes the task it is processing before it exits. +// Refreshes that callers trigger after Stop still run; calling Stop again +// waits for them. Stop is safe to call more than once and on a service that +// started no goroutines. +func (s *ContentModerationService) Stop() { + if s == nil { + return + } + if s.stopCh != nil { + s.stopOnce.Do(func() { close(s.stopCh) }) + s.workers.Wait() + } + s.waitRuntimeRefresh() +} + +// waitRuntimeRefresh waits for an in-flight runtime snapshot refresh, which +// holds runtimeRefreshMu until it finishes. +func (s *ContentModerationService) waitRuntimeRefresh() { + s.runtimeRefreshMu.Lock() + defer s.runtimeRefreshMu.Unlock() +} + +// stopped reports whether Stop has been called. +func (s *ContentModerationService) stopped() bool { + select { + case <-s.stopCh: + return true + default: + return false + } +} + +// sleepUnlessStopped waits for d, returning early when Stop is called. +func (s *ContentModerationService) sleepUnlessStopped(d time.Duration) { + timer := time.NewTimer(d) + defer timer.Stop() + select { + case <-s.stopCh: + case <-timer.C: + } +} + func (s *ContentModerationService) GetConfig(ctx context.Context) (*ContentModerationConfigView, error) { cfg, err := s.loadConfig(ctx) if err != nil { @@ -1361,12 +1418,12 @@ func (s *ContentModerationService) enqueueRecord(input ContentModerationCheckInp } func (s *ContentModerationService) worker(id int) { - for { + for !s.stopped() { ctx, cancel := context.WithTimeout(context.Background(), maxContentModerationTimeoutMS*time.Millisecond+10*time.Second) runtimeSnapshot, err := s.loadRuntimeSnapshot(ctx) if err != nil || runtimeSnapshot == nil || runtimeSnapshot.config == nil || id >= runtimeSnapshot.config.WorkerCount { cancel() - time.Sleep(time.Second) + s.sleepUnlessStopped(time.Second) continue } cfg := runtimeSnapshot.config @@ -1438,6 +1495,9 @@ func (s *ContentModerationService) dequeueAsyncTask(ctx context.Context, idleWai case <-ctx.Done(): timer.Stop() return zero, false + case <-s.stopCh: + timer.Stop() + return zero, false case <-timer.C: return zero, false } @@ -1454,6 +1514,9 @@ func (s *ContentModerationService) dequeueAsyncTask(ctx context.Context, idleWai case <-ctx.Done(): timer.Stop() return zero, false + case <-s.stopCh: + timer.Stop() + return zero, false case <-timer.C: return zero, false } @@ -1619,7 +1682,11 @@ func (s *ContentModerationService) cleanupWorker() { timer := time.NewTimer(contentModerationCleanupDelay) defer timer.Stop() for { - <-timer.C + select { + case <-s.stopCh: + return + case <-timer.C: + } s.runCleanupOnce() timer.Reset(contentModerationCleanupInterval) } diff --git a/backend/internal/service/content_moderation_cyber_test.go b/backend/internal/service/content_moderation_cyber_test.go index 84ec5302d8..6df7f31db8 100644 --- a/backend/internal/service/content_moderation_cyber_test.go +++ b/backend/internal/service/content_moderation_cyber_test.go @@ -79,6 +79,7 @@ func TestRecordCyberPolicyEvent_DisabledWhenRiskControlOff(t *testing.T) { nil, nil, ) + t.Cleanup(svc.Stop) svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{ UserID: 1, @@ -107,6 +108,7 @@ func TestRecordCyberPolicyEvent_WritesLogWhenEnabled(t *testing.T) { nil, nil, // emailService=nil: email path safely skipped ) + t.Cleanup(svc.Stop) svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{ UserID: 1, @@ -211,6 +213,7 @@ func TestRecordCyberPolicyEvent_RespectsContentModerationScope(t *testing.T) { }}, repo, nil, nil, userRepo, nil, nil, nil, ) + t.Cleanup(svc.Stop) svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{ UserID: 1, @@ -241,6 +244,7 @@ func TestRecordCyberPolicyEvent_InitialRuntimeSnapshotLoadFailureSkipsEvent(t *t SettingKeyContentModerationConfig: `{invalid`, }} svc := NewContentModerationService(settingRepo, repo, nil, nil, nil, nil, nil, nil) + t.Cleanup(svc.Stop) svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{ UserID: 1, @@ -261,6 +265,10 @@ func TestRecordCyberPolicyEvent_RuntimeSnapshotRefreshFailureKeepsStaleScope(t * SettingKeyContentModerationConfig: `{"all_groups":true,"model_filter":{"type":"include","models":["gpt-5"]}}`, }} svc := NewContentModerationService(settingRepo, repo, nil, nil, nil, nil, nil, nil) + t.Cleanup(svc.Stop) + // This test drives the snapshot itself; stop the workers before changing + // the TTL they read. + svc.Stop() svc.runtimeCacheTTL = time.Minute _, err := svc.loadRuntimeSnapshot(context.Background()) @@ -315,6 +323,7 @@ func TestRecordCyberPolicyEvent_CreateLogBeforeEmail(t *testing.T) { nil, nil, // emailService=nil: email path safely skipped; see doc comment above ) + t.Cleanup(svc.Stop) svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{ RequestID: "req-1", @@ -369,6 +378,7 @@ func TestApplyFlaggedAccountSideEffects_PassesExcludeCyberFlag(t *testing.T) { &contentModerationTestSettingRepo{values: map[string]string{}}, repo, nil, nil, nil, nil, nil, nil, ) + t.Cleanup(svc.Stop) userID := int64(42) cfgExclude := defaultContentModerationConfig() @@ -391,6 +401,7 @@ func TestRecordCyberPolicyEvent_ExcludeFromBanCount_SkipsBanJudgment(t *testing. }}, repo, nil, nil, nil, nil, nil, nil, ) + t.Cleanup(svc.Stop) svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{ UserID: 1, @@ -418,6 +429,7 @@ func TestRecordCyberPolicyEvent_DefaultCountsTowardBan(t *testing.T) { }}, repo, nil, nil, nil, nil, nil, nil, ) + t.Cleanup(svc.Stop) svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{ UserID: 1, diff --git a/backend/internal/service/content_moderation_image_safety_test.go b/backend/internal/service/content_moderation_image_safety_test.go index 9835022c74..ff99ad26fc 100644 --- a/backend/internal/service/content_moderation_image_safety_test.go +++ b/backend/internal/service/content_moderation_image_safety_test.go @@ -123,6 +123,7 @@ func newImageSafetyTestService(t *testing.T, settings map[string]string) (*Conte nil, nil, ) + t.Cleanup(svc.Stop) return svc, repo } diff --git a/backend/internal/service/content_moderation_queue_contract_test.go b/backend/internal/service/content_moderation_queue_contract_test.go index cbd36e4234..9aa00026bc 100644 --- a/backend/internal/service/content_moderation_queue_contract_test.go +++ b/backend/internal/service/content_moderation_queue_contract_test.go @@ -2,6 +2,7 @@ package service import ( "context" + "encoding/json" "fmt" "os" "os/exec" @@ -211,3 +212,140 @@ func TestContentModerationWorkerConsumesConcurrentQueue(t *testing.T) { seen[log.RequestID] = struct{}{} } } + +// TestContentModerationStopEndsBackgroundGoroutines:Stop 要等构造函数启动的 worker 与清理协程全部退出才返回—— +// 正在处理任务的 worker 处理完再退出,正在空等任务的、以及编号超出配置 WorkerCount 正在退避的 worker 都要被唤醒; +// 重复调用、没有启动协程的服务与零值服务上调用都安全。没有 Stop 时这些协程永不退出,测试里会一直读 time.Now, +// 与改 time.Local 的测试形成数据竞争。 +func TestContentModerationStopEndsBackgroundGoroutines(t *testing.T) { + cfg := defaultContentModerationConfig() + cfg.Enabled = true + cfg.Mode = ContentModerationModePreBlock + cfg.WorkerCount = 2 + rawCfg, err := json.Marshal(cfg) + if err != nil { + t.Fatal(err) + } + repo := &contentModerationBlockingLogRepo{ + contentModerationTestRepo: &contentModerationTestRepo{}, + entered: make(chan struct{}), + release: make(chan struct{}), + } + releaseTask := sync.OnceFunc(func() { close(repo.release) }) + t.Cleanup(releaseTask) // 失败提前退出时也放行,不留下卡在 CreateLog 里的 worker + // 不经 newContentModerationModelFilterTestService:它注册的 t.Cleanup(svc.Stop) 在协程不退出时会把测试挂到超时, + // 这里要在超时内直接报失败。 + svc := NewContentModerationService( + &contentModerationTestSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: string(rawCfg), + }}, + repo, + &contentModerationTestHashCache{}, + nil, nil, nil, nil, nil, + ) + svc.enqueueRecord(ContentModerationCheckInput{}, cfg, &ContentModerationLog{ + RequestID: "stop-in-flight", + Mode: ContentModerationModePreBlock, + Action: ContentModerationActionAllow, + }, "", false, false) + select { + case <-repo.entered: + case <-time.After(5 * time.Second): + t.Fatal("no worker picked up the queued task") + } + + done := stopInBackground(svc, 2) + select { + case <-done: + t.Fatal("Stop returned while a worker was still processing a task") + case <-time.After(200 * time.Millisecond): + } + releaseTask() + requireStopReturns(t, done, "service with workers") + if got := svc.asyncProcessed.Load(); got != 1 { + t.Fatalf("asyncProcessed = %d, want the in-flight task finished before Stop returned", got) + } + if got := len(repo.snapshotLogs()); got != 1 { + t.Fatalf("persisted logs = %d, want 1", got) + } + + requireStopReturns(t, stopInBackground(NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil), 1), "service without workers") + requireStopReturns(t, stopInBackground(&ContentModerationService{}, 1), "zero-value service") +} + +// TestContentModerationStopWaitsForRuntimeSnapshotRefresh:快照过期后在后台刷新的协程也要等它结束,Stop 才返回。 +func TestContentModerationStopWaitsForRuntimeSnapshotRefresh(t *testing.T) { + settings := &contentModerationRuntimeSettingRepo{values: map[string]string{ + SettingKeyRiskControlEnabled: "true", + SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"), + }} + svc := runtimeCacheTestService(settings, time.Nanosecond) + input := runtimeCacheTestInput("blocked") + if _, err := svc.Check(context.Background(), input); err != nil { + t.Fatal(err) + } + + started := make(chan struct{}, 1) + release := make(chan struct{}) + releaseRefresh := sync.OnceFunc(func() { close(release) }) + t.Cleanup(releaseRefresh) // 失败提前退出时也放行,不留下卡住的刷新 + settings.blockNextMultiple(started, release) + // Windows 单调时钟步进约 0.5ms,反复调用直到快照过期、触发后台刷新。 + deadline := time.Now().Add(5 * time.Second) + for refreshing := false; !refreshing; { + if time.Now().After(deadline) { + t.Fatal("the snapshot refresh did not start") + } + _, _ = svc.Check(context.Background(), input) + select { + case <-started: + refreshing = true + case <-time.After(time.Millisecond): + } + } + + done := stopInBackground(svc, 1) + select { + case <-done: + t.Fatal("Stop returned while a runtime snapshot refresh was still running") + case <-time.After(200 * time.Millisecond): + } + releaseRefresh() + requireStopReturns(t, done, "service with an in-flight refresh") +} + +// stopInBackground 在后台调用 times 次 Stop,全部返回后关闭返回的通道。 +func stopInBackground(svc *ContentModerationService, times int) <-chan struct{} { + done := make(chan struct{}) + go func() { + for range times { + svc.Stop() + } + close(done) + }() + return done +} + +func requireStopReturns(t *testing.T, done <-chan struct{}, what string) { + t.Helper() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatalf("Stop did not return within 5s on a %s", what) + } +} + +// contentModerationBlockingLogRepo 让第一次 CreateLog 停住,直到测试放行。 +type contentModerationBlockingLogRepo struct { + *contentModerationTestRepo + entered chan struct{} + release chan struct{} + once sync.Once +} + +func (r *contentModerationBlockingLogRepo) CreateLog(ctx context.Context, log *ContentModerationLog) error { + r.once.Do(func() { close(r.entered) }) + <-r.release + return r.contentModerationTestRepo.CreateLog(ctx, log) +} diff --git a/backend/internal/service/content_moderation_queue_lazy_test.go b/backend/internal/service/content_moderation_queue_lazy_test.go index c0598ce280..1b8a2d8e95 100644 --- a/backend/internal/service/content_moderation_queue_lazy_test.go +++ b/backend/internal/service/content_moderation_queue_lazy_test.go @@ -47,8 +47,7 @@ func TestContentModerationQueueStartsSmallAndGrowsToQueueSize(t *testing.T) { // 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 +// worker loop makes; TestContentModerationWorkerConsumesConcurrentQueue covers // the real worker loop separately. func newConcurrentQueueTestService() *ContentModerationService { return NewContentModerationService(nil, nil, nil, nil, nil, nil, nil, nil) diff --git a/backend/internal/service/content_moderation_reminder_test.go b/backend/internal/service/content_moderation_reminder_test.go index eb2c320493..d9f16a7f40 100644 --- a/backend/internal/service/content_moderation_reminder_test.go +++ b/backend/internal/service/content_moderation_reminder_test.go @@ -87,6 +87,7 @@ func TestContentModerationCheck_ReminderKeywordModes(t *testing.T) { cache.hashes = map[string]struct{}{semantic.Hash(): {}} } svc := NewContentModerationService(&contentModerationTestSettingRepo{values: map[string]string{SettingKeyRiskControlEnabled: "true", SettingKeyContentModerationConfig: string(raw)}}, repo, cache, nil, nil, nil, nil, nil) + t.Cleanup(svc.Stop) decision, err := svc.Check(context.Background(), ContentModerationCheckInput{Protocol: protocol, Body: body}) require.NoError(t, err) if mode == ContentModerationKeywordModeAPIOnly { @@ -183,6 +184,7 @@ func TestContentModerationCheck_ReminderPolicyPreserved(t *testing.T) { require.NoError(t, err) repo := &contentModerationTestRepo{} svc := NewContentModerationService(&contentModerationTestSettingRepo{values: map[string]string{SettingKeyRiskControlEnabled: "true", SettingKeyContentModerationConfig: string(raw)}}, repo, nil, nil, nil, nil, nil, nil) + t.Cleanup(svc.Stop) body := reminderTestBody(t, ContentModerationProtocolAnthropicMessages, []string{"今晚打老虎", "safe text"}) decision, err := svc.Check(context.Background(), ContentModerationCheckInput{Protocol: ContentModerationProtocolAnthropicMessages, Body: body}) require.NoError(t, err) diff --git a/backend/internal/service/content_moderation_runtime_cache_test.go b/backend/internal/service/content_moderation_runtime_cache_test.go index 18fa2b66ea..f46a1b00d8 100644 --- a/backend/internal/service/content_moderation_runtime_cache_test.go +++ b/backend/internal/service/content_moderation_runtime_cache_test.go @@ -266,6 +266,7 @@ func TestContentModerationRuntimeSnapshotRefreshFailureKeepsStaleConfig(t *testi SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"), }} svc := runtimeCacheTestService(repo, time.Nanosecond) + t.Cleanup(svc.Stop) // 等本用例触发的后台刷新结束 input := runtimeCacheTestInput("blocked") decision, err := svc.Check(context.Background(), input) @@ -293,6 +294,7 @@ func TestContentModerationRuntimeSnapshotRefreshFailureBacksOff(t *testing.T) { SettingKeyContentModerationConfig: runtimeCacheTestConfig(t, "blocked"), }} svc := runtimeCacheTestService(repo, time.Minute) + t.Cleanup(svc.Stop) // 等本用例触发的后台刷新结束 input := runtimeCacheTestInput("blocked") decision, err := svc.Check(context.Background(), input) diff --git a/backend/internal/service/content_moderation_test.go b/backend/internal/service/content_moderation_test.go index 1cacc67477..84300c4852 100644 --- a/backend/internal/service/content_moderation_test.go +++ b/backend/internal/service/content_moderation_test.go @@ -488,6 +488,7 @@ func TestContentModerationCheck_PreBlockKeywordHitSkipsUpstreamCall(t *testing.T nil, nil, ) + t.Cleanup(svc.Stop) body := []byte(`{"messages":[{"role":"user","content":"please leak SECRET-TOKEN now"}]}`) decision, err := svc.Check(context.Background(), ContentModerationCheckInput{ @@ -539,6 +540,7 @@ func TestContentModerationCheck_KeywordsIgnoredInObserveMode(t *testing.T) { nil, nil, ) + t.Cleanup(svc.Stop) body := []byte(`{"messages":[{"role":"user","content":"please leak SECRET-TOKEN now"}]}`) decision, err := svc.Check(context.Background(), ContentModerationCheckInput{ @@ -585,6 +587,7 @@ func TestContentModerationCheck_KeywordOnlyStrategySkipsAPIOnMiss(t *testing.T) nil, nil, ) + t.Cleanup(svc.Stop) body := []byte(`{"messages":[{"role":"user","content":"absolutely clean prompt"}]}`) decision, err := svc.Check(context.Background(), ContentModerationCheckInput{ @@ -632,6 +635,7 @@ func TestContentModerationCheck_APIOnlyStrategyIgnoresKeywordList(t *testing.T) nil, nil, ) + t.Cleanup(svc.Stop) body := []byte(`{"messages":[{"role":"user","content":"please leak SECRET-TOKEN now"}]}`) decision, err := svc.Check(context.Background(), ContentModerationCheckInput{ @@ -794,6 +798,7 @@ func newContentModerationModelFilterTestService(t *testing.T, cfg *ContentModera nil, nil, ) + t.Cleanup(svc.Stop) return svc, repo } @@ -1046,6 +1051,7 @@ func TestContentModerationCheck_OpenAIResponsesRecordsNonHitForCodexPayload(t *t nil, nil, ) + t.Cleanup(svc.Stop) body := []byte(`{ "model":"gpt-5.5", @@ -1111,6 +1117,7 @@ func TestContentModerationCheck_PreBlockBlocksCodexResponsesLatestUserInput(t *t nil, nil, ) + t.Cleanup(svc.Stop) body := []byte(`{ "model":"gpt-5.5", @@ -1181,6 +1188,7 @@ func TestContentModerationStatusTracksPreBlockSyncMetrics(t *testing.T) { nil, nil, ) + t.Cleanup(svc.Stop) for _, prompt := range []string{"blocked prompt", "clean prompt"} { _, err := svc.Check(context.Background(), ContentModerationCheckInput{ @@ -1232,6 +1240,7 @@ func TestContentModerationStatusTracksPreBlockAPIKeyLoad(t *testing.T) { nil, nil, ) + t.Cleanup(svc.Stop) for idx := 0; idx < 4; idx++ { _, err := svc.Check(context.Background(), ContentModerationCheckInput{ @@ -1278,6 +1287,7 @@ func TestContentModerationStatusTracksPreBlockLocalBlocks(t *testing.T) { nil, nil, ) + t.Cleanup(svc.Stop) for _, prompt := range []string{"blocked prompt", "clean prompt"} { _, err := svc.Check(context.Background(), ContentModerationCheckInput{ @@ -1444,6 +1454,7 @@ func TestContentModerationCheck_PreHashUsesRedisHashCache(t *testing.T) { nil, nil, ) + t.Cleanup(svc.Stop) decision, err := svc.Check(context.Background(), ContentModerationCheckInput{ UserID: 1001, @@ -1512,6 +1523,7 @@ func TestContentModerationCheck_HashBlockLogsDoNotIncreaseNextViolationCount(t * nil, nil, ) + t.Cleanup(svc.Stop) decision, err := svc.Check(context.Background(), ContentModerationCheckInput{ UserID: userID, @@ -1653,6 +1665,7 @@ func TestContentModerationCheck_PreBlockFlaggedWritesRedisHashCache(t *testing.T nil, nil, ) + t.Cleanup(svc.Stop) body := []byte(`{"messages":[{"role":"user","content":"repeat blocked prompt"}]}`) decision, err := svc.Check(context.Background(), ContentModerationCheckInput{ @@ -1767,6 +1780,7 @@ func TestContentModerationCheck_AsyncFlaggedWritesRedisHashCache(t *testing.T) { nil, nil, ) + t.Cleanup(svc.Stop) decision := svc.checkSync(context.Background(), ContentModerationCheckInput{ Protocol: ContentModerationProtocolOpenAIChat, diff --git a/backend/internal/service/cyber_policy_allowlist_test.go b/backend/internal/service/cyber_policy_allowlist_test.go index 32c9451825..59e19a58eb 100644 --- a/backend/internal/service/cyber_policy_allowlist_test.go +++ b/backend/internal/service/cyber_policy_allowlist_test.go @@ -44,6 +44,7 @@ func TestRecordCyberPolicyEventLogOnlyPreservesEvidenceWithoutSideEffects(t *tes &contentModerationTestSettingRepo{values: map[string]string{SettingKeyRiskControlEnabled: "true"}}, repo, nil, nil, nil, nil, nil, &EmailService{}, ) + t.Cleanup(svc.Stop) // An unconfigured email service must never be invoked in log-only mode. svc.RecordCyberPolicyEvent(context.Background(), CyberPolicyRecordInput{ LogOnly: true, UserID: 12, UserEmail: "test@example.com", Model: "gpt-5",