From c7d44134a3b9ed34c37aedee6c5addae3f12b14a Mon Sep 17 00:00:00 2001 From: sisantaChhatoi Date: Thu, 3 Dec 2026 02:08:00 +0530 Subject: [PATCH] refactor(server): use modern Go idioms Mechanical modernization of the server package's tests with the gopls/go fix modernizers: range over int, strings.SplitSeq, strings.Cut / CutPrefix, slices.Contains / Sort / Backward, maps.Copy, min / max, sync.WaitGroup.Go and t.Context in tests. No behaviour change. Co-Authored-By: Claude Opus 5.5 --- server/bedrock_gateway_test.go | 3 +-- server/change_password_limit_test.go | 16 ++++++++-------- server/chat_mentions_test.go | 2 +- server/core_test.go | 4 ++-- server/cost_ledger_test.go | 4 +--- server/customtool_target_gate_test.go | 4 ++-- server/envseal_linux_test.go | 2 +- server/execpriv_nnp_linux_test.go | 2 +- server/execpriv_root_linux_test.go | 10 +++------- server/execpriv_shim_nnp_linux_test.go | 2 +- server/llmpool_health_test.go | 10 +++------- server/log_hygiene_test.go | 3 +-- server/login_limit_test.go | 4 ++-- server/logsink_test.go | 8 +++----- server/manager_lifecycle_test.go | 18 +++++++----------- server/notify_api_test.go | 6 +++--- server/ready_test.go | 6 ++---- server/report_asset_counts_test.go | 2 +- server/side_questions_test.go | 6 +++--- server/task_llm_rotation_test.go | 24 ++++++++++-------------- server/task_llm_test.go | 14 ++++++-------- server/traffic_rewrite_test.go | 2 +- 22 files changed, 63 insertions(+), 89 deletions(-) diff --git a/server/bedrock_gateway_test.go b/server/bedrock_gateway_test.go index b9b67039..fb2e12a7 100644 --- a/server/bedrock_gateway_test.go +++ b/server/bedrock_gateway_test.go @@ -23,8 +23,7 @@ func TestBedrockGatewaySavedProfileAndConnection(t *testing.T) { if m.pg == nil { db.SkipNoPG(t) } - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir()) s.allowLoopbackModels = true // the fake endpoint listens on loopback (test-only guard seam) const token = "synthetic-gateway-token" diff --git a/server/change_password_limit_test.go b/server/change_password_limit_test.go index e9ce8f7e..68e2596c 100644 --- a/server/change_password_limit_test.go +++ b/server/change_password_limit_test.go @@ -26,7 +26,7 @@ func TestPasswordChangeWaitBlocksByIPAndToken(t *testing.T) { clk := newFakeClock() s := &Server{pwdLimit: newLoginLimiter(clk.now)} const tok = "stolen-session" - for i := 0; i < loginMaxAttempts; i++ { + for i := range loginMaxAttempts { if wait := s.passwordChangeWait(changePasswordRequest("192.0.2.50:40000", tok)); wait != 0 { t.Fatalf("attempt %d blocked after %v", i+1, wait) } @@ -36,7 +36,7 @@ func TestPasswordChangeWaitBlocksByIPAndToken(t *testing.T) { } s = &Server{pwdLimit: newLoginLimiter(clk.now)} - for i := 0; i < loginMaxAttempts; i++ { + for i := range loginMaxAttempts { remote := fmt.Sprintf("198.51.100.%d:40000", i+1) if wait := s.passwordChangeWait(changePasswordRequest(remote, tok)); wait != 0 { t.Fatalf("rotated IP attempt %d blocked after %v", i+1, wait) @@ -47,7 +47,7 @@ func TestPasswordChangeWaitBlocksByIPAndToken(t *testing.T) { } s = &Server{pwdLimit: newLoginLimiter(clk.now)} - for i := 0; i < loginMaxAttempts; i++ { + for i := range loginMaxAttempts { if wait := s.passwordChangeWait(changePasswordRequest("192.0.2.51:40000", tok)); wait != 0 { t.Fatalf("fill attempt %d blocked after %v", i+1, wait) } @@ -107,7 +107,7 @@ func TestChangePasswordRateLimitReturns429WithRetryAfter(t *testing.T) { clk := newFakeClock() _, _, post := changePasswordServer(t, clk) const ip = "192.0.2.40:40000" - for i := 0; i < loginMaxAttempts; i++ { + for i := range loginMaxAttempts { if w := post(ip, "wrong-password-xx", "correct-horse-9"); w.Code != 401 { t.Fatalf("attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String()) } @@ -130,7 +130,7 @@ func TestChangePasswordRateLimitReturns429WithRetryAfter(t *testing.T) { func TestChangePasswordRateLimitFollowsStolenTokenAcrossIPs(t *testing.T) { clk := newFakeClock() _, _, post := changePasswordServer(t, clk) - for i := 0; i < loginMaxAttempts; i++ { + for i := range loginMaxAttempts { remote := fmt.Sprintf("198.51.100.%d:40000", i+1) if w := post(remote, "wrong-password-xx", "correct-horse-9"); w.Code != 401 { t.Fatalf("attempt %d from %s: status=%d want 401; body=%s", i+1, remote, w.Code, w.Body.String()) @@ -145,7 +145,7 @@ func TestChangePasswordSuccessResetsCounter(t *testing.T) { clk := newFakeClock() s, tok, post := changePasswordServer(t, clk) const ip = "192.0.2.41:40000" - for i := 0; i < loginMaxAttempts-1; i++ { + for i := range loginMaxAttempts - 1 { if w := post(ip, "wrong-password-xx", "correct-horse-9"); w.Code != 401 { t.Fatalf("attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String()) } @@ -180,7 +180,7 @@ func TestChangePasswordSuccessResetsCounter(t *testing.T) { s.authChangePassword(rec, r) return rec } - for i := 0; i < loginMaxAttempts; i++ { + for i := range loginMaxAttempts { if w := post2("wrong-password-xx", "correct-horse-9"); w.Code != 401 { t.Fatalf("after reset attempt %d: status=%d want 401; body=%s", i+1, w.Code, w.Body.String()) } @@ -195,7 +195,7 @@ func TestChangePasswordUnauthenticatedDoesNotCount(t *testing.T) { s, _, post := changePasswordServer(t, clk) const ip = "192.0.2.42:40000" body := `{"old_password":"wrong-password-xx","new_password":"correct-horse-9"}` - for i := 0; i < loginMaxAttempts+1; i++ { + for i := range loginMaxAttempts + 1 { r := httptest.NewRequest("POST", "/api/auth/change-password", strings.NewReader(body)) r.RemoteAddr = ip r.Header.Set("Authorization", "Bearer not-a-token") diff --git a/server/chat_mentions_test.go b/server/chat_mentions_test.go index ef94edd3..adb5fb49 100644 --- a/server/chat_mentions_test.go +++ b/server/chat_mentions_test.go @@ -44,7 +44,7 @@ func TestChatMentionPagination(t *testing.T) { s, fid := newRetestServer(t) pg := s.m.pg query := fmt.Sprintf("mention-pages-%d", fid) - for i := 0; i < 43; i++ { + for range 43 { id, err := pg.AddFinding(0, 0, "xss", query, "low", query, "proof", "test", nil) if err != nil { t.Fatal(err) diff --git a/server/core_test.go b/server/core_test.go index a4dfaf3e..1edd123f 100644 --- a/server/core_test.go +++ b/server/core_test.go @@ -53,7 +53,7 @@ func TestCoreTaskLifecyclePG(t *testing.T) { doRetry := func(method, path string, body any) (int, map[string]any) { var code int var out map[string]any - for i := 0; i < 5; i++ { + for range 5 { code, out = do(method, path, body) if code < 500 { break @@ -79,7 +79,7 @@ func TestCoreTaskLifecyclePG(t *testing.T) { // the exploration owns goal node(s) — goal seeding is async, poll briefly var goals []*db.Node - for i := 0; i < 30; i++ { + for range 30 { goals, err = m.pg.Exploration(expID).ListByKind("goal", 10) if err != nil || len(goals) > 0 { break diff --git a/server/cost_ledger_test.go b/server/cost_ledger_test.go index 1a45a63f..df3b7cb1 100644 --- a/server/cost_ledger_test.go +++ b/server/cost_ledger_test.go @@ -2,7 +2,6 @@ package server import ( "bytes" - "context" "encoding/json" "net/http" "net/http/httptest" @@ -80,8 +79,7 @@ func TestProfilePricesThroughAPI(t *testing.T) { if m.pg == nil { db.SkipNoPG(t) } - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() s := New(ctx, m, t.TempDir(), t.TempDir(), t.TempDir()) body, _ := json.Marshal(map[string]any{ diff --git a/server/customtool_target_gate_test.go b/server/customtool_target_gate_test.go index 2f563eb9..52432da8 100644 --- a/server/customtool_target_gate_test.go +++ b/server/customtool_target_gate_test.go @@ -384,8 +384,8 @@ func (p *toolScript) next(t *testing.T) string { // lastToolResult is the text of the last tool result the model is shown. func lastToolResult(msgs []llm.Message) string { - for i := len(msgs) - 1; i >= 0; i-- { - for _, b := range msgs[i].Content { + for _, msg := range slices.Backward(msgs) { + for _, b := range msg.Content { if b.Type != llm.BlockToolResult { continue } diff --git a/server/envseal_linux_test.go b/server/envseal_linux_test.go index e9fae29f..44ad2d8f 100644 --- a/server/envseal_linux_test.go +++ b/server/envseal_linux_test.go @@ -93,7 +93,7 @@ func TestSealedEnvironmentHandoff(t *testing.T) { got := map[string]string{} seen := map[string]bool{} done := false - for _, line := range strings.Split(string(out), "\n") { + for line := range strings.SplitSeq(string(out), "\n") { if !strings.HasPrefix(line, "SEAL ") { continue } diff --git a/server/execpriv_nnp_linux_test.go b/server/execpriv_nnp_linux_test.go index d2a2f90b..e29005b1 100644 --- a/server/execpriv_nnp_linux_test.go +++ b/server/execpriv_nnp_linux_test.go @@ -17,7 +17,7 @@ func noNewPrivsOfThread(t *testing.T) string { if err != nil { t.Fatal(err) } - for _, line := range strings.Split(string(b), "\n") { + for line := range strings.SplitSeq(string(b), "\n") { if v, ok := strings.CutPrefix(line, "NoNewPrivs:"); ok { return strings.TrimSpace(v) } diff --git a/server/execpriv_root_linux_test.go b/server/execpriv_root_linux_test.go index 487627df..47efc59d 100644 --- a/server/execpriv_root_linux_test.go +++ b/server/execpriv_root_linux_test.go @@ -15,6 +15,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "syscall" "testing" @@ -741,7 +742,7 @@ func TestNormaTaskDirPlantedByExecutorAsRoot(t *testing.T) { // envNames returns the variable names of an `env` listing. func envNames(out string) map[string]string { m := map[string]string{} - for _, line := range strings.Split(out, "\n") { + for line := range strings.SplitSeq(out, "\n") { if k, v, ok := strings.Cut(line, "="); ok && k != "" && !strings.ContainsAny(k, " \t") { m[k] = v } @@ -776,12 +777,7 @@ func checkExecutorEnv(t *testing.T, path, out, home string, want ...string) { } func slicesContains(s []string, v string) bool { - for _, x := range s { - if x == v { - return true - } - } - return false + return slices.Contains(s, v) } // Each executor path starts its process with the allowlisted environment: a diff --git a/server/execpriv_shim_nnp_linux_test.go b/server/execpriv_shim_nnp_linux_test.go index 2524aaef..10ca9934 100644 --- a/server/execpriv_shim_nnp_linux_test.go +++ b/server/execpriv_shim_nnp_linux_test.go @@ -30,7 +30,7 @@ func TestExecDropShimInheritsNoNewPrivs(t *testing.T) { if err != nil { t.Fatalf("shim helper failed: %v\n%s", err, out) } - for _, line := range strings.Split(string(out), "\n") { + for line := range strings.SplitSeq(string(out), "\n") { if v, ok := strings.CutPrefix(line, "NoNewPrivs:"); ok { if got := strings.TrimSpace(v); got != "1" { t.Fatalf("exec'd program NoNewPrivs = %q, want 1 (thread migrated after prctl)\n%s", got, out) diff --git a/server/llmpool_health_test.go b/server/llmpool_health_test.go index e54aa523..fab0fcc6 100644 --- a/server/llmpool_health_test.go +++ b/server/llmpool_health_test.go @@ -1,7 +1,6 @@ package server import ( - "context" "errors" "sync" "testing" @@ -12,8 +11,7 @@ import ( ) func TestHealthSyncLoopWritesLatest(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() var mu sync.Mutex saved := map[int64]db.LLMHealth{} @@ -73,8 +71,7 @@ func TestHealthSyncLoopWritesLatest(t *testing.T) { } func TestHealthSyncRetriesFailedSave(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() var mu sync.Mutex calls := 0 @@ -110,8 +107,7 @@ func TestHealthSyncRetriesFailedSave(t *testing.T) { } func TestHealthSyncEnqueueDoesNotWaitOnSave(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() started := make(chan struct{}) release := make(chan struct{}) diff --git a/server/log_hygiene_test.go b/server/log_hygiene_test.go index b6025a3f..135d07dd 100644 --- a/server/log_hygiene_test.go +++ b/server/log_hygiene_test.go @@ -314,8 +314,7 @@ func TestLogsHistoryMasksCredentialsInOldRows(t *testing.T) { } sink := &logSinkT{cap: 3000, subs: map[chan LogLine]struct{}{}, out: &lockedBuffer{}} - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() sink.SetDB(ctx, m.pg) if got := sinkText(sink); strings.Contains(got, password) || !strings.Contains(got, "http://olduser:xxxxx@old.test:3128") { t.Errorf("restored ring: want the old row with its password masked; password present=%v", strings.Contains(got, password)) diff --git a/server/login_limit_test.go b/server/login_limit_test.go index 790a3588..3ccc0f9b 100644 --- a/server/login_limit_test.go +++ b/server/login_limit_test.go @@ -53,7 +53,7 @@ func loginServer(t *testing.T, clk *fakeClock) (*Server, func(remote, password s func failN(t *testing.T, post func(string, string, map[string]string) *httptest.ResponseRecorder, remote string, n int) { t.Helper() - for i := 0; i < n; i++ { + for i := range n { if w := post(remote, "wrong-password", nil); w.Code != 401 { t.Fatalf("attempt %d from %s: status=%d want 401; body=%s", i+1, remote, w.Code, w.Body.String()) } @@ -213,7 +213,7 @@ func TestLoginRateLimitBehindTrustedProxy(t *testing.T) { const proxy = "127.0.0.1:50000" via := func(xff string) map[string]string { return map[string]string{"X-Forwarded-For": xff} } - for i := 0; i < loginMaxAttempts; i++ { + for i := range loginMaxAttempts { if w := post(proxy, "wrong-password", via("198.51.100.20")); w.Code != 401 { t.Fatalf("attempt %d: status=%d want 401", i+1, w.Code) } diff --git a/server/logsink_test.go b/server/logsink_test.go index 182098b0..e3f76706 100644 --- a/server/logsink_test.go +++ b/server/logsink_test.go @@ -9,13 +9,11 @@ import ( func TestLogSinkUnsubscribeDuringAddDoesNotPanic(t *testing.T) { s := &logSinkT{cap: 8, subs: map[chan LogLine]struct{}{}, out: io.Discard} var wg sync.WaitGroup - for i := 0; i < 32; i++ { + for range 32 { _, unsub := s.subscribe() - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { unsub() - }() + }) s.add(LogLine{Text: "line"}) } wg.Wait() diff --git a/server/manager_lifecycle_test.go b/server/manager_lifecycle_test.go index 11be769b..b11d53f5 100644 --- a/server/manager_lifecycle_test.go +++ b/server/manager_lifecycle_test.go @@ -62,24 +62,20 @@ func TestTaskLifecycleSnapshotConcurrentConsistency(t *testing.T) { writeState(1, true) var wg sync.WaitGroup - for writer := 0; writer < 4; writer++ { + for writer := range 4 { writer := writer - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { for i := 1; i <= 1000; i++ { generation := int64(writer*1000 + i) writeState(generation, generation%2 == 0) } - }() + }) } errCh := make(chan error, 4) - for reader := 0; reader < 4; reader++ { - wg.Add(1) - go func() { - defer wg.Done() - for i := 0; i < 1000; i++ { + for range 4 { + wg.Go(func() { + for range 1000 { state := task.lifecycleSnapshot() if state.Queued == state.Paused { errCh <- fmt.Errorf("queued=%v paused=%v", state.Queued, state.Paused) @@ -99,7 +95,7 @@ func TestTaskLifecycleSnapshotConcurrentConsistency(t *testing.T) { return } } - }() + }) } wg.Wait() close(errCh) diff --git a/server/notify_api_test.go b/server/notify_api_test.go index f98d17a6..d785ba0b 100644 --- a/server/notify_api_test.go +++ b/server/notify_api_test.go @@ -429,7 +429,7 @@ func TestNotifyDigestBatchesMultipleFindingsIntoOneMessage(t *testing.T) { "mode": db.NotifyModeDigest, "config": map[string]any{"webhook": hook.URL}, }) - for i := 0; i < 3; i++ { + for i := range 3 { f.record(t, fmt.Sprintf("digest vuln %d", i+1), "high") } ctx := context.Background() @@ -594,7 +594,7 @@ func TestNotifyDeliveriesHistoryAndRetry(t *testing.T) { } ch := f.channel(t, chID) // Keep delivering until the retry budget is exhausted. - for i := 0; i < db.MaxNotifyAttempts; i++ { + for range db.MaxNotifyAttempts { f.n.stepRealtime(ctx, ch, 50, "") if _, err := f.pg.Exec(`UPDATE notification_deliveries SET next_attempt_at = now() - interval '1 minute' WHERE channel_id=$1`, chID); err != nil { t.Fatal(err) @@ -881,7 +881,7 @@ func TestNotifyDigestSegmentsAndDefersRemainder(t *testing.T) { // Make the titles long, so 60 entries far exceed 4096 bytes and segmentation // is guaranteed. longName := strings.Repeat("very long vulnerability name", 6) - for i := 0; i < total; i++ { + for i := range total { f.record(t, longName+strconv.Itoa(i+1), "high") } ctx := context.Background() diff --git a/server/ready_test.go b/server/ready_test.go index 9e6b1355..1ec733d5 100644 --- a/server/ready_test.go +++ b/server/ready_test.go @@ -208,11 +208,9 @@ func TestReadyConcurrentRequestsShareOnePing(t *testing.T) { const callers = 20 results := make([]bool, callers) var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { results[0] = cache.check(context.Background(), ping) - }() + }) <-started for i := 1; i < callers; i++ { diff --git a/server/report_asset_counts_test.go b/server/report_asset_counts_test.go index 56dfb5b5..2dbeba03 100644 --- a/server/report_asset_counts_test.go +++ b/server/report_asset_counts_test.go @@ -65,7 +65,7 @@ func TestReportCountsOnlyTheTaskAssets(t *testing.T) { t.Fatalf("report status=%d body=%s", rec.Code, rec.Body.String()) } var line string - for _, l := range strings.Split(rec.Body.String(), "\n") { + for l := range strings.SplitSeq(rec.Body.String(), "\n") { if strings.HasPrefix(l, "- Assets: ") { line = l } diff --git a/server/side_questions_test.go b/server/side_questions_test.go index a277b58e..e526c9bf 100644 --- a/server/side_questions_test.go +++ b/server/side_questions_test.go @@ -63,7 +63,7 @@ func TestSideHTTPPreparationCancellationAndClear(t *testing.T) { f := newSideHTTPFixture(t) p, path := f.conversation(t) snap := f.checkpoint(t, p) - for i := 0; i < 21; i++ { + for i := range 21 { e, _, err := f.m.pg.StartSideRequest(t.Context(), snap, fmt.Sprint(i), "past question") if err != nil { t.Fatal(err) @@ -250,7 +250,7 @@ func TestSideHTTPBusyIsolationClearAndReconnect(t *testing.T) { // SSE reconnect always starts with a cumulative snapshot even with Last-Event-ID. httpServer := httptest.NewServer(f.handler) defer httpServer.Close() - for i := 0; i < 2; i++ { + for range 2 { req, _ := http.NewRequest("GET", httpServer.URL+"/api/side-questions/"+e.ID+"/events", nil) req.Header.Set("Authorization", "Bearer "+f.token) req.Header.Set("Last-Event-ID", "999") @@ -306,7 +306,7 @@ func TestSideHTTPBusyIsolationClearAndReconnect(t *testing.T) { func TestSideHTTPGlobalLimitTaskWorkerAndDeletion(t *testing.T) { f := newSideHTTPFixture(t) var requests []sidequestion.Exchange - for i := 0; i < 20; i++ { + for i := range 20 { p, path := f.conversation(t) f.checkpoint(t, p) want := 202 diff --git a/server/task_llm_rotation_test.go b/server/task_llm_rotation_test.go index 20d77ccb..6d4051e5 100644 --- a/server/task_llm_rotation_test.go +++ b/server/task_llm_rotation_test.go @@ -40,7 +40,7 @@ func TestRotationConcurrentProvidersAndPrecedence(t *testing.T) { started := make(chan int, 3) release := []chan struct{}{make(chan struct{}), make(chan struct{})} ids := []int64{} - for i := 0; i < 2; i++ { + for i := range 2 { i := i endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { started <- i @@ -111,7 +111,7 @@ func TestRotationConcurrentProvidersAndPrecedence(t *testing.T) { } dispatch(0) close(release[0]) - for i := 0; i < 2; i++ { + for range 2 { select { case err := <-done: if err != nil { @@ -163,17 +163,15 @@ func TestRotationConcurrentDispatchAndUpdates(t *testing.T) { const workers = 100 counts := make(chan int64, workers) var wg sync.WaitGroup - for i := 0; i < workers; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range workers { + wg.Go(func() { id, ok := task.nextRotatedProfile() if !ok { t.Error("missing assignment") return } counts <- id - }() + }) } wg.Wait() close(counts) @@ -185,14 +183,12 @@ func TestRotationConcurrentDispatchAndUpdates(t *testing.T) { t.Fatalf("unbalanced assignments: %v", got) } // Replace the chain while dispatching, exercising the shared list lock. - wg.Add(1) - go func() { - defer wg.Done() - for i := 0; i < workers; i++ { + wg.Go(func() { + for i := range workers { task.setLLMState(nil, nil, []int64{3, 4}, int64(i+1), "ready", "", i%2 == 0) } - }() - for i := 0; i < workers; i++ { + }) + for range workers { task.nextRotatedProfile() task.llmStateSnapshot() } @@ -323,7 +319,7 @@ func TestRunIntentRotatesPinnedProfileWithCachedExecCtx(t *testing.T) { defer m.Close() ids := make([]int64, 0, 2) - for i := 0; i < 2; i++ { + for i := range 2 { id, err := m.pg.SaveProfile(&db.LLMProfile{ Name: fmt.Sprintf("runintent-rotate-%d-%d", time.Now().UnixNano(), i), Format: "openai", diff --git a/server/task_llm_test.go b/server/task_llm_test.go index 15c1c330..b4ef7554 100644 --- a/server/task_llm_test.go +++ b/server/task_llm_test.go @@ -202,28 +202,26 @@ func TestTaskLLMStateSnapshotIsConcurrentAndDetached(t *testing.T) { t.Parallel() task := &Task{ID: "7"} var wg sync.WaitGroup - for writer := 0; writer < 2; writer++ { + for writer := range 2 { wg.Add(1) go func(offset int) { defer wg.Done() - for i := 0; i < 500; i++ { + for i := range 500 { id := int64(offset*1000 + i + 1) task.setLLMState(&id, &id, []int64{id, id + 1}, int64(i), "ready", "") } }(writer) } - for reader := 0; reader < 4; reader++ { - wg.Add(1) - go func() { - defer wg.Done() - for i := 0; i < 500; i++ { + for range 4 { + wg.Go(func() { + for range 500 { state := task.llmStateSnapshot() if len(state.ProfileIDs) > 0 { state.ProfileIDs[0] = -1 } _ = taskDTO(task, "running") } - }() + }) } wg.Wait() state := task.llmStateSnapshot() diff --git a/server/traffic_rewrite_test.go b/server/traffic_rewrite_test.go index 6ce435d8..390adec9 100644 --- a/server/traffic_rewrite_test.go +++ b/server/traffic_rewrite_test.go @@ -421,7 +421,7 @@ func TestRewriteRulesLimits(t *testing.T) { return fmt.Sprintf(`{"name":"t-rwapi-limit-%03d","phase":"response","actions":[{"type":"set_header","name":"X-A","value":"v"}]}`, i) } var ids []int64 - for i := 0; i < db.MaxTrafficRewriteRules; i++ { + for i := range db.MaxTrafficRewriteRules { ids = append(ids, decodeRewriteRuleJSON(t, request(true, "POST", rewriteAPI, body(i))).ID) } if resp := request(true, "POST", rewriteAPI, body(100)); resp.Code != 400 || !strings.Contains(resp.Body.String(), "100") {