Strider report

Strider corpus: loki

1111 msformat4908 mscheck 48782total 6695errors 17324warnings 24763notes

Showing 1000 of 48782 detailed findings. The summary includes all 48782 findings.

clients/cmd/docker-driver/config_test.go1

46:26add-constantstring literal "foo" appears more than twice; define a constant

clients/cmd/docker-driver/config_test.go:46:26

45 model.LabelSet{"swarm_stack": "foo", "bar": "buzz"},
46 model.LabelSet{"job": "foo", "bar": "buzz"},
47 false,

pkg/limits/store_test.go1

177:19append-to-sized-sliceexpected already has a positive length; use make with length zero and capacity, or reslice to zero before append

pkg/limits/store_test.go:177:19

176 // truncate the expected time to the start of the bucket.
177 expected = append(expected, rateBucket{})
178 expected[1].timestamp = time3.Truncate(time.Minute).UnixNano()

operator/tools/tools.go1

7:2blank-importsblank import should be justified by a comment

operator/tools/tools.go:7:2

6import (
7 _ "github.com/maxbrunsfeld/counterfeiter/v6"
8)

pkg/compression/pool_test.go1

55:5call-to-gcavoid explicit garbage collection

pkg/compression/pool_test.go:55:5

54 if !assert.Eventually(t, func() bool {
55 runtime.GC()
56 return runtime.NumGoroutine() <= 50

clients/cmd/docker-driver/config.go1

135:6cognitive-complexityfunction has cognitive complexity 45; maximum is 7

clients/cmd/docker-driver/config.go:135:6

134
135func parseConfig(logCtx logger.Info) (*config, error) {
136 if err := validateDriverOpt(logCtx); err != nil {

clients/pkg/logentry/stages/drop.go1

38:2confusing-namingname source differs from Source only by capitalization

clients/pkg/logentry/stages/drop.go:38:2

37 Source interface{} `mapstructure:"source"`
38 source *[]string
39 Value *string `mapstructure:"value"`

operator/internal/handlers/internal/networkpolicy/service.go1

85:53confusing-resultsadjacent unnamed results of the same type should be named

operator/internal/handlers/internal/networkpolicy/service.go:85:53

84
85func parseServiceEndpoint(endpoint string) (string, string, int32, bool) {
86 https := strings.HasPrefix(endpoint, "https://")

clients/cmd/docker-driver/logdriver/io.go1

19:6constructor-interface-returnNewLogEntryEncoder returns interface LogEntryEncoder although its concrete result is consistently *logEntryEncoder; return the concrete type

clients/cmd/docker-driver/logdriver/io.go:19:6

18// NewLogEntryEncoder creates a protobuf stream encoder for log entries.
19func NewLogEntryEncoder(w io.Writer) LogEntryEncoder {
20 return &logEntryEncoder{

pkg/engine/internal/worker/worker_test.go1

315:111context-as-argumentcontext.Context should be the first parameter

pkg/engine/internal/worker/worker_test.go:315:111

314//nolint:revive
315func newTestWorkerWithContext(t *testing.T, logger log.Logger, loc objtest.Location, net *testNetwork, runCtx context.Context) *worker.Worker {
316 t.Helper()

pkg/bloomgateway/bloomgateway_test.go1

218:21context-cancel-in-loopcontext.WithTimeout is created in a loop but its cancellation function is not called during the iteration

pkg/bloomgateway/bloomgateway_test.go:218:21

217
218 ctx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second)
219 ctx = user.InjectOrgID(ctx, tenantID)

clients/pkg/util/client.go1

175:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

clients/pkg/util/client.go:175:2

174 // ctx is used in any upstream calls from the `client`.
175 ctx context.Context
176 cancel context.CancelFunc

pkg/storage/chunk/cache/memcached_test.go1

124:48copy-lock-valuecomposite literal copies cache_test.mockMemcache by value; it contains sync.RWMutex

pkg/storage/chunk/cache/memcached_test.go:124:48

123 keys := []string{"k1", "k2", "k3", "k4", "k5", "k6"}
124 client := &delayedMockMemcache{mockMemcache: *newMockMemcache(), delay: 10 * time.Millisecond}
125 for _, k := range keys {

clients/cmd/docker-driver/config.go1

91:6cyclomatic-complexityfunction complexity is 30; maximum is 10

clients/cmd/docker-driver/config.go:91:6

90
91func validateDriverOpt(loggerInfo logger.Info) error {
92 config := loggerInfo.Config

cmd/dataobj-inspect/main.go1

12:2deep-exitprocess-exit calls should be confined to main or init

cmd/dataobj-inspect/main.go:12:2

11 fmt.Fprint(os.Stderr, err.Error())
12 os.Exit(1)
13}

pkg/querier/queryrange/parquet_test.go1

28:2defer-close-before-error-checkcheck the error from os.CreateTemp before deferring f.Close

pkg/querier/queryrange/parquet_test.go:28:2

27 f, err := os.CreateTemp("", "metrics-*.parquet")
28 defer f.Close() // nolint:staticcheck
29

pkg/bloomgateway/client.go1

48:15deprecated-api-usagegoogle.golang.org/grpc.Dial is deprecated: use NewClient instead. Will be supported throughout 1.x.

pkg/bloomgateway/client.go:48:15

47 // nolint:staticcheck // grpc.Dial() has been deprecated; we'll address it before upgrading to gRPC 2.
48 conn, err := grpc.Dial(address, opts...)
49 if err != nil {

pkg/engine/internal/executor/dataobjscan.go1

320:2discarded-deferred-resultreturn values from a deferred function are ignored

pkg/engine/internal/executor/dataobjscan.go:320:2

319
320 defer func() {
321 // Use consistent sort order for columns. While at some point we may wish

clients/cmd/docker-driver/driver.go1

46:3discarded-error-resulterror result returned by level.Error(l.logger).Log is discarded

clients/cmd/docker-driver/driver.go:46:3

45 if err := l.stream.Close(); err != nil {
46 level.Error(l.logger).Log("msg", "error while closing fifo stream", "err", err)
47 }

clients/cmd/docker-driver/loki.go1

33:1doc-comment-perioddocumentation comment should end with punctuation

clients/cmd/docker-driver/loki.go:33:1

32
33// New create a new Loki logger that forward logs to Loki instance
34func New(logCtx logger.Info, logger log.Logger) (logger.Logger, error) {

pkg/compactor/deletion/delete_requests_store_test.go1

543:23duration-multiplied-by-durationmultiplying two time.Duration values produces squared time units; multiply a duration by a unitless count

pkg/compactor/deletion/delete_requests_store_test.go:543:23

542 UserID: user1,
543 StartTime: now.Add(-i * time.Hour),
544 EndTime: now.Add(-i * time.Hour).Add(30 * time.Minute),

clients/pkg/logentry/stages/drop.go1

171:3early-returninvert the condition and return early to reduce nesting

clients/pkg/logentry/stages/drop.go:171:3

170 if m.cfg.LongerThan != nil {
171 if len(e.Line) > m.cfg.longerThan.Val() {
172 // Too long, drop

pkg/logql/log/logfmt/jsonstring.go1

74:4enforce-switch-styledefault clause should be the last switch clause

pkg/logql/log/logfmt/jsonstring.go:74:4

73 switch s[r] {
74 default:
75 return

pkg/distributor/ratestore_test.go1

256:5error-namingpackage error variable should be named errFoo or ErrFoo

pkg/distributor/ratestore_test.go:256:5

255
256var benchErr error
257

clients/pkg/logentry/metric/counters_test.go1

85:14error-stringserror string should not be capitalized or end with punctuation

clients/pkg/logentry/metric/counters_test.go:85:14

84 if ((err != nil) && (err.Error() != tt.err.Error())) || (err == nil && tt.err != nil) {
85 t.Errorf("Metrics stage validation error, expected error = %v, actual error = %v", tt.err, err)
86 return

pkg/chunkenc/interface.go1

26:6error-type-namingerror implementation type should have an Error suffix

pkg/chunkenc/interface.go:26:6

25
26type errTooFarBehind struct {
27 // original timestamp of the entry itself.

operator/internal/handlers/internal/rules/rules_test.go1

131:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

operator/internal/handlers/internal/rules/rules_test.go:131:2

130
131 _, _, _, _, err := BuildOptions(context.TODO(), logger, k, &stack)
132

clients/cmd/docker-driver/config.go1

87:6exported-declaration-commentexported type should have a comment beginning with its name

clients/cmd/docker-driver/config.go:87:6

86
87type PipelineConfig struct {
88 PipelineStages stages.PipelineStages `yaml:"pipeline_stages,omitempty"`

clients/pkg/logentry/stages/drop_test.go1

1:1file-length-limitfile has 502 lines; maximum is 500

clients/pkg/logentry/stages/drop_test.go:1:1

1package stages
2

pkg/logql/log/pattern/lexer.rl.go1

1filename-formatfilename does not match the supported Go filename format

pkg/logql/log/pattern/lexer.rl.go:1

1
2//line pkg/logql/log/pattern/lexer.rl:1

clients/pkg/logentry/stages/inspector.go1

17:37flag-parameterboolean parameter disableFormatting controls function flow

clients/pkg/logentry/stages/inspector.go:17:37

16
17func newInspector(writer io.Writer, disableFormatting bool) *inspector {
18 f := &formatter{

clients/cmd/docker-driver/config.go2

1:1formatfile is not formatted

clients/cmd/docker-driver/config.go:1:1

1package main
2
  • Fix (safe): run `strider fmt clients/cmd/docker-driver/config.go`
135:6function-lengthfunction has 98 statements and 172 lines; maximum is 50 statements or 75 lines

clients/cmd/docker-driver/config.go:135:6

134
135func parseConfig(logCtx logger.Info) (*config, error) {
136 if err := validateDriverOpt(logCtx); err != nil {

operator/internal/config/options.go1

23:6function-result-limitfunction returns 4 values; maximum is 3

operator/internal/config/options.go:23:6

22// from a provided configuration file.
23func LoadConfig(scheme *runtime.Scheme, configFile string) (*configv1.ProjectConfig, *TokenCCOAuthConfig, ctrl.Options, error) {
24 options := ctrl.Options{Scheme: scheme}

pkg/compactor/deletion/request_handler.go1

135:33get-function-return-valueGet-prefixed function should return a value

pkg/compactor/deletion/request_handler.go:135:33

134// GetAllDeleteRequestsHandler handles get all delete requests
135func (dm *DeleteRequestHandler) GetAllDeleteRequestsHandler(w http.ResponseWriter, r *http.Request) {
136 if dm == nil {

pkg/dataobj/internal/dataset/row_reader_downloader.go1

310:31identical-if-chain-branchesif-else-if chain repeats a branch body

pkg/dataobj/internal/dataset/row_reader_downloader.go:310:31

309 continue
310 } else if page == requestor {
311 continue // Already added.

clients/pkg/logentry/stages/json.go1

163:3identical-switch-branchesswitch repeats a case body

clients/pkg/logentry/stages/json.go:163:3

162 extracted[n] = r
163 case string:
164 extracted[n] = r

clients/cmd/docker-driver/config.go2

23:2import-alias-namingimport alias should contain lower-case letters and digits

clients/cmd/docker-driver/config.go:23:2

22 "github.com/grafana/loki/v3/clients/pkg/logentry/stages"
23 clients_util "github.com/grafana/loki/v3/clients/pkg/util"
24
82:2import-shadowingidentifier labels shadows an imported package

clients/cmd/docker-driver/config.go:82:2

81type config struct {
82 labels model.LabelSet
83 clientConfig clients_util.Config

pkg/dataobj/range_reader.go1

112:12impossible-integer-comparisoncomparison is always false for type int64

pkg/dataobj/range_reader.go:112:12

111 return nil, ctx.Err()
112 } else if length > math.MaxInt {
113 return nil, fmt.Errorf("length too large: %d", length)

pkg/compactor/testutil.go1

128:46increment-decrementuse ++ or -- instead of assigning an addition or subtraction of one

pkg/compactor/testutil.go:128:46

127 commonIndexes[fileName] = ""
128 for j := 0; j < perUserDBsConfig.NumUsers; j = j + 1 {
129 commonIndexes[fileName] = commonIndexes[fileName] + BuildUserID(j) + "\n"

operator/internal/manifests/shard_rules_configmap.go1

93:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

operator/internal/manifests/shard_rules_configmap.go:93:4

92 tenant.RuleFiles = append(tenant.RuleFiles, ruleFileName)
93 opts.Tenants.Configs[tenantID] = tenant
94 }

pkg/bloomgateway/bloomgateway_test.go1

49:73inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.FormatUint with base 10

pkg/bloomgateway/bloomgateway_test.go:49:73

48 g.Labels = &logproto.IndexSeries{
49 Labels: logproto.FromLabelsToLabelAdapters(labels.FromStrings("foo", fmt.Sprintf("%d", g.Fingerprint))),
50 }

clients/cmd/docker-driver/loki_test.go1

16:16insecure-url-schemeURL uses insecure http scheme

clients/cmd/docker-driver/loki_test.go:16:16

15 Config: map[string]string{
16 "loki-url": "http://localhost:3000",
17 },

pkg/bloombuild/planner/config.go1

52:13interface-method-limitinterface has 11 methods, exceeding the configured design limit of 10

pkg/bloombuild/planner/config.go:52:13

51
52type Limits interface {
53 RetentionLimits

clients/pkg/logentry/stages/pack.go1

59:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

clients/pkg/logentry/stages/pack.go:59:7

58// MarshalJSON creates a Packed struct as JSON where the Labels are flattened into the top level of the object
59func (w Packed) MarshalJSON() ([]byte, error) {
60 // Marshal the entry to properly escape if it's json or contains quotes

cmd/migrate/main.go2

324:7max-control-nestingcontrol-flow nesting exceeds 5 levels

cmd/migrate/main.go:324:7

323 finalChks = make([]chunk.Chunk, 0, len(chunks))
324 for i := range chunks {
325 onechunk := []chunk.Chunk{chunks[i]}
275:6max-parametersfunction has 9 parameters; maximum is 8

cmd/migrate/main.go:275:6

274
275func newChunkMover(ctx context.Context, s config.SchemaConfig, source, dest storage.Store, sourceUser, destUser string, matchers []*labels.Matcher, batch int, syncRanges int) *chunkMover {
276 cm := &chunkMover{

integration/client/client.go1

477:6max-public-structsfile declares more than 5 exported structs

integration/client/client.go:477:6

476// VectorValues holds a label key value pairs for the metric and single timestamp and value
477type VectorValues struct {
478 Metric map[string]string `json:"metric"`

clients/cmd/docker-driver/driver.go1

75:2modifies-parameterassignment modifies parameter logCtx

clients/cmd/docker-driver/driver.go:75:2

74 folder := fmt.Sprintf("/var/log/docker/%s/", logCtx.ContainerID)
75 logCtx.LogPath = filepath.Join(folder, "json.log")
76 level.Info(d.logger).Log("msg", "starting logging driver for container", "id", logCtx.ContainerID, "config", fmt.Sprintf("%+v", logCtx.Config), "file", file, "logpath", logCtx.LogPath)

cmd/chunks-inspect/labels.go1

17:40modifies-value-receiverassignment modifies value receiver ls

cmd/chunks-inspect/labels.go:17:40

16func (ls Labels) Len() int { return len(ls) }
17func (ls Labels) Swap(i, j int) { ls[i], ls[j] = ls[j], ls[i] }
18func (ls Labels) Less(i, j int) bool { return ls[i].Name < ls[j].Name }

clients/cmd/docker-driver/config_test.go1

28:13nested-structsmove nested anonymous struct types to named declarations

clients/cmd/docker-driver/config_test.go:28:13

27
28 tests := []struct {
29 name string

clients/cmd/fluent-bit/loki.go1

254:6nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

clients/cmd/fluent-bit/loki.go:254:6

253 if err != nil {
254 return "", nil
255 }

pkg/analytics/reporter.go1

84:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/analytics/reporter.go:84:3

83 if !config.Enabled {
84 return nil, nil
85 }

pkg/bloombuild/builder/builder.go1

404:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/bloombuild/builder/builder.go:404:3

403 })
404 defer closeBlocksIter()
405

operator/internal/manifests/shard_rules_configmap.go1

53:4no-else-after-returnremove else and unindent its body after the return

operator/internal/manifests/shard_rules_configmap.go:53:4

52 }
53 } else {
54 return RuleName{

clients/cmd/fluent-bit/config.go1

22:6no-initreplace init with explicit initialization

clients/cmd/fluent-bit/config.go:22:6

21
22func init() {
23 // Init everything with default values.

pkg/bloomgateway/stats.go1

61:2no-naked-returnreturn values must be explicit

pkg/bloomgateway/stats.go:61:2

60 dur += s.PostProcessingTime.Load()
61 return
62}

clients/cmd/docker-driver/config.go1

69:2no-package-varpackage variables introduce mutable global state

clients/cmd/docker-driver/config.go:69:2

68var (
69 defaultClientConfig = clients_util.Config{
70 BatchWait: clients_util.BatchWait,

pkg/ingester/recalculate_owned_streams.go1

132:22non-pointer-sync-pool-valuestore a pointer-like value in sync.Pool to avoid an allocation during Put

pkg/ingester/recalculate_owned_streams.go:132:22

131 defer func() {
132 s.descsBufPool.Put(descsBuf[:0])
133 s.hostsBufPool.Put(hostsBuf[:0])

clients/pkg/logentry/stages/eventlogmessage_test.go1

353:4overwritten-before-usethis value of val is overwritten before use

clients/pkg/logentry/stages/eventlogmessage_test.go:353:4

352 if len(resultKey) > 1 {
353 val = resultKey[1]
354 }

clients/cmd/docker-driver/config.go1

1:9package-commentspackage should have a documentation comment

clients/cmd/docker-driver/config.go:1:9

1package main
2

pkg/dataobj/compaction/binpacking.go1

1:9package-directory-mismatchpackage planner does not match directory compaction

pkg/dataobj/compaction/binpacking.go:1:9

1package planner
2

clients/cmd/fluent-bit/dque.go1

148:29range-value-addresstaking the address of range value e can be misleading

clients/cmd/fluent-bit/dque.go:148:29

147 for e := range c.entries {
148 if err := c.queue.Enqueue(&dqueEntry{e.Labels, e.Timestamp, e.Line}); err != nil {
149 level.Warn(c.logger).Log("msg", fmt.Sprintf("cannot enqueue record %s:", e.Line), "err", err)

operator/api/loki/v1beta1/alertingrule_types.go1

177:7receiver-namingreceiver name dst is inconsistent with src

operator/api/loki/v1beta1/alertingrule_types.go:177:7

176// ConvertFrom converts from the Hub version (v1) to this version (v1beta1).
177func (dst *AlertingRule) ConvertFrom(srcRaw conversion.Hub) error {
178 src := srcRaw.(*v1.AlertingRule)

pkg/analytics/stats.go1

257:2redefines-builtin-ididentifier min shadows a predeclared identifier

pkg/analytics/stats.go:257:2

256type Statistics struct {
257 min *atomic.Float64
258 max *atomic.Float64

operator/tools/tools.go1

2:1redundant-build-taglegacy +build line is redundant with go:build

operator/tools/tools.go:2:1

1//go:build tools
2// +build tools
3

clients/cmd/docker-driver/config.go1

65:26redundant-conversionconversion from model.LabelName to the identical type is redundant

clients/cmd/docker-driver/config.go:65:26

64 defaultExternalLabels = "container_name={{.Name}}"
65 defaultHostLabelName = model.LabelName("host")
66)

integration/bloom_building_test.go1

20:2redundant-import-aliasimport alias is identical to the package name

integration/bloom_building_test.go:20:2

19 "github.com/grafana/loki/v3/pkg/storage"
20 v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1"
21 "github.com/grafana/loki/v3/pkg/storage/chunk/cache"

operator/internal/controller/loki/internal/lokistack/update.go1

26:3redundant-switch-breakomit unnecessary break at the end of a case clause

operator/internal/controller/loki/internal/lokistack/update.go:26:3

25 // break into retry logic below on conflict
26 break
27 case err != nil:
  • Fix (safe): remove the redundant break

pkg/storage/stores/shipper/indexshipper/tsdb/compactor_test.go1

896:20separate-byte-string-map-keyinline this byte-to-string conversion in each map lookup to avoid an allocation

pkg/storage/stores/shipper/indexshipper/tsdb/compactor_test.go:896:20

895 err = compactedIndex.ForEachSeries(context.Background(), func(series retention.Series) error {
896 seriesIDStr := string(series.SeriesID())
897 foundChunkEntries[seriesIDStr] = append(foundChunkEntries[seriesIDStr], series.Chunks()...)

integration/client/client.go1

83:3single-case-switchswitch with one case can be replaced by an if statement

integration/client/client.go:83:3

82 for _, opt := range opts {
83 switch opt.Type() {
84 case "headerinject":

pkg/storage/store.go1

432:4single-iteration-loopthe surrounding loop always terminates during its first iteration

pkg/storage/store.go:432:4

431 matchers = append(matchers, shardMatcher)
432 break // nolint:staticcheck
433 }

pkg/bloombuild/builder/builder.go1

366:3slice-preallocationpreallocate created with capacity len(range source) before appending once per iteration

pkg/bloombuild/builder/builder.go:366:3

365 blockOpts = v1.NewBlockOptions(blockEnc, maxBlockSize, maxBloomSize)
366 created []bloomshipper.Meta
367 totalSeries int

clients/pkg/util/client.go1

443:46standard-http-method-constantreplace the HTTP method literal with http.MethodPost

clients/pkg/util/client.go:443:46

442 defer cancel()
443 req, err := http.NewRequestWithContext(ctx, "POST", c.cfg.URL.String(), bytes.NewReader(buf))
444 if err != nil {

clients/pkg/logentry/stages/eventlogmessage.go1

151:1task-commentTODO comment should be resolved or linked to an owned work item

clients/pkg/logentry/stages/eventlogmessage.go:151:1

150// Sanitize a input string to convert it into a valid prometheus label
151// TODO: switch to prometheus/prometheus/util/strutil/SanitizeFullLabelName
152func SanitizeFullLabelName(input string) string {

pkg/logql/rangemapper_test.go1

137:35time-datetime.Date month argument 0 is outside 1..12

pkg/logql/rangemapper_test.go:137:35

136 )`,
137 queryTime: time.Date(0, 0, 0, 12, 54, 0, 0, time.UTC), // 1970 12:54:00
138 splityByInterval: 1 * time.Hour,

pkg/canary/writer/writer.go1

43:17time-namingtime.Duration name should not include a unit suffix

pkg/canary/writer/writer.go:43:17

42 sentChan chan time.Time,
43 entryInterval, outOfOrderMin, outOfOrderMax time.Duration,
44 outOfOrderPercentage, entrySize int,

pkg/dataobj/sections/logs/table_build.go1

107:5time-value-equalitycompare time.Time values with Time.Equal instead of == or !=

pkg/dataobj/sections/logs/table_build.go:107:5

106 }
107 if a.Timestamp != b.Timestamp {
108 return false

clients/cmd/docker-driver/config_test.go1

62:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/cmd/docker-driver/config_test.go:62:1

61
62var pipelineString = `
63- regex:

clients/cmd/fluent-bit/loki.go1

140:24unchecked-type-assertionuse the checked two-result form of the type assertion

clients/cmd/fluent-bit/loki.go:140:24

139
140 for k, v := range kube.(map[string]interface{}) {
141 switch k {

clients/pkg/util/client.go1

467:2unclosed-http-response-bodylocally acquired HTTP response body is not directly closed or transferred before replacement or function exit

clients/pkg/util/client.go:467:2

466
467 resp, err := c.client.Do(req)
468 if err != nil {

pkg/logql/log/pattern/lexer.rl.go1

7unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:7

6//line pkg/logql/log/pattern/lexer.rl.go:7
7var _pattern_actions []byte = []byte{
8 0, 1, 0, 1, 1, 1, 2, 1, 3,

clients/pkg/logentry/stages/decolorize.go1

14:46unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/decolorize.go:14:46

13// Run implements Stage
14func (m *decolorizeStage) Run(in chan Entry) chan Entry {
15 decolorizer, _ := log.NewDecolorizer()

pkg/tool/printer/printer.go1

63:2unnecessary-formatformatting call has no formatting directive

pkg/tool/printer/printer.go:63:2

62
63 fmt.Printf("\nTemplates:\n")
64 for fn, template := range templates {

pkg/logql/log/logfmt/decode.go1

58:1unreachable-codestatement is unreachable after unconditional control flow

pkg/logql/log/logfmt/decode.go:58:1

57
58key:
59 const invalidKeyError = "invalid key"

pkg/querytee/proxy_backend_test.go1

61:36unsafe-formatted-url-host-portformatted host and port may be invalid for IPv6; build the address with net.JoinHostPort

pkg/querytee/proxy_backend_test.go:61:36

60 t.Run(testName, func(t *testing.T) {
61 u, err := url.Parse(fmt.Sprintf("http://%s:%s@test", testData.backendUser, testData.backendPass))
62 require.NoError(t, err)

operator/internal/controller/loki/recordingrule_controller.go1

41:66unused-parameterparameter req is unused

operator/internal/controller/loki/recordingrule_controller.go:41:66

40// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.11.0/pkg/reconcile
41func (r *RecordingRuleReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
42 err := lokistack.AnnotateForDiscoveredRules(ctx, r.Client)

clients/cmd/docker-driver/loki.go1

91:7unused-receiverreceiver l is unused

clients/cmd/docker-driver/loki.go:91:7

90// Log implements `logger.Logger`
91func (l *loki) Name() string {
92 return driverName

clients/cmd/docker-driver/config.go1

399:38use-anyuse any instead of interface{}

clients/cmd/docker-driver/config.go:399:38

398// loadConfig read YAML-formatted config from filename into cfg.
399func loadConfig(filename string, cfg interface{}) error {
400 buf, err := os.ReadFile(filename)

cmd/chunks-inspect/loki.go1

191:16use-errors-newreplace fmt.Errorf with errors.New for a static message

cmd/chunks-inspect/loki.go:191:16

190 if n <= 0 {
191 return nil, fmt.Errorf("failed to read number of labels in structured metadata")
192 }

pkg/querier/queryrange/detected_fields_test.go1

1126:4use-fmt-printuse fmt.Print or fmt.Println instead of the builtin

pkg/querier/queryrange/detected_fields_test.go:1126:4

1125 for _, field := range detectedFields {
1126 print(field.Label)
1127 switch field.Label {

clients/pkg/logentry/stages/multiline_test.go1

76:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

clients/pkg/logentry/stages/multiline_test.go:76:2

75
76 sort.Slice(out, func(l, r int) bool {
77 return out[l].Timestamp.Before(out[r].Timestamp)

clients/pkg/logentry/stages/util_test.go1

68:11var-namingidentifier should use MixedCaps rather than underscores

clients/pkg/logentry/stages/util_test.go:68:11

67func TestGetString(t *testing.T) {
68 var f64, f64_1 float64
69 var f32 float32

clients/pkg/logentry/stages/multiline.go1

128:5waitgroup-add-inside-goroutinecall WaitGroup.Add before starting the goroutine to avoid racing with Wait

clients/pkg/logentry/stages/multiline.go:128:5

127
128 wg.Add(1)
129 go m.runMultiline(s, out, wg)

pkg/util/shard.go1

32:12weak-cryptographydeprecated cryptographic primitive crypto/md5.New should not protect new data

pkg/util/shard.go:32:12

31 // Use the identifier to compute an hash we'll use to seed the random.
32 hasher := md5.New() //#nosec G401 -- This does not require collision resistance, this is an intentionally predictable value -- nosemgrep: use-of-md5
33 hasher.Write(YoloBuf(identifier)) // nolint:errcheck

clients/cmd/docker-driver/driver.go1

55:29add-constantstring literal "msg" appears more than twice; define a constant

clients/cmd/docker-driver/driver.go:55:29

54 if err := l.jsonl.Close(); err != nil {
55 level.Error(l.logger).Log("msg", "error while closing json logger", "err", err)
56 }

pkg/logql/bench/discover/pkg/tsdb/reader_test.go1

52:2call-to-gcavoid explicit garbage collection

pkg/logql/bench/discover/pkg/tsdb/reader_test.go:52:2

51
52 runtime.GC()
53 runtime.GC()

clients/cmd/docker-driver/driver.go1

67:18cognitive-complexityfunction has cognitive complexity 10; maximum is 7

clients/cmd/docker-driver/driver.go:67:18

66
67func (d *driver) StartLogging(file string, logCtx logger.Info) error {
68 d.mu.Lock()

clients/pkg/logentry/stages/drop.go1

44:2confusing-namingname olderThan differs from OlderThan only by capitalization

clients/pkg/logentry/stages/drop.go:44:2

43 OlderThan *string `mapstructure:"older_than"`
44 olderThan time.Duration
45 LongerThan *string `mapstructure:"longer_than"`

operator/internal/handlers/internal/storage/secrets.go1

68:120confusing-resultsadjacent unnamed results of the same type should be named

operator/internal/handlers/internal/storage/secrets.go:68:120

67
68func getSecrets(ctx context.Context, k k8s.Client, stack *lokiv1.LokiStack, fg configv1.FeatureGates) (*corev1.Secret, *corev1.Secret, error) {
69 var (

clients/cmd/docker-driver/logdriver/io.go1

52:6constructor-interface-returnNewLogEntryDecoder returns interface LogEntryDecoder although its concrete result is consistently *logEntryDecoder; return the concrete type

clients/cmd/docker-driver/logdriver/io.go:52:6

51// NewLogEntryDecoder creates a new stream decoder for log entries.
52func NewLogEntryDecoder(r io.Reader) LogEntryDecoder {
53 return &logEntryDecoder{

pkg/storage/stores/shipper/indexshipper/testutil/testutil.go1

49:37context-as-argumentcontext.Context should be the first parameter

pkg/storage/stores/shipper/indexshipper/testutil/testutil.go:49:37

48// nolint
49func queryIndexes(t *testing.T, ctx context.Context, queries []boltdbcommon.Query, indexIteratorFunc IndexIteratorFunc, callback boltdbcommon.QueryPagesCallback) {
50 userID, err := tenant.TenantID(ctx)

pkg/bloomgateway/bloomgateway_test.go1

262:21context-cancel-in-loopcontext.WithTimeout is created in a loop but its cancellation function is not called during the iteration

pkg/bloomgateway/bloomgateway_test.go:262:21

261
262 ctx, cancelFn := context.WithTimeout(context.Background(), 500*time.Millisecond)
263 ctx = user.InjectOrgID(ctx, tenantID)

cmd/migrate/main.go1

264:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

cmd/migrate/main.go:264:2

263type chunkMover struct {
264 ctx context.Context
265 schema config.SchemaConfig

clients/cmd/docker-driver/config.go1

135:6cyclomatic-complexityfunction complexity is 39; maximum is 10

clients/cmd/docker-driver/config.go:135:6

134
135func parseConfig(logCtx logger.Info) (*config, error) {
136 if err := validateDriverOpt(logCtx); err != nil {

cmd/logcli/main.go1

727:3deep-exitprocess-exit calls should be confined to main or init

cmd/logcli/main.go:727:3

726 if err != nil {
727 log.Fatalf("Unable to parse time %v", err)
728 }

pkg/querier/queryrange/parquet_test.go1

53:2defer-close-before-error-checkcheck the error from os.CreateTemp before deferring f.Close

pkg/querier/queryrange/parquet_test.go:53:2

52 f, err := os.CreateTemp("", "logs-*.parquet")
53 defer f.Close() // nolint:staticcheck
54

pkg/compactor/client/grpc.go1

88:21deprecated-api-usagegoogle.golang.org/grpc.Dial is deprecated: use NewClient instead. Will be supported throughout 1.x.

pkg/compactor/client/grpc.go:88:21

87 // nolint:staticcheck // grpc.Dial() has been deprecated; we'll address it before upgrading to gRPC 2.
88 client.conn, err = grpc.Dial(addr, dialOpts...)
89 if err != nil {

clients/cmd/docker-driver/driver.go1

49:3discarded-error-resulterror result returned by level.Error(l.logger).Log is discarded

clients/cmd/docker-driver/driver.go:49:3

48 if err := l.lokil.Close(); err != nil {
49 level.Error(l.logger).Log("msg", "error while closing loki logger", "err", err)
50 }

clients/cmd/docker-driver/loki.go1

64:1doc-comment-perioddocumentation comment should end with punctuation

clients/cmd/docker-driver/loki.go:64:1

63
64// Log implements `logger.Logger`
65func (l *loki) Log(m *logger.Message) error {

pkg/compactor/deletion/delete_requests_store_test.go1

544:23duration-multiplied-by-durationmultiplying two time.Duration values produces squared time units; multiply a duration by a unitless count

pkg/compactor/deletion/delete_requests_store_test.go:544:23

543 StartTime: now.Add(-i * time.Hour),
544 EndTime: now.Add(-i * time.Hour).Add(30 * time.Minute),
545 Query: fmt.Sprintf(`{foo="%d", user="%s"}`, i, user1),

clients/pkg/logentry/stages/drop.go1

186:3early-returninvert the condition and return early to reduce nesting

clients/pkg/logentry/stages/drop.go:186:3

185 ct := time.Now()
186 if e.Timestamp.Before(ct.Add(-m.cfg.olderThan)) {
187 // Too old, drop

pkg/logql/syntax/query_scanner.go1

481:2enforce-switch-styledefault clause should be the last switch clause

pkg/logql/syntax/query_scanner.go:481:2

480 switch prefix {
481 default:
482 return "decimal literal"

pkg/engine/internal/executor/pipeline.go1

37:2error-namingpackage error variable should be named errFoo or ErrFoo

pkg/engine/internal/executor/pipeline.go:37:2

36 errPipelineNotOpen = errors.New("pipeline not opened")
37 EOF = fmt.Errorf("pipeline exhausted: %w", io.EOF) //nolint:revive,staticcheck
38)

clients/pkg/logentry/stages/json_test.go1

143:27error-stringserror string should not be capitalized or end with punctuation

clients/pkg/logentry/stages/json_test.go:143:27

142 0,
143 errors.Wrap(errors.New("SyntaxError: Unknown char: '#'"), ErrCouldNotCompileJMES),
144 },

pkg/columnar/error.go1

5:6error-type-namingerror implementation type should have an Error suffix

pkg/columnar/error.go:5:6

4
5type errorSliceBounds struct {
6 i, j int

operator/internal/handlers/internal/rules/rules_test.go1

254:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

operator/internal/handlers/internal/rules/rules_test.go:254:2

253
254 _, _, _, _, err := BuildOptions(context.TODO(), logger, k, &stack)
255

clients/cmd/docker-driver/http.go1

14:6exported-declaration-commentexported type should have a comment beginning with its name

clients/cmd/docker-driver/http.go:14:6

13
14type StartLoggingRequest struct {
15 File string

clients/pkg/logentry/stages/metrics_test.go1

1:1file-length-limitfile has 636 lines; maximum is 500

clients/pkg/logentry/stages/metrics_test.go:1:1

1package stages
2

cmd/chunks-inspect/main.go1

28:33flag-parameterboolean parameter blockDetails controls function flow

cmd/chunks-inspect/main.go:28:33

27
28func printFile(filename string, blockDetails, printLines, storeBlocks bool) {
29 f, err := os.Open(filename)

clients/cmd/docker-driver/config_test.go1

1:1formatfile is not formatted

clients/cmd/docker-driver/config_test.go:1:1

1package main
2
  • Fix (safe): run `strider fmt clients/cmd/docker-driver/config_test.go`

clients/cmd/fluent-bit/config.go1

72:6function-lengthfunction has 124 statements and 213 lines; maximum is 50 statements or 75 lines

clients/cmd/fluent-bit/config.go:72:6

71
72func parseConfig(cfg ConfigGetter) (*config, error) {
73 res := &config{}

operator/internal/handlers/internal/networkpolicy/service.go1

85:6function-result-limitfunction returns 4 values; maximum is 3

operator/internal/handlers/internal/networkpolicy/service.go:85:6

84
85func parseServiceEndpoint(endpoint string) (string, string, int32, bool) {
86 https := strings.HasPrefix(endpoint, "https://")

pkg/compactor/deletion/request_handler.go1

306:33get-function-return-valueGet-prefixed function should return a value

pkg/compactor/deletion/request_handler.go:306:33

305// GetCacheGenerationNumberHandler handles requests for a user's cache generation number
306func (dm *DeleteRequestHandler) GetCacheGenerationNumberHandler(w http.ResponseWriter, r *http.Request) {
307 if dm == nil {

pkg/dataobj/internal/dataset/row_reader_downloader.go1

334:31identical-if-chain-branchesif-else-if chain repeats a branch body

pkg/dataobj/internal/dataset/row_reader_downloader.go:334:31

333 continue
334 } else if page == requestor {
335 continue // Already added.

clients/pkg/logentry/stages/json.go1

165:3identical-switch-branchesswitch repeats a case body

clients/pkg/logentry/stages/json.go:165:3

164 extracted[n] = r
165 case bool:
166 extracted[n] = r

clients/cmd/docker-driver/config_test.go1

16:2import-alias-namingimport alias should contain lower-case letters and digits

clients/cmd/docker-driver/config_test.go:16:2

15
16 util_log "github.com/grafana/loki/v3/pkg/util/log"
17)

clients/cmd/docker-driver/config.go1

141:2import-shadowingidentifier labels shadows an imported package

clients/cmd/docker-driver/config.go:141:2

140 clientConfig := defaultClientConfig
141 labels := model.LabelSet{}
142

pkg/dataset/file_header.go1

132:5impossible-integer-comparisoncomparison is always false for type int64

pkg/dataset/file_header.go:132:5

131 }
132 if size > int64(math.MaxInt) {
133 return nil, 0, fmt.Errorf("%s is too large to read: %d bytes", name, size)

pkg/distributor/distributor_test.go1

566:5increment-decrementuse ++ or -- instead of assigning an addition or subtraction of one

pkg/distributor/distributor_test.go:566:5

565 for _, st := range pr.Streams {
566 labels[st.Labels] = labels[st.Labels] + 1
567 }

pkg/bloombuild/planner/retention_test.go1

743:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

pkg/bloombuild/planner/retention_test.go:743:4

742 if _, ok := tenants[tenant]; !ok {
743 tenants[tenant] = &validation.Limits{}
744 }

pkg/bloomgateway/querier_test.go1

205:34inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

pkg/bloomgateway/querier_test.go:205:34

204 for i := 0; i < n; i++ {
205 s := labels.FromStrings("app", fmt.Sprintf("%d", i))
206 sFP := labels.StableHash(s)

clients/cmd/fluent-bit/config.go1

81:9insecure-url-schemeURL uses insecure http scheme

clients/cmd/fluent-bit/config.go:81:9

80 if url == "" {
81 url = "http://localhost:3100/loki/api/v1/push"
82 }

pkg/chunkenc/interface.go1

52:12interface-method-limitinterface has 17 methods, exceeding the configured design limit of 10

pkg/chunkenc/interface.go:52:12

51// Chunk is the interface for the compressed logs chunk format.
52type Chunk interface {
53 Bounds() (time.Time, time.Time)

cmd/chunks-inspect/labels.go1

74:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

cmd/chunks-inspect/labels.go:74:7

73// UnmarshalJSON implements json.Unmarshaler.
74func (ls *Labels) UnmarshalJSON(b []byte) error {
75 var m map[string]string

cmd/migrate/main.go1

327:8max-control-nestingcontrol-flow nesting exceeds 5 levels

cmd/migrate/main.go:327:8

326 var retry int
327 for retry = 4; retry >= 0; retry-- {
328 onechunk, err = f.FetchChunks(m.ctx, onechunk)

operator/internal/manifests/gateway.go1

645:6max-parametersfunction has 9 parameters; maximum is 8

operator/internal/manifests/gateway.go:645:6

644// configureObsGatewayServerPKI configures PKI for the observatorium gateway.
645func configureObsGatewayServerPKI(
646 podSpec *corev1.PodSpec,

integration/client/client.go1

505:6max-public-structsfile declares more than 5 exported structs

integration/client/client.go:505:6

504// DataType holds the result type and a list of StreamValues
505type DataType struct {
506 ResultType string

clients/cmd/docker-driver/loki.go1

35:2modifies-parameterassignment modifies parameter logger

clients/cmd/docker-driver/loki.go:35:2

34func New(logCtx logger.Info, logger log.Logger) (logger.Logger, error) {
35 logger = log.With(logger, "container_id", logCtx.ContainerID)
36 cfg, err := parseConfig(logCtx)

cmd/chunks-inspect/labels.go1

17:47modifies-value-receiverassignment modifies value receiver ls

cmd/chunks-inspect/labels.go:17:47

16func (ls Labels) Len() int { return len(ls) }
17func (ls Labels) Swap(i, j int) { ls[i], ls[j] = ls[j], ls[i] }
18func (ls Labels) Less(i, j int) bool { return ls[i].Name < ls[j].Name }

clients/cmd/docker-driver/config_test.go1

94:13nested-structsmove nested anonymous struct types to named declarations

clients/cmd/docker-driver/config_test.go:94:13

93 }
94 tests := []struct {
95 name string

clients/cmd/fluent-bit/loki.go1

259:5nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

clients/cmd/fluent-bit/loki.go:259:5

258 if err != nil {
259 return "", nil
260 }

pkg/analytics/seed.go1

26:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/analytics/seed.go:26:3

25 if mergeable == nil {
26 return nil, nil
27 }

pkg/dataobj/consumer/logsobj/builder_test.go1

369:5no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/dataobj/consumer/logsobj/builder_test.go:369:5

368 require.NoError(b, err)
369 defer closer2.Close()
370 }

operator/internal/manifests/storage/configure.go1

227:5no-else-after-returnremove else and unindent its body after the return

operator/internal/manifests/storage/configure.go:227:5

226 }
227 } else {
228 return []corev1.EnvVar{

clients/cmd/fluent-bit/out_grafana_loki.go1

30:6no-initreplace init with explicit initialization

clients/cmd/fluent-bit/out_grafana_loki.go:30:6

29
30func init() {
31 var logLevel dslog.Level

pkg/chunkenc/unordered.go1

204:3no-naked-returnreturn values must be explicit

pkg/chunkenc/unordered.go:204:3

203 if hb.IsEmpty() || (maxt < hb.mint || hb.maxt < mint) {
204 return
205 }

clients/cmd/docker-driver/config_test.go1

19:5no-package-varpackage variables introduce mutable global state

clients/cmd/docker-driver/config_test.go:19:5

18
19var jobRename = `
20- regex: (.*)

pkg/ingester/recalculate_owned_streams.go1

133:22non-pointer-sync-pool-valuestore a pointer-like value in sync.Pool to avoid an allocation during Put

pkg/ingester/recalculate_owned_streams.go:133:22

132 s.descsBufPool.Put(descsBuf[:0])
133 s.hostsBufPool.Put(hostsBuf[:0])
134 s.zoneBufPool.Put(zoneBuf[:0])

clients/pkg/logentry/stages/eventlogmessage_test.go1

357:4overwritten-before-usethis value of val is overwritten before use

clients/pkg/logentry/stages/eventlogmessage_test.go:357:4

356 if len(resultKeyValue) > 1 {
357 val = resultKeyValue[1]
358 }

clients/cmd/docker-driver/driver.go1

1:9package-commentspackage should have a documentation comment

clients/cmd/docker-driver/driver.go:1:9

1package main
2

pkg/dataobj/compaction/binpacking_test.go1

1:9package-directory-mismatchpackage planner does not match directory compaction

pkg/dataobj/compaction/binpacking_test.go:1:9

1package planner
2

clients/cmd/fluent-bit/loki_test.go1

90:9range-value-addresstaking the address of range value tt can be misleading

clients/cmd/fluent-bit/loki_test.go:90:9

89 rec := util.NewFakeClient(func() {})
90 l := &loki{
91 cfg: tt.cfg,

operator/api/loki/v1beta1/lokistack_types.go1

1127:7receiver-namingreceiver name dst is inconsistent with src

operator/api/loki/v1beta1/lokistack_types.go:1127:7

1126// nolint:golint
1127func (dst *LokiStack) ConvertFrom(srcRaw conversion.Hub) error {
1128 src := srcRaw.(*v1.LokiStack)

pkg/analytics/stats.go1

258:2redefines-builtin-ididentifier max shadows a predeclared identifier

pkg/analytics/stats.go:258:2

257 min *atomic.Float64
258 max *atomic.Float64
259 count *atomic.Int64

pkg/logql/sketch/topk_slow_test.go1

2:1redundant-build-taglegacy +build line is redundant with go:build

pkg/logql/sketch/topk_slow_test.go:2:1

1//go:build sketch_slow
2// +build sketch_slow
3

clients/cmd/fluent-bit/loki_test.go1

127:23redundant-conversionconversion from format to the identical type is redundant

clients/cmd/fluent-bit/loki_test.go:127:23

126 {"kv empty", map[string]interface{}{}, kvPairFormat, ``, false},
127 {"bad format", nil, format(3), "", true},
128 {"nested json", map[string]interface{}{"log": `{"level":"error"}`}, jsonFormat, `{"log":{"level":"error"}}`, false},

operator/api/loki/v1beta1/alertingrule_types.go1

4:2redundant-import-aliasimport alias is identical to the package name

operator/api/loki/v1beta1/alertingrule_types.go:4:2

3import (
4 v1 "github.com/grafana/loki/operator/api/loki/v1"
5 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

operator/internal/controller/loki/internal/lokistack/update.go1

58:3redundant-switch-breakomit unnecessary break at the end of a case clause

operator/internal/controller/loki/internal/lokistack/update.go:58:3

57 // break into retry logic below on conflict
58 break
59 case err != nil:
  • Fix (safe): remove the redundant break

operator/internal/certrotation/build_test.go1

39:3single-case-switchswitch with one case can be replaced by an if statement

operator/internal/certrotation/build_test.go:39:3

38
39 switch o := obj.(type) {
40 case *corev1.Secret:

pkg/bloombuild/planner/versioned_range.go1

215:6slice-preallocationpreallocate upToDate with capacity len(range source) before appending once per iteration

pkg/bloombuild/planner/versioned_range.go:215:6

214 var outdated []bloomshipper.Meta
215 var upToDate []bloomshipper.Meta
216

integration/client/client.go1

154:30standard-http-method-constantreplace the HTTP method literal with http.MethodPost

integration/client/client.go:154:30

153 }
154 req, err := http.NewRequest("POST", apiEndpoint, bytes.NewReader(data))
155 if err != nil {

clients/pkg/logentry/stages/inspector.go1

90:2task-commentTODO comment should be resolved or linked to an owned work item

clients/pkg/logentry/stages/inspector.go:90:2

89
90 // TODO(dannyk): try using go-cmp to filter this condition out with Equal(), but for now this just makes it work
91 if fmt.Sprintf("%v", vx) == fmt.Sprintf("%v", vy) {

pkg/logql/rangemapper_test.go1

137:38time-datetime.Date day argument 0 is outside 1..31

pkg/logql/rangemapper_test.go:137:38

136 )`,
137 queryTime: time.Date(0, 0, 0, 12, 54, 0, 0, time.UTC), // 1970 12:54:00
138 splityByInterval: 1 * time.Hour,

pkg/logcli/query/query.go1

586:9time-value-equalitycompare time.Time values with Time.Equal instead of == or !=

pkg/logcli/query/query.go:586:9

585func (q *Query) isInstant() bool {
586 return q.Start == q.End && q.Step == 0
587}

clients/cmd/docker-driver/http.go1

85:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/cmd/docker-driver/http.go:85:1

84
85type response struct {
86 Err string

clients/cmd/fluent-bit/loki.go1

143:23unchecked-type-assertionuse the checked two-result form of the type assertion

clients/cmd/fluent-bit/loki.go:143:23

142 case "labels":
143 for m, n := range v.(map[string]interface{}) {
144 kuberneteslbs[model.LabelName(keyReplacer.Replace(m))] = model.LabelValue(fmt.Sprintf("%v", n))

pkg/canary/reader/reader.go1

250:2unclosed-http-response-bodylocally acquired HTTP response body is not directly closed or transferred before replacement or function exit

pkg/canary/reader/reader.go:250:2

249
250 resp, err := r.httpClient.Do(req)
251 if err != nil {

pkg/logql/log/pattern/lexer.rl.go1

12unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:12

11
12var _pattern_key_offsets []byte = []byte{
13 0, 0, 8, 10, 12, 14, 16, 18,

clients/pkg/logentry/stages/drop.go1

149:40unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/drop.go:149:40

148
149func (m *dropStage) Run(in chan Entry) chan Entry {
150 out := make(chan Entry)

tools/deprecated-config-checker/main.go1

75:2unnecessary-formatformatting call has no formatting directive

tools/deprecated-config-checker/main.go:75:2

74
75 fmt.Printf("No deprecated or deleted configs found.\n")
76}

pkg/logql/log/logfmt/decode.go1

106:1unreachable-codestatement is unreachable after unconditional control flow

pkg/logql/log/logfmt/decode.go:106:1

105
106equal:
107 dec.pos++

operator/internal/handlers/dashboards_create.go1

20:94unused-parameterparameter s is unused

operator/internal/handlers/dashboards_create.go:20:94

19// CreateDashboards handles the LokiStack dashboards create events.
20func CreateDashboards(ctx context.Context, log logr.Logger, operatorNs string, k k8s.Client, s *runtime.Scheme) error {
21 objs, err := openshift.BuildDashboards(operatorNs)

clients/cmd/fluent-bit/dque.go1

154:7unused-receiverreceiver c is unused

clients/cmd/fluent-bit/dque.go:154:7

153
154func (c *dqueClient) Name() string {
155 return ""

clients/cmd/docker-driver/config_test.go1

69:20use-anyuse any instead of interface{}

clients/cmd/docker-driver/config_test.go:69:20

68var pipeline = PipelineConfig{
69 PipelineStages: []interface{}{
70 map[string]interface{}{

cmd/chunks-inspect/loki.go1

208:17use-errors-newreplace fmt.Errorf with errors.New for a static message

cmd/chunks-inspect/loki.go:208:17

207 if read <= 0 {
208 return nil, fmt.Errorf("expected to find a length for a structured metadata string but did not find one")
209 }

integration/loki_micro_services_delete_test.go1

224:3use-slices-sortuse slices.Sort or slices.SortFunc when possible

integration/loki_micro_services_delete_test.go:224:3

223 require.Len(t, resp.Data.Stream, len(expectedStreams))
224 sort.Slice(resp.Data.Stream, func(i, j int) bool {
225 return labels.FromMap(resp.Data.Stream[i].Stream).String() < labels.FromMap(resp.Data.Stream[j].Stream).String()

clients/pkg/logentry/stages/util_test.go1

78:2var-namingidentifier should use MixedCaps rather than underscores

clients/pkg/logentry/stages/util_test.go:78:2

77 }
78 s64_1, err := getString(f64_1)
79 if err != nil {

pkg/engine/internal/scheduler/wire/wire_http2_test.go1

257:4waitgroup-add-inside-goroutinecall WaitGroup.Add before starting the goroutine to avoid racing with Wait

pkg/engine/internal/scheduler/wire/wire_http2_test.go:257:4

256
257 serverWg.Add(1)
258 go func(p *wire.Peer) {

clients/cmd/docker-driver/driver.go1

55:71add-constantstring literal "err" appears more than twice; define a constant

clients/cmd/docker-driver/driver.go:55:71

54 if err := l.jsonl.Close(); err != nil {
55 level.Error(l.logger).Log("msg", "error while closing json logger", "err", err)
56 }

pkg/logql/bench/discover/pkg/tsdb/reader_test.go1

53:2call-to-gcavoid explicit garbage collection

pkg/logql/bench/discover/pkg/tsdb/reader_test.go:53:2

52 runtime.GC()
53 runtime.GC()
54

clients/cmd/docker-driver/driver.go1

137:6cognitive-complexityfunction has cognitive complexity 20; maximum is 7

clients/cmd/docker-driver/driver.go:137:6

136
137func consumeLog(lf *logPair) {
138 dec := logdriver.NewLogEntryDecoder(lf.stream)

clients/pkg/logentry/stages/drop.go1

46:2confusing-namingname longerThan differs from LongerThan only by capitalization

clients/pkg/logentry/stages/drop.go:46:2

45 LongerThan *string `mapstructure:"longer_than"`
46 longerThan flagext.ByteSize
47}

operator/internal/manifests/internal/config/build.go1

34:35confusing-resultsadjacent unnamed results of the same type should be named

operator/internal/manifests/internal/config/build.go:34:35

33// Build builds a loki stack configuration files
34func Build(opts Options) ([]byte, []byte, error) {
35 // Build loki config yaml

clients/pkg/logentry/logql/ast.go1

43:6constructor-interface-returnNewFilterExpr returns interface Expr although its concrete result is consistently *filterExpr; return the concrete type

clients/pkg/logentry/logql/ast.go:43:6

42// NewFilterExpr wraps an existing Expr with a next filter expression.
43func NewFilterExpr(left Expr, ty labels.MatchType, match string) Expr {
44 return &filterExpr{

production/helm/loki/src/helm-test/canary_test.go1

80:45context-as-argumentcontext.Context should be the first parameter

production/helm/loki/src/helm-test/canary_test.go:80:45

79
80func testResultPrometheus(t *testing.T, ctx context.Context, query string, test func(model.SampleValue) bool, msg string) error {
81 // TODO (ewelch): if we did a lot of these, we'd want to reuse the client but right now we only run a couple tests

pkg/compactor/compactor.go1

494:34context-cancel-in-loopcontext.WithCancel is created in a loop but its cancellation function is not called during the iteration

pkg/compactor/compactor.go:494:34

493 level.Info(util_log.Logger).Log("msg", "this instance has been chosen to run the compactor, starting compactor")
494 runningCtx, runningCancel = context.WithCancel(ctx)
495

pkg/bloombuild/builder/batch.go1

35:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

pkg/bloombuild/builder/batch.go:35:2

34 batchSize int
35 ctx context.Context
36 fetchers []Fetcher[A, B]

clients/cmd/docker-driver/driver.go1

137:6cyclomatic-complexityfunction complexity is 11; maximum is 10

clients/cmd/docker-driver/driver.go:137:6

136
137func consumeLog(lf *logPair) {
138 dec := logdriver.NewLogEntryDecoder(lf.stream)

cmd/loki/main.go1

41:2deep-exitprocess-exit calls should be confined to main or init

cmd/loki/main.go:41:2

40 util_log.Flush()
41 os.Exit(code)
42}

pkg/compactor/deletion/grpc_request_handler_test.go1

41:15deprecated-api-usagegoogle.golang.org/grpc.DialContext is deprecated: use NewClient instead. Will be supported throughout 1.x.

pkg/compactor/deletion/grpc_request_handler_test.go:41:15

40 // nolint:staticcheck // grpc.DialContext() has been deprecated; we'll address it before upgrading to gRPC 2.
41 conn, err := grpc.DialContext(context.Background(), "",
42 grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {

clients/cmd/docker-driver/driver.go1

55:3discarded-error-resulterror result returned by level.Error(l.logger).Log is discarded

clients/cmd/docker-driver/driver.go:55:3

54 if err := l.jsonl.Close(); err != nil {
55 level.Error(l.logger).Log("msg", "error while closing json logger", "err", err)
56 }

clients/cmd/docker-driver/loki.go1

90:1doc-comment-perioddocumentation comment should end with punctuation

clients/cmd/docker-driver/loki.go:90:1

89
90// Log implements `logger.Logger`
91func (l *loki) Name() string {

pkg/compactor/deletion/delete_requests_store_test.go1

550:23duration-multiplied-by-durationmultiplying two time.Duration values produces squared time units; multiply a duration by a unitless count

pkg/compactor/deletion/delete_requests_store_test.go:550:23

549 UserID: user2,
550 StartTime: now.Add(-i * time.Hour),
551 EndTime: now.Add(-(i + 1) * time.Hour),

clients/pkg/logentry/stages/drop.go1

206:3early-returninvert the condition and return early to reduce nesting

clients/pkg/logentry/stages/drop.go:206:3

205 }
206 if match {
207 if Debug {

pkg/engine/internal/scheduler/wire/error.go1

16:5error-namingpackage error variable should be named errFoo or ErrFoo

pkg/engine/internal/scheduler/wire/error.go:16:5

15
16var _ error = (*Error)(nil)
17

clients/pkg/logentry/stages/metrics_test.go1

422:14error-stringserror string should not be capitalized or end with punctuation

clients/pkg/logentry/stages/metrics_test.go:422:14

421 if ((err != nil) && (err.Error() != test.err.Error())) || (err == nil && test.err != nil) {
422 t.Errorf("Metrics stage validation error, expected error = %v, actual error = %v", test.err, err)
423 return

pkg/logql/bench/faker.go1

216:6error-type-namingerror implementation type should have an Error suffix

pkg/logql/bench/faker.go:216:6

215// Faker provides methods to generate fake data consistently
216type Faker struct {
217 rnd *rand.Rand

pkg/distributor/distributor_test.go1

1372:3excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

pkg/distributor/distributor_test.go:1372:3

1371 stream.Labels = `{buzz="f", a="b"}`
1372 _, _, _, _, _, err := d.parseStreamLabels(context.Background(), vCtx, stream.Labels, stream, streamResolver, constants.Loki)
1373 if err != nil {

clients/cmd/docker-driver/http.go1

19:6exported-declaration-commentexported type should have a comment beginning with its name

clients/cmd/docker-driver/http.go:19:6

18
19type StopLoggingRequest struct {
20 File string

clients/pkg/util/client.go1

1:1file-length-limitfile has 524 lines; maximum is 500

clients/pkg/util/client.go:1:1

1package util
2

cmd/chunks-inspect/main.go1

28:47flag-parameterboolean parameter printLines controls function flow

cmd/chunks-inspect/main.go:28:47

27
28func printFile(filename string, blockDetails, printLines, storeBlocks bool) {
29 f, err := os.Open(filename)

clients/cmd/docker-driver/driver.go1

1:1formatfile is not formatted

clients/cmd/docker-driver/driver.go:1:1

1package main
2
  • Fix (safe): run `strider fmt clients/cmd/docker-driver/driver.go`

clients/cmd/fluent-bit/config_labels_test.go1

13:6function-lengthfunction has 3 statements and 79 lines; maximum is 50 statements or 75 lines

clients/cmd/fluent-bit/config_labels_test.go:13:6

12
13func Test_externalLabelsFromFluentBitLabelsOption(t *testing.T) {
14 tests := []struct {

operator/internal/handlers/internal/rules/rules.go1

25:6function-result-limitfunction returns 5 values; maximum is 3

operator/internal/handlers/internal/rules/rules.go:25:6

24// - When remote write is enabled and the authorization Secret data is invalid.
25func BuildOptions(
26 ctx context.Context,

pkg/distributor/ratestore.go1

293:21get-function-return-valueGet-prefixed function should return a value

pkg/distributor/ratestore.go:293:21

292
293func (s *rateStore) getRatesFromIngesters(ctx context.Context, clients chan ingesterClient, responses chan *logproto.StreamRatesResponse) {
294 for c := range clients {

pkg/dataobj/internal/dataset/row_reader_downloader.go1

350:31identical-if-chain-branchesif-else-if chain repeats a branch body

pkg/dataobj/internal/dataset/row_reader_downloader.go:350:31

349 continue
350 } else if page == requestor {
351 continue // Already added.

clients/pkg/logentry/stages/metrics.go1

200:3identical-switch-branchesswitch repeats a case body

clients/pkg/logentry/stages/metrics.go:200:3

199 vec.DeleteAll()
200 case *metric.Gauges:
201 vec.DeleteAll()

clients/cmd/docker-driver/loki_test.go1

10:2import-alias-namingimport alias should contain lower-case letters and digits

clients/cmd/docker-driver/loki_test.go:10:2

9
10 util_log "github.com/grafana/loki/v3/pkg/util/log"
11)

clients/cmd/docker-driver/config.go1

148:2import-shadowingidentifier url shadows an imported package

clients/cmd/docker-driver/config.go:148:2

147 }
148 url, err := url.Parse(rawURL)
149 if err != nil {

pkg/dataset/open.go1

71:6impossible-integer-comparisoncomparison is always false for type int64

pkg/dataset/open.go:71:6

70 }
71 if posting.Length > int64(math.MaxInt) {
72 errs = append(errs, fmt.Errorf("buffer %d is too large to read: %d bytes", id, posting.Length))

pkg/kafka/partition/reader_service.go1

283:3increment-decrementuse ++ or -- instead of assigning an addition or subtraction of one

pkg/kafka/partition/reader_service.go:283:3

282 // Kafka returns the next empty offset so we must subtract 1 to get the oldest written offset.
283 lastProducedOffset = lastProducedOffset - 1
284

pkg/bloombuild/planner/retention_test.go1

750:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

pkg/bloombuild/planner/retention_test.go:750:4

749 if _, ok := tenants[tenant]; !ok {
750 tenants[tenant] = &validation.Limits{}
751 }

pkg/compactor/client/http.go1

98:18inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.FormatInt with base 10

pkg/compactor/client/http.go:98:18

97 if timeRange != nil {
98 q.Set("start", fmt.Sprintf("%d", timeRange.Start.Unix()))
99 q.Set("end", fmt.Sprintf("%d", timeRange.End.Unix()))

clients/cmd/fluent-bit/config_test.go1

41:35insecure-url-schemeURL uses insecure http scheme

clients/cmd/fluent-bit/config_test.go:41:35

40 clientConfig: util.Config{
41 URL: mustParseURL("http://localhost:3100/loki/api/v1/push"),
42 BatchSize: defaultClientCfg.BatchSize,

pkg/chunkenc/unordered.go1

27:16interface-method-limitinterface has 15 methods, exceeding the configured design limit of 10

pkg/chunkenc/unordered.go:27:16

26
27type HeadBlock interface {
28 IsEmpty() bool

cmd/chunks-inspect/time.go1

33:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

cmd/chunks-inspect/time.go:33:7

32// UnmarshalJSON implements the json.Unmarshaler interface.
33func (t *Time) UnmarshalJSON(b []byte) error {
34 p := strings.Split(string(b), ".")

cmd/migrate/main.go1

329:9max-control-nestingcontrol-flow nesting exceeds 5 levels

cmd/migrate/main.go:329:9

328 onechunk, err = f.FetchChunks(m.ctx, onechunk)
329 if err != nil {
330 if retry == 0 {

pkg/bloombuild/builder/builder.go1

57:6max-parametersfunction has 10 parameters; maximum is 8

pkg/bloombuild/builder/builder.go:57:6

56
57func New(
58 cfg Config,

integration/client/client.go1

546:6max-public-structsfile declares more than 5 exported structs

integration/client/client.go:546:6

545// Response holds the status and data
546type Response struct {
547 Status string

clients/cmd/fluent-bit/config.go1

59:3modifies-parameterassignment modifies parameter labels

clients/cmd/fluent-bit/config.go:59:3

58 if labels == "" {
59 labels = `{job="fluent-bit"}`
60 }

pkg/bloombuild/planner/versioned_range.go1

31:2modifies-value-receiverassignment modifies value receiver t

pkg/bloombuild/planner/versioned_range.go:31:2

30func (t tsdbTokenRange) Swap(i, j int) {
31 t[i], t[j] = t[j], t[i]
32}

clients/cmd/fluent-bit/config_labels_test.go1

14:13nested-structsmove nested anonymous struct types to named declarations

clients/cmd/fluent-bit/config_labels_test.go:14:13

13func Test_externalLabelsFromFluentBitLabelsOption(t *testing.T) {
14 tests := []struct {
15 name string

clients/pkg/logentry/stages/json.go1

128:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

clients/pkg/logentry/stages/json.go:128:4

127 }
128 return nil
129 }

pkg/analytics/seed.go1

33:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/analytics/seed.go:33:3

32 if other == nil {
33 return nil, nil
34 }

pkg/dataobj/internal/dataset/row_reader_test.go1

830:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/dataobj/internal/dataset/row_reader_test.go:830:3

829 next, stop := iter.Pull(columnValues(rng, colCfg))
830 defer stop()
831

operator/internal/manifests/storage/configure.go1

257:5no-else-after-returnremove else and unindent its body after the return

operator/internal/manifests/storage/configure.go:257:5

256 }
257 } else {
258 return []corev1.EnvVar{

clients/pkg/logentry/logql/parser.go1

14:6no-initreplace init with explicit initialization

clients/pkg/logentry/logql/parser.go:14:6

13
14func init() {
15 // Improve the error messages coming out of yacc.

pkg/compactor/deletion/delete_requests_db_boltdb.go1

136:3no-naked-returnreturn values must be explicit

pkg/compactor/deletion/delete_requests_db_boltdb.go:136:3

135 _, err = tx.WriteTo(compressedWriter)
136 return
137 })

clients/cmd/docker-driver/config_test.go1

62:5no-package-varpackage variables introduce mutable global state

clients/cmd/docker-driver/config_test.go:62:5

61
62var pipelineString = `
63- regex:

pkg/ingester/recalculate_owned_streams.go1

134:21non-pointer-sync-pool-valuestore a pointer-like value in sync.Pool to avoid an allocation during Put

pkg/ingester/recalculate_owned_streams.go:134:21

133 s.hostsBufPool.Put(hostsBuf[:0])
134 s.zoneBufPool.Put(zoneBuf[:0])
135 }()

clients/pkg/logentry/stages/eventlogmessage_test.go1

368:4overwritten-before-usethis value of val is overwritten before use

clients/pkg/logentry/stages/eventlogmessage_test.go:368:4

367 if len(resultKey) > 1 {
368 val = strings.TrimSpace(resultKey[1])
369 }

clients/cmd/docker-driver/http.go1

1:9package-commentspackage should have a documentation comment

clients/cmd/docker-driver/http.go:1:9

1package main
2

pkg/dataobj/compaction/planner.go1

1:9package-directory-mismatchpackage planner does not match directory compaction

pkg/dataobj/compaction/planner.go:1:9

1package planner
2

clients/pkg/logentry/logql/parser_test.go1

166:25range-value-addresstaking the address of range value matcher can be misleading

clients/pkg/logentry/logql/parser_test.go:166:25

165 if matcher.Type == labels.MatchNotRegexp || matcher.Type == labels.MatchRegexp {
166 typed.matchers[i] = &labels.Matcher{Type: matcher.Type, Name: matcher.Name, Value: matcher.Value}
167 }

operator/api/loki/v1beta1/recordingrule_types.go1

152:7receiver-namingreceiver name dst is inconsistent with src

operator/api/loki/v1beta1/recordingrule_types.go:152:7

151// ConvertFrom converts from the Hub version (v1) to this version (v1beta1).
152func (dst *RecordingRule) ConvertFrom(srcRaw conversion.Hub) error {
153 src := srcRaw.(*v1.RecordingRule)

pkg/bloombuild/planner/tableIterator.go1

10:2redefines-builtin-ididentifier min shadows a predeclared identifier

pkg/bloombuild/planner/tableIterator.go:10:2

9type dayRangeIterator struct {
10 min, max, cur config.DayTime
11 curPeriod config.PeriodConfig

pkg/logql/syntax/fuzz.go1

2:1redundant-build-taglegacy +build line is redundant with go:build

pkg/logql/syntax/fuzz.go:2:1

1//go:build gofuzz
2// +build gofuzz
3

clients/pkg/logentry/stages/geoip.go1

258:10redundant-conversionconversion from model.LabelName to the identical type is redundant

clients/pkg/logentry/stages/geoip.go:258:10

257 if autonomousSystemNumber != 0 {
258 labels[model.LabelName("geoip_autonomous_system_number")] = model.LabelValue(fmt.Sprint(autonomousSystemNumber))
259 }

operator/api/loki/v1beta1/alertingrule_types_test.go1

6:2redundant-import-aliasimport alias is identical to the package name

operator/api/loki/v1beta1/alertingrule_types_test.go:6:2

5
6 v1 "github.com/grafana/loki/operator/api/loki/v1"
7 "github.com/grafana/loki/operator/api/loki/v1beta1"

operator/internal/status/status.go1

59:3redundant-switch-breakomit unnecessary break at the end of a case clause

operator/internal/status/status.go:59:3

58 // break into retry-logic below on conflict
59 break
60 default:
  • Fix (safe): remove the redundant break

operator/internal/handlers/internal/rules/cleanup_test.go1

167:3single-case-switchswitch with one case can be replaced by an if statement

operator/internal/handlers/internal/rules/cleanup_test.go:167:3

166 k.ListStub = func(_ context.Context, list client.ObjectList, options ...client.ListOption) error {
167 switch list.(type) {
168 case *corev1.ConfigMapList:

pkg/bloomgateway/client.go1

217:8slice-preallocationpreallocate series with capacity len(range source) before appending once per iteration

pkg/bloomgateway/client.go:217:8

216 level.Error(c.logger).Log("msg", "failed to resolve server address for block", "block", blockWithSeries.block, "err", err)
217 var series [][]*logproto.GroupedChunkRefs
218 for i := range blocks {

integration/client/client.go1

202:30standard-http-method-constantreplace the HTTP method literal with http.MethodPost

integration/client/client.go:202:30

201 }
202 req, err := http.NewRequest("POST", apiEndpoint, bytes.NewReader(data))
203 if err != nil {

operator/api/loki/v1/lokistack_types.go1

47:2task-commentFIXME comment should be resolved or linked to an owned work item

operator/api/loki/v1/lokistack_types.go:47:2

46 //
47 // FIXME: Add clear description of ingestion/query performance expectations.
48 SizeOneXPico LokiStackSizeType = "1x.pico"

pkg/logql/rangemapper_test.go1

150:35time-datetime.Date month argument 0 is outside 1..12

pkg/logql/rangemapper_test.go:150:35

149 )`,
150 queryTime: time.Date(0, 0, 0, 12, 54, 0, 0, time.UTC), // 1970 12:54:00
151 splityByInterval: 1 * time.Hour,

pkg/storage/batch.go1

255:8time-value-equalitycompare time.Time values with Time.Equal instead of == or !=

pkg/storage/batch.go:255:8

254 if from.Equal(it.end) {
255 if it.end != it.start {
256 return nil

clients/cmd/docker-driver/logdriver/io.go1

26:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/cmd/docker-driver/logdriver/io.go:26:1

25
26type logEntryEncoder struct {
27 buf []byte

clients/cmd/fluent-bit/out_grafana_loki.go1

109:43unchecked-type-assertionuse the checked two-result form of the type assertion

clients/cmd/fluent-bit/out_grafana_loki.go:109:43

108func FLBPluginFlushCtx(ctx, data unsafe.Pointer, length C.int, _ *C.char) int {
109 plugin := output.FLBPluginGetContext(ctx).(*loki)
110 if plugin == nil {

pkg/canary/reader/reader.go1

341:2unclosed-http-response-bodylocally acquired HTTP response body is not directly closed or transferred before replacement or function exit

pkg/canary/reader/reader.go:341:2

340
341 resp, err := r.httpClient.Do(req)
342 if err != nil {

pkg/logql/log/pattern/lexer.rl.go1

17unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:17

16
17var _pattern_trans_keys []byte = []byte{
18 62, 95, 48, 57, 65, 90, 97, 122,

clients/pkg/logentry/stages/eventlogmessage.go1

69:51unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/eventlogmessage.go:69:51

68
69func (m *eventLogMessageStage) Run(in chan Entry) chan Entry {
70 out := make(chan Entry)

pkg/logql/log/logfmt/decode.go1

140:1unreachable-codestatement is unreachable after unconditional control flow

pkg/logql/log/logfmt/decode.go:140:1

139
140skip_value:
141 for p, c := range line[dec.pos:] {

operator/internal/handlers/internal/gateway/cleanup.go1

21:35unused-parameterparameter log is unused

operator/internal/handlers/internal/gateway/cleanup.go:21:35

20// Cleanup removes external access resources (Routes/Ingress) when external access is disabled.
21func Cleanup(ctx context.Context, log logr.Logger, k k8s.Client, stack *v1.LokiStack) error {
22 if stack.Spec.Tenants == nil || !stack.Spec.Tenants.DisableIngress {

clients/pkg/logentry/logql/ast.go1

28:7unused-receiverreceiver e is unused

clients/pkg/logentry/logql/ast.go:28:7

27
28func (e *matchersExpr) Filter() (Filter, error) {
29 return nil, nil

clients/cmd/docker-driver/config_test.go1

70:14use-anyuse any instead of interface{}

clients/cmd/docker-driver/config_test.go:70:14

69 PipelineStages: []interface{}{
70 map[string]interface{}{
71 "regex": map[string]interface{}{

cmd/chunks-inspect/loki.go1

222:15use-errors-newreplace fmt.Errorf with errors.New for a static message

cmd/chunks-inspect/loki.go:222:15

221 if n <= 0 {
222 return nil, fmt.Errorf("failed to read number of blocks")
223 }

integration/loki_micro_services_delete_test.go1

228:4use-slices-sortuse slices.Sort or slices.SortFunc when possible

integration/loki_micro_services_delete_test.go:228:4

227 for _, stream := range resp.Data.Stream {
228 sort.Slice(stream.Values, func(i, j int) bool {
229 return stream.Values[i][1] < stream.Values[j][1]

cmd/chunks-inspect/loki.go1

42:2var-namingidentifier should use MixedCaps rather than underscores

cmd/chunks-inspect/loki.go:42:2

41 encSnappy = Encoding{code: 4, name: "snappy", readerFn: func(reader io.Reader) (io.Reader, error) { return snappy.NewReader(reader), nil }}
42 enclz4_256k = Encoding{code: 5, name: "lz4-256k", readerFn: func(reader io.Reader) (io.Reader, error) { return lz4.NewReader(reader), nil }}
43 enclz4_1M = Encoding{code: 6, name: "lz4-1M", readerFn: func(reader io.Reader) (io.Reader, error) { return lz4.NewReader(reader), nil }}

pkg/engine/internal/scheduler/wire/wire_http2_test.go1

318:4waitgroup-add-inside-goroutinecall WaitGroup.Add before starting the goroutine to avoid racing with Wait

pkg/engine/internal/scheduler/wire/wire_http2_test.go:318:4

317 var peerWg sync.WaitGroup
318 peerWg.Add(1)
319 go func() {

clients/cmd/docker-driver/driver.go1

164:71add-constantstring literal "id" appears more than twice; define a constant

clients/cmd/docker-driver/driver.go:164:71

163 if err := lf.lokil.Log(&msg); err != nil {
164 level.Error(lf.logger).Log("msg", "error pushing message to loki", "id", lf.info.ContainerID, "err", err, "message", msg)
165 }

pkg/querier/queryrange/detected_fields_test.go1

122:4call-to-gcavoid explicit garbage collection

pkg/querier/queryrange/detected_fields_test.go:122:4

121 t.Run("detects fields with huge limit doesn't explode memory", func(t *testing.T) {
122 runtime.GC()
123 var before runtime.MemStats

clients/cmd/fluent-bit/config.go1

72:6cognitive-complexityfunction has cognitive complexity 45; maximum is 7

clients/cmd/fluent-bit/config.go:72:6

71
72func parseConfig(cfg ConfigGetter) (*config, error) {
73 res := &config{}

clients/pkg/util/api.go1

55:23confusing-namingname Stop differs from stop only by capitalization

clients/pkg/util/api.go:55:23

54
55func (e entryHandler) Stop() {
56 e.stop()

operator/internal/manifests/internal/config/build_test.go1

21:59confusing-resultsadjacent unnamed results of the same type should be named

operator/internal/manifests/internal/config/build_test.go:21:59

20
21func loadTestData(t *testing.T, testcase string) (string, string) {
22 t.Helper()

clients/pkg/logentry/stages/extensions.go1

143:6constructor-interface-returnNewCRI returns interface Stage although its concrete result is consistently *cri; return the concrete type

clients/pkg/logentry/stages/extensions.go:143:6

142// NewCRI creates a CRI format specific pipeline stage
143func NewCRI(logger log.Logger, config interface{}, registerer prometheus.Registerer) (Stage, error) {
144 base := PipelineStages{

production/helm/loki/src/helm-test/canary_test.go1

112:41context-as-argumentcontext.Context should be the first parameter

production/helm/loki/src/helm-test/canary_test.go:112:41

111
112func testResultCanary(t *testing.T, ctx context.Context, metric string, test func(model.SampleValue) bool, msg string) error {
113 address := os.Getenv("CANARY_SERVICE_ADDRESS")

pkg/engine/internal/worker/scheduler_lookup.go1

90:40context-cancel-in-loopcontext.WithCancel is created in a loop without retaining and calling its cancellation function during the iteration

pkg/engine/internal/worker/scheduler_lookup.go:90:40

89 var handler handlerContext
90 handler.Context, handler.Cancel = context.WithCancel(ctx)
91 handlers[update.Addr] = handler

pkg/bloombuild/builder/batch.go1

190:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

pkg/bloombuild/builder/batch.go:190:2

189 // constructor arguments
190 ctx context.Context
191 fetcher Fetcher[bloomshipper.BlockRef, *bloomshipper.CloseableBlockQuerier]

clients/cmd/fluent-bit/config.go1

72:6cyclomatic-complexityfunction complexity is 41; maximum is 10

clients/cmd/fluent-bit/config.go:72:6

71
72func parseConfig(cfg ConfigGetter) (*config, error) {
73 res := &config{}

cmd/migrate/main.go1

405:3deep-exitprocess-exit calls should be confined to main or init

cmd/migrate/main.go:405:3

404 if err != nil {
405 log.Fatalf("Unable to parse time %v", err)
406 }

pkg/compactor/jobqueue/queue_test.go1

75:15deprecated-api-usagegoogle.golang.org/grpc.DialContext is deprecated: use NewClient instead. Will be supported throughout 1.x.

pkg/compactor/jobqueue/queue_test.go:75:15

74 // nolint:staticcheck // compactor_grpc.DialContext() has been deprecated; we'll address it before upgrading to gRPC 2.
75 conn, err := grpc.DialContext(context.Background(), "",
76 grpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {

clients/cmd/docker-driver/driver.go1

76:2discarded-error-resulterror result returned by level.Info(d.logger).Log is discarded

clients/cmd/docker-driver/driver.go:76:2

75 logCtx.LogPath = filepath.Join(folder, "json.log")
76 level.Info(d.logger).Log("msg", "starting logging driver for container", "id", logCtx.ContainerID, "config", fmt.Sprintf("%+v", logCtx.Config), "file", file, "logpath", logCtx.LogPath)
77

clients/cmd/docker-driver/loki.go1

95:1doc-comment-perioddocumentation comment should end with punctuation

clients/cmd/docker-driver/loki.go:95:1

94
95// Log implements `logger.Logger`
96func (l *loki) Close() error {

pkg/compactor/deletion/delete_requests_store_test.go1

551:23duration-multiplied-by-durationmultiplying two time.Duration values produces squared time units; multiply a duration by a unitless count

pkg/compactor/deletion/delete_requests_store_test.go:551:23

550 StartTime: now.Add(-i * time.Hour),
551 EndTime: now.Add(-(i + 1) * time.Hour),
552 Query: fmt.Sprintf(`{foo="%d", user="%s"}`, i, user2),

clients/pkg/logentry/stages/match.go1

123:3early-returninvert the condition and return early to reduce nesting

clients/pkg/logentry/stages/match.go:123:3

122 if err != nil {
123 if existing, ok := err.(prometheus.AlreadyRegisteredError); ok {
124 dropCount = existing.ExistingCollector.(*prometheus.CounterVec)

pkg/storage/chunk/client/congestion/retry.go1

12:5error-namingpackage error variable should be named errFoo or ErrFoo

pkg/storage/chunk/client/congestion/retry.go:12:5

11
12var RetriesExceeded = errors.New("retries exceeded")
13

clients/pkg/logentry/stages/regex_test.go1

212:14error-stringserror string should not be capitalized or end with punctuation

clients/pkg/logentry/stages/regex_test.go:212:14

211 if (err != nil) != (tt.err != nil) {
212 t.Errorf("RegexConfig.validate() expected error = %v, actual error = %v", tt.err, err)
213 return

pkg/querier/worker/util_test.go1

31:6error-type-namingerror implementation type should have an Error suffix

pkg/querier/worker/util_test.go:31:6

30// error so errors.Is keeps working.
31type grpcStatusErr struct {
32 code codes.Code

pkg/ingester/limiter_test.go1

498:3excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

pkg/ingester/limiter_test.go:498:3

497 // Expected: 200 (the higher of the two)
498 calculated, _, _, _ := streamCountLimiter.getCurrentLimit("tenant1", noPolicy, fixedLimitSupplier)
499 require.Equal(t, 200, calculated, "Without policy, should use the higher of calculated and fixed limits")

clients/cmd/docker-driver/http.go1

23:6exported-declaration-commentexported type should have a comment beginning with its name

clients/cmd/docker-driver/http.go:23:6

22
23type CapabilitiesResponse struct {
24 Err string

cmd/logcli/main.go1

1:1file-length-limitfile has 897 lines; maximum is 500

cmd/logcli/main.go:1:1

1package main
2

cmd/chunks-inspect/main.go1

28:59flag-parameterboolean parameter storeBlocks controls function flow

cmd/chunks-inspect/main.go:28:59

27
28func printFile(filename string, blockDetails, printLines, storeBlocks bool) {
29 f, err := os.Open(filename)

clients/cmd/docker-driver/http.go1

1:1formatfile is not formatted

clients/cmd/docker-driver/http.go:1:1

1package main
2
  • Fix (safe): run `strider fmt clients/cmd/docker-driver/http.go`

clients/cmd/fluent-bit/config_test.go1

26:6function-lengthfunction has 5 statements and 133 lines; maximum is 50 statements or 75 lines

clients/cmd/fluent-bit/config_test.go:26:6

25
26func Test_parseConfig(t *testing.T) {
27 fileName := createTempLabelMap(t)

operator/internal/manifests/gateway.go1

543:6function-result-limitfunction returns 4 values; maximum is 3

operator/internal/manifests/gateway.go:543:6

542// gatewayConfigObjs creates a configMap for rbac.yaml and a secret for tenants.yaml
543func gatewayConfigObjs(opt Options) (*corev1.ConfigMap, *corev1.Secret, string, error) {
544 cfg := gatewayConfigOptions(opt)

pkg/logcli/index/volume.go1

14:6get-function-return-valueGet-prefixed function should return a value

pkg/logcli/index/volume.go:14:6

13// GetVolume executes a volume query and prints the results
14func GetVolume(q *volume.Query, c client.Client, out output.LogOutput, statistics bool) {
15 do(q, false, c, out, statistics)

pkg/dataobj/internal/dataset/value_encoding_bitmap_test.go1

168:49identical-if-chain-branchesif-else-if chain repeats a branch body

pkg/dataobj/internal/dataset/value_encoding_bitmap_test.go:168:49

167 t.Skip()
168 } else if distinct < 1 || distinct*10 > count {
169 // at most 10% of the values can be true

clients/pkg/logentry/stages/metrics.go1

202:3identical-switch-branchesswitch repeats a case body

clients/pkg/logentry/stages/metrics.go:202:3

201 vec.DeleteAll()
202 case *metric.Histograms:
203 vec.DeleteAll()

clients/cmd/docker-driver/main.go1

16:2import-alias-namingimport alias should contain lower-case letters and digits

clients/cmd/docker-driver/main.go:16:2

15 _ "github.com/grafana/loki/v3/pkg/util/build"
16 util_log "github.com/grafana/loki/v3/pkg/util/log"
17)

clients/cmd/docker-driver/driver.go1

29:2import-shadowingidentifier logger shadows an imported package

clients/cmd/docker-driver/driver.go:29:2

28 idx map[string]*logPair
29 logger log.Logger
30}

pkg/storage/stores/shipper/indexshipper/tsdb/index/index.go1

965:5impossible-integer-comparisoncomparison is always false for type uint32

pkg/storage/stores/shipper/indexshipper/tsdb/index/index.go:965:5

964 // Had to uint32 wrap these for arm32 builds, which we'll remove in the future.
965 if uint32(ln) > uint32(math.MaxUint32) {
966 return errors.Errorf("fingerprint offset size exceeds 4 bytes: %d", ln)

pkg/logql/sketch/topk_test.go1

156:3increment-decrementuse ++ or -- instead of assigning an addition or subtraction of one

pkg/logql/sketch/topk_test.go:156:3

155 }
156 m[s] = m[s] + 1
157 if _, ok := h.Find(s); ok {

pkg/compactor/deletion/deletion_manifest_builder.go1

171:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

pkg/compactor/deletion/deletion_manifest_builder.go:171:4

170
171 d.currentSegment[chunksGroupIdentifier] = deletionproto.ChunksGroup{
172 Requests: deleteRequests,

pkg/compactor/client/http.go1

99:16inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.FormatInt with base 10

pkg/compactor/client/http.go:99:16

98 q.Set("start", fmt.Sprintf("%d", timeRange.Start.Unix()))
99 q.Set("end", fmt.Sprintf("%d", timeRange.End.Unix()))
100 }

clients/cmd/fluent-bit/config_test.go1

54:22insecure-url-schemeURL uses insecure http scheme

clients/cmd/fluent-bit/config_test.go:54:22

53 map[string]string{
54 "URL": "http://somewhere.com:3100/loki/api/v1/push",
55 "TenantID": "my-tenant-id",

pkg/compactor/deletion/delete_requests_store.go1

32:26interface-method-limitinterface has 12 methods, exceeding the configured design limit of 10

pkg/compactor/deletion/delete_requests_store.go:32:26

31
32type DeleteRequestsStore interface {
33 AddDeleteRequest(ctx context.Context, userID, query string, startTime, endTime model.Time, shardByInterval time.Duration) (string, error)

pkg/chunkenc/facade.go1

60:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

pkg/chunkenc/facade.go:60:7

59// UnmarshalFromBuf implements chunk.Chunk.
60func (f *Facade) UnmarshalFromBuf(buf []byte) error {
61 var err error

cmd/migrate/main.go1

330:10max-control-nestingcontrol-flow nesting exceeds 5 levels

cmd/migrate/main.go:330:10

329 if err != nil {
330 if retry == 0 {
331 log.Println(threadID, "Final error retrieving chunks, giving up:", err)

pkg/bloombuild/builder/spec.go1

44:6max-parametersfunction has 9 parameters; maximum is 8

pkg/bloombuild/builder/spec.go:44:6

43// Blocks which are incompatible with the schema are skipped and will have their chunks reindexed
44func NewSimpleBloomGenerator(
45 userID string,

integration/client/client.go1

551:6max-public-structsfile declares more than 5 exported structs

integration/client/client.go:551:6

550
551type RulesResponse struct {
552 Status string

clients/cmd/fluent-bit/loki.go1

144:5modifies-parameterassignment modifies parameter kuberneteslbs

clients/cmd/fluent-bit/loki.go:144:5

143 for m, n := range v.(map[string]interface{}) {
144 kuberneteslbs[model.LabelName(keyReplacer.Replace(m))] = model.LabelValue(fmt.Sprintf("%v", n))
145 }

pkg/bloombuild/planner/versioned_range.go1

31:8modifies-value-receiverassignment modifies value receiver t

pkg/bloombuild/planner/versioned_range.go:31:8

30func (t tsdbTokenRange) Swap(i, j int) {
31 t[i], t[j] = t[j], t[i]
32}

clients/cmd/fluent-bit/config_test.go1

30:13nested-structsmove nested anonymous struct types to named declarations

clients/cmd/fluent-bit/config_test.go:30:13

29
30 tests := []struct {
31 name string

clients/pkg/logentry/stages/metrics.go1

367:3nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

clients/pkg/logentry/stages/metrics.go:367:3

366 }
367 return dur.Seconds(), nil
368 }

pkg/analytics/seed.go1

37:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/analytics/seed.go:37:3

36 if c.CreatedAt.Before(other.CreatedAt) {
37 return nil, nil
38 }

pkg/logcli/query/query.go1

315:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/logcli/query/query.go:315:3

314 }
315 defer f.Close()
316

pkg/canary/reader/reader.go1

503:6no-else-after-returnremove else and unindent its body after the return

pkg/canary/reader/reader.go:503:6

502 return nil
503 } else if _, ok := err.(net.Error); ok {
504 return nil

clients/pkg/logentry/stages/regex_test.go1

55:6no-initreplace init with explicit initialization

clients/pkg/logentry/stages/regex_test.go:55:6

54
55func init() {
56 Debug = true

pkg/compactor/retention/util_test.go1

264:2no-naked-returnreturn values must be explicit

pkg/compactor/retention/util_test.go:264:2

263 }
264 return
265}

clients/cmd/docker-driver/config_test.go1

68:5no-package-varpackage variables introduce mutable global state

clients/cmd/docker-driver/config_test.go:68:5

67`
68var pipeline = PipelineConfig{
69 PipelineStages: []interface{}{

pkg/logproto/timeseries.go1

79:16non-pointer-sync-pool-valuestore a pointer-like value in sync.Pool to avoid an allocation during Put

pkg/logproto/timeseries.go:79:16

78
79 slicePool.Put(ts[:0]) //nolint:staticcheck //see comment on slicePool for more details
80}

clients/pkg/logentry/stages/eventlogmessage_test.go1

372:4overwritten-before-usethis value of val is overwritten before use

clients/pkg/logentry/stages/eventlogmessage_test.go:372:4

371 if len(resultKey) > 1 {
372 val = strings.TrimSpace(resultKeyValue[1])
373 }

clients/cmd/docker-driver/logdriver/io.go1

1:9package-commentspackage should have a documentation comment

clients/cmd/docker-driver/logdriver/io.go:1:9

1package logdriver
2

pkg/dataobj/compaction/planner_test.go1

1:9package-directory-mismatchpackage planner does not match directory compaction

pkg/dataobj/compaction/planner_test.go:1:9

1package planner
2

clients/pkg/logentry/metric/counters_test.go1

83:33range-value-addresstaking the address of range value tt can be misleading

clients/pkg/logentry/metric/counters_test.go:83:33

82 t.Parallel()
83 err := validateCounterConfig(&tt.config)
84 if ((err != nil) && (err.Error() != tt.err.Error())) || (err == nil && tt.err != nil) {

operator/api/loki/v1beta1/rulerconfig_types.go1

779:7receiver-namingreceiver name dst is inconsistent with src

operator/api/loki/v1beta1/rulerconfig_types.go:779:7

778// ConvertFrom converts from the Hub version (v1) to this version (v1beta1).
779func (dst *RulerConfig) ConvertFrom(srcRaw conversion.Hub) error {
780 src := srcRaw.(*v1.RulerConfig)

pkg/bloombuild/planner/tableIterator.go1

10:7redefines-builtin-ididentifier max shadows a predeclared identifier

pkg/bloombuild/planner/tableIterator.go:10:7

9type dayRangeIterator struct {
10 min, max, cur config.DayTime
11 curPeriod config.PeriodConfig

pkg/logql/syntax/fuzz_test.go1

2:1redundant-build-taglegacy +build line is redundant with go:build

pkg/logql/syntax/fuzz_test.go:2:1

1//go:build gofuzz
2// +build gofuzz
3

clients/pkg/logentry/stages/geoip.go1

261:10redundant-conversionconversion from model.LabelName to the identical type is redundant

clients/pkg/logentry/stages/geoip.go:261:10

260 if autonomousSystemOrganization != "" {
261 labels[model.LabelName("geoip_autonomous_system_organization")] = model.LabelValue(autonomousSystemOrganization)
262 }

operator/api/loki/v1beta1/lokistack_types.go1

4:2redundant-import-aliasimport alias is identical to the package name

operator/api/loki/v1beta1/lokistack_types.go:4:2

3import (
4 v1 "github.com/grafana/loki/operator/api/loki/v1"
5 corev1 "k8s.io/api/core/v1"

pkg/logql/syntax/query_scanner.go1

691:4redundant-switch-breakomit unnecessary break at the end of a case clause

pkg/logql/syntax/query_scanner.go:691:4

690 case EOF:
691 break
692 case '"':
  • Fix (safe): remove the redundant break

operator/internal/handlers/internal/rules/rules_test.go1

362:3single-case-switchswitch with one case can be replaced by an if statement

operator/internal/handlers/internal/rules/rules_test.go:362:3

361 k.ListStub = func(_ context.Context, ol client.ObjectList, opt ...client.ListOption) error {
362 switch ol.(type) {
363 case *lokiv1.RecordingRuleList:

pkg/bloomgateway/querier.go1

146:6slice-preallocationpreallocate skippedGrps with capacity len(range source) before appending once per iteration

pkg/bloomgateway/querier.go:146:6

145
146 var skippedGrps [][]*logproto.GroupedChunkRefs
147 responses := make([][]*logproto.GroupedChunkRefs, 0, 2)

integration/client/client.go1

230:30standard-http-method-constantreplace the HTTP method literal with http.MethodGet

integration/client/client.go:230:30

229 url := fmt.Sprintf("%s%s", c.baseURL, path)
230 req, err := http.NewRequest("GET", url, nil)
231 if err != nil {

operator/api/loki/v1/lokistack_types.go1

55:2task-commentFIXME comment should be resolved or linked to an owned work item

operator/api/loki/v1/lokistack_types.go:55:2

54 //
55 // FIXME: Add clear description of ingestion/query performance expectations.
56 SizeOneXExtraSmall LokiStackSizeType = "1x.extra-small"

pkg/logql/rangemapper_test.go1

150:38time-datetime.Date day argument 0 is outside 1..31

pkg/logql/rangemapper_test.go:150:38

149 )`,
150 queryTime: time.Date(0, 0, 0, 12, 54, 0, 0, time.UTC), // 1970 12:54:00
151 splityByInterval: 1 * time.Hour,

pkg/storage/chunk/cache/resultscache/cache.go1

370:7time-value-equalitycompare time.Time values with Time.Equal instead of == or !=

pkg/storage/chunk/cache/resultscache/cache.go:370:7

369 // This means the extent's start and end time would be same, even if the timerange covers several hours.
370 if (req.GetStart() != req.GetEnd()) && ((end - start) > s.minCacheExtent) && (extent.End-extent.Start < s.minCacheExtent) {
371 continue

clients/cmd/fluent-bit/buffer.go1

17:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/cmd/fluent-bit/buffer.go:17:1

16
17var defaultBufferConfig = bufferConfig{
18 buffer: false,

clients/cmd/fluent-bit/out_grafana_loki.go1

131:18unchecked-type-assertionuse the checked two-result form of the type assertion

clients/cmd/fluent-bit/out_grafana_loki.go:131:18

130 case output.FLBTime:
131 timestamp = ts.(output.FLBTime).Time
132 case uint64:

pkg/compactor/client/http.go1

112:2unclosed-http-response-bodylocally acquired HTTP response body is not directly closed or transferred before replacement or function exit

pkg/compactor/client/http.go:112:2

111
112 resp, err := c.httpClient.Do(req)
113 if err != nil {

pkg/logql/log/pattern/lexer.rl.go1

26unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:26

25
26var _pattern_single_lengths []byte = []byte{
27 0, 2, 0, 0, 0, 0, 0, 0,

clients/pkg/logentry/stages/extensions.go1

66:37unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/extensions.go:66:37

65// implements Stage interface
66func (c *cri) Run(entry chan Entry) chan Entry {
67 entry = c.base.Run(entry)

pkg/logql/log/logfmt/decode.go1

151:1unreachable-codestatement is unreachable after unconditional control flow

pkg/logql/log/logfmt/decode.go:151:1

150
151qvalue:
152 const (

pkg/columnar/columnartest/equality.go1

96:43unused-parameterparameter left is unused

pkg/columnar/columnartest/equality.go:96:43

95
96func requireNullArraysEqual(t testing.TB, left, right *columnar.Null, mask memory.Bitmap) {
97 // Nothing to do here; the base checks in RequireArraysEqual covers

clients/pkg/logentry/metric/metricvec.go1

34:7unused-receiverreceiver c is unused

clients/pkg/logentry/metric/metricvec.go:34:7

33// see https://godoc.org/github.com/prometheus/client_golang/prometheus#hdr-Custom_Collectors_and_constant_Metrics search for "unchecked"
34func (c *metricVec) Describe(_ chan<- *prometheus.Desc) {}
35

clients/cmd/docker-driver/config_test.go1

71:24use-anyuse any instead of interface{}

clients/cmd/docker-driver/config_test.go:71:24

70 map[string]interface{}{
71 "regex": map[string]interface{}{
72 "expression": "(level|lvl|severity)=(?P<level>\\w+)",

integration/parse_metrics.go1

15:25use-errors-newreplace fmt.Errorf with errors.New for a static message

integration/parse_metrics.go:15:25

14var (
15 ErrNoMetricFound = fmt.Errorf("metric not found")
16 ErrInvalidMetricType = fmt.Errorf("invalid metric type")

integration/loki_micro_services_delete_test.go1

433:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

integration/loki_micro_services_delete_test.go:433:2

432
433 sort.Slice(svs, func(i, j int) bool {
434 return labels.FromMap(svs[i].Stream).String() < labels.FromMap(svs[j].Stream).String()

cmd/chunks-inspect/loki.go1

43:2var-namingidentifier should use MixedCaps rather than underscores

cmd/chunks-inspect/loki.go:43:2

42 enclz4_256k = Encoding{code: 5, name: "lz4-256k", readerFn: func(reader io.Reader) (io.Reader, error) { return lz4.NewReader(reader), nil }}
43 enclz4_1M = Encoding{code: 6, name: "lz4-1M", readerFn: func(reader io.Reader) (io.Reader, error) { return lz4.NewReader(reader), nil }}
44 enclz4_4M = Encoding{code: 7, name: "lz4-4M", readerFn: func(reader io.Reader) (io.Reader, error) { return lz4.NewReader(reader), nil }}

clients/cmd/fluent-bit/config_labels_test.go1

35:54add-constantstring literal "job" appears more than twice; define a constant

clients/cmd/fluent-bit/config_labels_test.go:35:54

34 labels: `{job="fluent-bit",env="prod"}`,
35 want: flagext.LabelSet{LabelSet: model.LabelSet{"job": "fluent-bit", "env": "prod"}},
36 },

pkg/querier/queryrange/detected_fields_test.go1

129:4call-to-gcavoid explicit garbage collection

pkg/querier/queryrange/detected_fields_test.go:129:4

128
129 runtime.GC()
130 var after runtime.MemStats

clients/cmd/fluent-bit/config_test.go1

160:6cognitive-complexityfunction has cognitive complexity 14; maximum is 7

clients/cmd/fluent-bit/config_test.go:160:6

159
160func assertConfig(t *testing.T, expected, actual *config) {
161 if expected.clientConfig.BatchSize != actual.clientConfig.BatchSize {

integration/client/client.go1

124:18confusing-namingname pushLogLine differs from PushLogLine only by capitalization

integration/client/client.go:124:18

123// pushLogLine creates a new logline
124func (c *Client) pushLogLine(line string, timestamp time.Time, structuredMetadata labels.Labels, extraLabelList ...map[string]string) error {
125 apiEndpoint := fmt.Sprintf("%s/loki/api/v1/push", c.baseURL)

pkg/bloombuild/planner/versioned_range.go1

213:69confusing-resultsadjacent unnamed results of the same type should be named

pkg/bloombuild/planner/versioned_range.go:213:69

212
213func outdatedMetas(metas []bloomshipper.Meta) ([]bloomshipper.Meta, []bloomshipper.Meta) {
214 var outdated []bloomshipper.Meta

clients/pkg/util/api.go1

60:6constructor-interface-returnNewEntryHandler returns interface EntryHandler although its concrete result is consistently entryHandler; return the concrete type

clients/pkg/util/api.go:60:6

59// NewEntryHandler creates a new EntryHandler using a input channel and a stop function.
60func NewEntryHandler(entries chan<- Entry, stop func()) EntryHandler {
61 return entryHandler{

pkg/logql/bench/bench_test.go1

499:7context-cancel-in-loopcancellation deferred inside a loop runs only when the surrounding function returns; cancel before the iteration ends

pkg/logql/bench/bench_test.go:499:7

498 ctx, cancel := context.WithTimeout(ctx, time.Minute)
499 defer cancel()
500

pkg/bloombuild/builder/batch_test.go1

31:3context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

pkg/bloombuild/builder/batch_test.go:31:3

30 desc string
31 ctx context.Context
32 batchSize int

clients/cmd/fluent-bit/config_test.go1

160:6cyclomatic-complexityfunction complexity is 15; maximum is 10

clients/cmd/fluent-bit/config_test.go:160:6

159
160func assertConfig(t *testing.T, expected, actual *config) {
161 if expected.clientConfig.BatchSize != actual.clientConfig.BatchSize {

cmd/querytee/main.go1

86:2deep-exitprocess-exit calls should be confined to main or init

cmd/querytee/main.go:86:2

85 util_log.Flush()
86 os.Exit(code)
87}

pkg/indexgateway/client_pool.go1

27:15deprecated-api-usagegoogle.golang.org/grpc.Dial is deprecated: use NewClient instead. Will be supported throughout 1.x.

pkg/indexgateway/client_pool.go:27:15

26 // nolint:staticcheck // grpc.Dial() has been deprecated; we'll address it before upgrading to gRPC 2.
27 conn, err := grpc.Dial(address, opts...)
28 if err != nil {

clients/cmd/docker-driver/driver.go1

120:2discarded-error-resulterror result returned by level.Debug(d.logger).Log is discarded

clients/cmd/docker-driver/driver.go:120:2

119func (d *driver) StopLogging(file string) {
120 level.Debug(d.logger).Log("msg", "Stop logging", "file", file)
121 d.mu.Lock()

clients/cmd/fluent-bit/dque.go1

120:1doc-comment-perioddocumentation comment should end with punctuation

clients/cmd/fluent-bit/dque.go:120:1

119
120// Stop the client
121func (c *dqueClient) Stop() {

clients/pkg/logentry/stages/pack.go1

42:4early-returninvert the condition and return early to reduce nesting

clients/pkg/logentry/stages/pack.go:42:4

41 if k == logqlmodel.PackedEntryKey {
42 if s, ok := v.(string); ok {
43 w.Entry = s

clients/pkg/logentry/stages/regex_test.go1

216:14error-stringserror string should not be capitalized or end with punctuation

clients/pkg/logentry/stages/regex_test.go:216:14

215 if (err != nil) && (err.Error() != tt.err.Error()) {
216 t.Errorf("RegexConfig.validate() expected error = %v, actual error = %v", tt.err, err)
217 return

pkg/ruler/storage/instance/errors.go1

12:6error-type-namingerror implementation type should have an Error suffix

pkg/ruler/storage/instance/errors.go:12:6

11// with the new config.
12type ErrInvalidUpdate struct {
13 Inner error

pkg/ingester/limiter_test.go1

505:3excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

pkg/ingester/limiter_test.go:505:3

504 // Expected: 100 (policy limit takes precedence)
505 calculated, _, _, _ = streamCountLimiter.getCurrentLimit("tenant1", "finance", fixedLimitSupplier)
506 require.Equal(t, 100, calculated, "With policy, policy limit should take precedence over fixed limit")

clients/cmd/docker-driver/http.go1

28:6exported-declaration-commentexported type should have a comment beginning with its name

clients/cmd/docker-driver/http.go:28:6

27
28type ReadLogsRequest struct {
29 Info logger.Info

integration/client/client.go1

1:1file-length-limitfile has 870 lines; maximum is 500

integration/client/client.go:1:1

1package client
2

cmd/logcli/main.go1

656:15flag-parameterboolean parameter instant controls function flow

cmd/logcli/main.go:656:15

655
656func newQuery(instant bool, cmd *kingpin.CmdClause) *query.Query {
657 // calculate query range from cli params

clients/cmd/docker-driver/loki.go1

1:1formatfile is not formatted

clients/cmd/docker-driver/loki.go:1:1

1package main
2
  • Fix (safe): run `strider fmt clients/cmd/docker-driver/loki.go`

clients/cmd/fluent-bit/loki_test.go1

21:6function-lengthfunction has 8 statements and 87 lines; maximum is 50 statements or 75 lines

clients/cmd/fluent-bit/loki_test.go:21:6

20
21func Test_loki_sendRecord(t *testing.T) {
22 simpleRecordFixture := map[interface{}]interface{}{

operator/internal/manifests/internal/gateway/build.go1

45:6function-result-limitfunction returns 4 values; maximum is 3

operator/internal/manifests/internal/gateway/build.go:45:6

44// Build builds a loki gateway configuration files
45func Build(opts Options) (rbacCfg []byte, tenantsCfg []byte, regoCfg []byte, err error) {
46 // Build loki gateway rbac yaml

pkg/logcli/index/volume.go1

20:6get-function-return-valueGet-prefixed function should return a value

pkg/logcli/index/volume.go:20:6

19// be a collection of data points over time.
20func GetVolumeRange(q *volume.Query, c client.Client, out output.LogOutput, statistics bool) {
21 do(q, true, c, out, statistics)

pkg/logql/bench/metadata_resolver.go1

152:46identical-if-chain-branchesif-else-if chain repeats a branch body

pkg/logql/bench/metadata_resolver.go:152:46

151 rangeFiltered = append(rangeFiltered, sel)
152 } else if !isInstant && meta.MinRange > 0 {
153 rangeFiltered = append(rangeFiltered, sel)

clients/pkg/logentry/stages/metrics.go1

329:2identical-switch-branchesswitch repeats a case body

clients/pkg/logentry/stages/metrics.go:329:2

328 return float64(i), nil
329 case int64:
330 return float64(i), nil

clients/cmd/fluent-bit/config.go1

11:2import-alias-namingimport alias should contain lower-case letters and digits

clients/cmd/fluent-bit/config.go:11:2

10
11 dskit_flagext "github.com/grafana/dskit/flagext"
12 "github.com/grafana/dskit/log"

clients/cmd/docker-driver/driver.go1

37:2import-shadowingidentifier logger shadows an imported package

clients/cmd/docker-driver/driver.go:37:2

36 info logger.Info
37 logger log.Logger
38 // folder where json log files will be created.

pkg/storage/stores/shipper/indexshipper/tsdb/index/index.go1

1150:6impossible-integer-comparisoncomparison is always false for type uint32

pkg/storage/stores/shipper/indexshipper/tsdb/index/index.go:1150:6

1149 for _, off := range offs {
1150 if off > (1<<32)-1 {
1151 return errors.Errorf("series offset %d exceeds 4 bytes", off)

pkg/logql/sketch/topk_test.go1

237:3increment-decrementuse ++ or -- instead of assigning an addition or subtraction of one

pkg/logql/sketch/topk_test.go:237:3

236 }
237 m[s] = m[s] + 1
238 if _, ok := h.Find(s); ok {

pkg/compactor/deletion/job_builder_test.go1

27:3inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

pkg/compactor/deletion/job_builder_test.go:27:3

26 if _, ok := t.updates[tableName]; !ok {
27 t.updates[tableName] = map[string]map[string]deletionproto.StorageUpdates{
28 userID: {

pkg/compactor/compactor_test.go1

161:10inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.FormatInt with base 10

pkg/compactor/compactor_test.go:161:10

160 indexFromTime := func(t time.Time) string {
161 return fmt.Sprintf("%d", t.Unix()/int64(24*time.Hour/time.Second))
162 }

clients/cmd/fluent-bit/config_test.go1

72:35insecure-url-schemeURL uses insecure http scheme

clients/cmd/fluent-bit/config_test.go:72:35

71 clientConfig: util.Config{
72 URL: mustParseURL("http://somewhere.com:3100/loki/api/v1/push"),
73 TenantID: "my-tenant-id",

pkg/distributor/limits.go1

13:13interface-method-limitinterface has 41 methods, exceeding the configured design limit of 10

pkg/distributor/limits.go:13:13

12// Limits is an interface for distributor limits/related configs
13type Limits interface {
14 retention.Limits

pkg/dataobj/internal/dataset/value.go1

211:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

pkg/dataobj/internal/dataset/value.go:211:7

210// [Value.MarshalBinary] for the encoding format.
211func (v *Value) UnmarshalBinary(data []byte) error {
212 if len(data) == 0 {

cmd/migrate/main.go1

341:8max-control-nestingcontrol-flow nesting exceeds 5 levels

cmd/migrate/main.go:341:8

340
341 if retry < 0 {
342 continue

pkg/canary/comparator/comparator.go1

148:6max-parametersfunction has 19 parameters; maximum is 8

pkg/canary/comparator/comparator.go:148:6

147
148func NewComparator(writer io.Writer,
149 wait time.Duration,

integration/client/client.go1

556:6max-public-structsfile declares more than 5 exported structs

integration/client/client.go:556:6

555
556type RulesData struct {
557 Groups []Rules

clients/cmd/fluent-bit/loki.go1

150:4modifies-parameterassignment modifies parameter kuberneteslbs

clients/cmd/fluent-bit/loki.go:150:4

149 default:
150 kuberneteslbs[model.LabelName(k)] = model.LabelValue(fmt.Sprintf("%v", v))
151 }

pkg/bloombuild/planner/versioned_range.go1

119:4modifies-value-receiverassignment modifies value receiver t

pkg/bloombuild/planner/versioned_range.go:119:4

118 if bounds.Equal(preExisting) {
119 t[i].version = version
120 return t, true

clients/cmd/fluent-bit/loki_test.go1

25:22nested-structsmove nested anonymous struct types to named declarations

clients/cmd/fluent-bit/loki_test.go:25:22

24 "bar": 500,
25 "error": make(chan struct{}),
26 }

integration/cluster/cluster.go1

153:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

integration/cluster/cluster.go:153:4

152 if errors.As(err, &aErr) {
153 return nil
154 }

pkg/analytics/seed.go1

46:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/analytics/seed.go:46:3

45 }
46 return nil, nil
47 }

pkg/logql/bench/bench_test.go1

499:7no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/logql/bench/bench_test.go:499:7

498 ctx, cancel := context.WithTimeout(ctx, time.Minute)
499 defer cancel()
500

pkg/chunkenc/memchunk_test.go1

2423:6no-else-after-returnremove else and unindent its body after the return

pkg/chunkenc/memchunk_test.go:2423:6

2422 return -1
2423 } else if a.Timestamp.After(b.Timestamp) {
2424 return 1

clients/pkg/logentry/stages/template.go1

59:6no-initreplace init with explicit initialization

clients/pkg/logentry/stages/template.go:59:6

58
59func init() {
60 for k, v := range extraFunctionMap {

pkg/compactor/retention/util_test.go1

417:3no-naked-returnreturn values must be explicit

pkg/compactor/retention/util_test.go:417:3

416 m.End = m.Start + millisecondsInDay - 1
417 return
418 }

clients/cmd/docker-driver/loki.go1

19:5no-package-varpackage variables introduce mutable global state

clients/cmd/docker-driver/loki.go:19:5

18
19var jobName = "docker"
20

pkg/ruler/storage/wal/wal.go1

571:18non-pointer-sync-pool-valuestore a pointer-like value in sync.Pool to avoid an allocation during Put

pkg/ruler/storage/wal/wal.go:571:18

570 //nolint:staticcheck
571 a.w.bufPool.Put(buf)
572

clients/pkg/logentry/stages/eventlogmessage_test.go1

383:4overwritten-before-usethis value of val is overwritten before use

clients/pkg/logentry/stages/eventlogmessage_test.go:383:4

382 if len(resultKey) > 1 && len(resultKey[1]) > 0 {
383 val = resultKey[1][1:]
384 }

clients/cmd/docker-driver/loki.go1

1:9package-commentspackage should have a documentation comment

clients/cmd/docker-driver/loki.go:1:9

1package main
2

pkg/dataobj/compaction/v2/calculator.go1

1:9package-directory-mismatchpackage compactionv2 does not match directory v2

pkg/dataobj/compaction/v2/calculator.go:1:9

1package compactionv2
2

clients/pkg/logentry/stages/geoip.go1

115:37range-value-addresstaking the address of range value e can be misleading

clients/pkg/logentry/stages/geoip.go:115:37

114 for e := range in {
115 g.process(e.Labels, e.Extracted, &e.Timestamp, &e.Line)
116 out <- e

pkg/loghttp/query.go1

276:7receiver-namingreceiver name s is inconsistent with ss

pkg/loghttp/query.go:276:7

275
276func (s Streams) ToProto() []logproto.Stream {
277 if len(s) == 0 {

pkg/compactor/deletion/request_handler_test.go1

146:48redefines-builtin-ididentifier error shadows a predeclared identifier

pkg/compactor/deletion/request_handler_test.go:146:48

145 for _, tc := range []struct {
146 orgID, query, startTime, endTime, interval, error string
147 }{

production/helm/loki/src/helm-test/canary_test.go1

2:1redundant-build-taglegacy +build line is redundant with go:build

production/helm/loki/src/helm-test/canary_test.go:2:1

1//go:build helm_test
2// +build helm_test
3

clients/pkg/logentry/stages/json_test.go1

66:17redundant-conversionconversion from float64 to the identical type is redundant

clients/pkg/logentry/stages/json_test.go:66:17

65 "nested": "{\"child\":\"value\"}",
66 "duration": float64(125),
67 "unknown": nil,

operator/api/loki/v1beta1/lokistack_types_test.go1

10:2redundant-import-aliasimport alias is identical to the package name

operator/api/loki/v1beta1/lokistack_types_test.go:10:2

9
10 v1 "github.com/grafana/loki/operator/api/loki/v1"
11 "github.com/grafana/loki/operator/api/loki/v1beta1"

operator/internal/handlers/internal/rules/rules_test.go1

536:3single-case-switchswitch with one case can be replaced by an if statement

operator/internal/handlers/internal/rules/rules_test.go:536:3

535 k.ListStub = func(_ context.Context, ol client.ObjectList, opt ...client.ListOption) error {
536 switch ol.(type) {
537 case *lokiv1.AlertingRuleList:

pkg/bloomgateway/util_test.go1

102:8slice-preallocationpreallocate collected with capacity len(range source) before appending once per iteration

pkg/bloomgateway/util_test.go:102:8

101 result := daysForRange(from, through)
102 var collected []string
103 for _, d := range result {

integration/client/client.go1

375:30standard-http-method-constantreplace the HTTP method literal with http.MethodPost

integration/client/client.go:375:30

374
375 req, err := http.NewRequest("POST", apiEndpoint, nil)
376 if err != nil {

operator/api/loki/v1/lokistack_types.go1

63:2task-commentFIXME comment should be resolved or linked to an owned work item

operator/api/loki/v1/lokistack_types.go:63:2

62 //
63 // FIXME: Add clear description of ingestion/query performance expectations.
64 SizeOneXSmall LokiStackSizeType = "1x.small"

clients/cmd/fluent-bit/config.go1

27:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/cmd/fluent-bit/config.go:27:1

26
27type ConfigGetter interface {
28 Get(key string) string

clients/pkg/logentry/logql/parser.go1

25:26unchecked-type-assertionuse the checked two-result form of the type assertion

clients/pkg/logentry/logql/parser.go:25:26

24 l := lexer{
25 parser: exprNewParser().(*exprParserImpl),
26 }

pkg/lokifrontend/frontend/downstream_roundtripper.go1

66:2unclosed-http-response-bodylocally acquired HTTP response body is not directly closed or transferred before replacement or function exit

pkg/lokifrontend/frontend/downstream_roundtripper.go:66:2

65
66 httpResp, err := d.transport.RoundTrip(r)
67 if err != nil {

pkg/logql/log/pattern/lexer.rl.go1

31unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:31

30
31var _pattern_range_lengths []byte = []byte{
32 0, 3, 1, 1, 1, 1, 1, 1,

clients/pkg/logentry/stages/geoip.go1

109:41unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/geoip.go:109:41

108// Run implements Stage
109func (g *geoIPStage) Run(in chan Entry) chan Entry {
110 out := make(chan Entry)

pkg/storage/stores/shipper/indexshipper/tsdb/index/index.go1

2482:1unreachable-codestatement is unreachable after unconditional control flow

pkg/storage/stores/shipper/indexshipper/tsdb/index/index.go:2482:1

2481
2482iterate:
2483 for i := 0; i < chunksRemaining; i++ {

pkg/columnar/columnartest/equality.go1

96:49unused-parameterparameter right is unused

pkg/columnar/columnartest/equality.go:96:49

95
96func requireNullArraysEqual(t testing.TB, left, right *columnar.Null, mask memory.Bitmap) {
97 // Nothing to do here; the base checks in RequireArraysEqual covers

clients/pkg/logentry/stages/decolorize.go1

14:7unused-receiverreceiver m is unused

clients/pkg/logentry/stages/decolorize.go:14:7

13// Run implements Stage
14func (m *decolorizeStage) Run(in chan Entry) chan Entry {
15 decolorizer, _ := log.NewDecolorizer()

clients/cmd/docker-driver/config_test.go1

75:14use-anyuse any instead of interface{}

clients/cmd/docker-driver/config_test.go:75:14

74 },
75 map[string]interface{}{
76 "labels": map[string]interface{}{

integration/parse_metrics.go1

16:25use-errors-newreplace fmt.Errorf with errors.New for a static message

integration/parse_metrics.go:16:25

15 ErrNoMetricFound = fmt.Errorf("metric not found")
16 ErrInvalidMetricType = fmt.Errorf("invalid metric type")
17)

operator/internal/manifests/storage/schema.go1

43:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

operator/internal/manifests/storage/schema.go:43:2

42
43 sort.SliceStable(sortedSchemas, func(i, j int) bool {
44 iDate, _ := sortedSchemas[i].EffectiveDate.UTCTime()

cmd/chunks-inspect/loki.go1

44:2var-namingidentifier should use MixedCaps rather than underscores

cmd/chunks-inspect/loki.go:44:2

43 enclz4_1M = Encoding{code: 6, name: "lz4-1M", readerFn: func(reader io.Reader) (io.Reader, error) { return lz4.NewReader(reader), nil }}
44 enclz4_4M = Encoding{code: 7, name: "lz4-4M", readerFn: func(reader io.Reader) (io.Reader, error) { return lz4.NewReader(reader), nil }}
45 encFlate = Encoding{code: 8, name: "flate", readerFn: func(reader io.Reader) (io.Reader, error) { return flate.NewReader(reader), nil }}

clients/cmd/fluent-bit/config_labels_test.go1

35:61add-constantstring literal "fluent-bit" appears more than twice; define a constant

clients/cmd/fluent-bit/config_labels_test.go:35:61

34 labels: `{job="fluent-bit",env="prod"}`,
35 want: flagext.LabelSet{LabelSet: model.LabelSet{"job": "fluent-bit", "env": "prod"}},
36 },

pkg/querier/queryrange/downstreamer_test.go1

619:2call-to-gcavoid explicit garbage collection

pkg/querier/queryrange/downstreamer_test.go:619:2

618 // Record baseline goroutine count.
619 runtime.GC()
620 time.Sleep(50 * time.Millisecond)

clients/cmd/fluent-bit/dque.go1

88:22cognitive-complexityfunction has cognitive complexity 10; maximum is 7

clients/cmd/fluent-bit/dque.go:88:22

87
88func (c *dqueClient) dequeuer() {
89 defer c.wg.Done()

integration/client/client.go1

181:18confusing-namingname pushOTLPLogLine differs from PushOTLPLogLine only by capitalization

integration/client/client.go:181:18

180// pushOTLPLogLine creates a new logline
181func (c *Client) pushOTLPLogLine(line string, timestamp time.Time, logAttributes map[string]any) error {
182 apiEndpoint := fmt.Sprintf("%s/otlp/v1/logs", c.baseURL)

pkg/bloomgateway/multiplexing.go1

98:37confusing-resultsadjacent unnamed results of the same type should be named

pkg/bloomgateway/multiplexing.go:98:37

97// see pkg/storage/stores/shipper/indexshipper/tsdb.Bounded
98func (t Task) Bounds() (model.Time, model.Time) {
99 return t.interval.Start, t.interval.End

clients/pkg/util/client.go1

243:6constructor-interface-returnNewWithTripperware returns interface Client although its concrete result is consistently *client; return the concrete type

clients/pkg/util/client.go:243:6

242// NewWithTripperware creates a new Loki client with a custom tripperware.
243func NewWithTripperware(metrics *Metrics, cfg Config, maxStreams, maxLineSize int, maxLineSizeTruncate bool, logger log.Logger, tp Tripperware) (Client, error) {
244 c, err := newClient(metrics, cfg, maxStreams, maxLineSize, maxLineSizeTruncate, logger)

pkg/pattern/tee_service.go1

427:7context-cancel-in-loopcancellation deferred inside a loop runs only when the surrounding function returns; cancel before the iteration ends

pkg/pattern/tee_service.go:427:7

426 )
427 defer cancel()
428

pkg/bloombuild/builder/spec.go1

146:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

pkg/bloombuild/builder/spec.go:146:2

145type LazyBlockBuilderIterator struct {
146 ctx context.Context
147 opts v1.BlockOptions

clients/cmd/fluent-bit/loki.go1

221:16cyclomatic-complexityfunction complexity is 14; maximum is 10

clients/cmd/fluent-bit/loki.go:221:16

220
221func (l *loki) createLine(records map[string]interface{}, f format) (string, error) {
222 switch f {

operator/cmd/loki-broker/main.go1

70:3deep-exitprocess-exit calls should be confined to main or init

operator/cmd/loki-broker/main.go:70:3

69 log.Info("-custom.resource.path flag is required")
70 os.Exit(1)
71 }

pkg/ingester/checkpoint_test.go1

38:3deprecated-api-usagegithub.com/grafana/loki/v3/pkg/logproto.Selector is deprecated: Do not use.

pkg/ingester/checkpoint_test.go:38:3

37 err := i.Query(&logproto.QueryRequest{
38 Selector: `{foo="bar"}`,
39 Limit: 100,

clients/cmd/docker-driver/driver.go1

132:4discarded-error-resulterror result returned by level.Debug(d.logger).Log is discarded

clients/cmd/docker-driver/driver.go:132:4

131 if err := os.RemoveAll(lf.folder); err != nil {
132 level.Debug(d.logger).Log("msg", "error deleting folder", "folder", lf.folder)
133 }

clients/cmd/fluent-bit/dque.go1

135:1doc-comment-perioddocumentation comment should end with punctuation

clients/cmd/fluent-bit/dque.go:135:1

134
135// Stop the client
136func (c *dqueClient) StopNow() {

clients/pkg/logentry/stages/pack.go1

48:4early-returninvert the condition and return early to reduce nesting

clients/pkg/logentry/stages/pack.go:48:4

47 } else {
48 if s, ok := v.(string); ok {
49 w.Labels[k] = s

clients/pkg/logentry/stages/replace_test.go1

260:14error-stringserror string should not be capitalized or end with punctuation

clients/pkg/logentry/stages/replace_test.go:260:14

259 if (err != nil) != (tt.err != nil) {
260 t.Errorf("ReplaceConfig.validate() expected error = %v, actual error = %v", tt.err, err)
261 return

pkg/ruler/storage/instance/errors.go1

43:6error-type-namingerror implementation type should have an Error suffix

pkg/ruler/storage/instance/errors.go:43:6

42// is wrapped inside of a ErrInvalidUpdate.
43type errImmutableField struct{ Field string }
44

pkg/ingester/owned_streams.go1

78:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

pkg/ingester/owned_streams.go:78:2

77func (s *ownedStreamService) updateFixedLimit() (old, newVal int32) {
78 newLimit, _, _, _ := s.limiter.GetStreamCountLimit(s.tenantID, noPolicy)
79 return s.fixedLimit.Swap(int32(newLimit)), int32(newLimit)

clients/cmd/docker-driver/logdriver/io.go1

14:6exported-declaration-commentexported type should have a comment beginning with its name

clients/cmd/docker-driver/logdriver/io.go:14:6

13// The stream format is [uint32 big-endian size][protobuf message].
14type LogEntryEncoder interface {
15 Encode(*LogEntry) error

integration/cluster/cluster.go1

1:1file-length-limitfile has 562 lines; maximum is 500

integration/cluster/cluster.go:1:1

1package cluster
2

cmd/logcli/main.go1

769:21flag-parameterboolean parameter rangeQuery controls function flow

cmd/logcli/main.go:769:21

768
769func newVolumeQuery(rangeQuery bool, cmd *kingpin.CmdClause) *volume.Query {
770 // calculate query range from cli params

clients/cmd/fluent-bit/config.go1

1:1formatfile is not formatted

clients/cmd/fluent-bit/config.go:1:1

1package main
2
  • Fix (safe): run `strider fmt clients/cmd/fluent-bit/config.go`

clients/pkg/logentry/logql/parser_test.go1

47:6function-lengthfunction has 2 statements and 114 lines; maximum is 50 statements or 75 lines

clients/pkg/logentry/logql/parser_test.go:47:6

46
47func TestParse(t *testing.T) {
48 for _, tc := range []struct {

pkg/bloombuild/planner/queue/queue.go1

198:17function-result-limitfunction returns 4 values; maximum is 3

pkg/bloombuild/planner/queue/queue.go:198:17

197// Dequeue takes a task from the queue. The task is not removed from the filesystem until Release is called.
198func (q *Queue) Dequeue(ctx context.Context, last Index, consumerID string) (*protos.ProtoTask, any, Index, error) {
199 item, idx, err := q.queue.Dequeue(ctx, last, consumerID)

pkg/ruler/base/api.go1

559:15get-function-return-valueGet-prefixed function should return a value

pkg/ruler/base/api.go:559:15

558
559func (a *API) GetRuleGroup(w http.ResponseWriter, req *http.Request) {
560 logger := util_log.WithContext(req.Context(), a.logger)

pkg/scratch/filesystem.go1

90:22identical-if-chain-branchesif-else-if chain repeats a branch body

pkg/scratch/filesystem.go:90:22

89 return nil
90 } else if d == nil {
91 // Ignore errors (d == nil only if there's an error); process what

clients/pkg/logentry/stages/metrics.go1

331:2identical-switch-branchesswitch repeats a case body

clients/pkg/logentry/stages/metrics.go:331:2

330 return float64(i), nil
331 case int32:
332 return float64(i), nil

clients/pkg/logentry/stages/decolorize_test.go1

10:2import-alias-namingimport alias should contain lower-case letters and digits

clients/pkg/logentry/stages/decolorize_test.go:10:2

9
10 util_log "github.com/grafana/loki/v3/pkg/util/log"
11)

clients/cmd/docker-driver/driver.go1

59:16import-shadowingidentifier logger shadows an imported package

clients/cmd/docker-driver/driver.go:59:16

58
59func newDriver(logger log.Logger) *driver {
60 return &driver{

pkg/compactor/deletion/job_builder_test.go1

36:3inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

pkg/compactor/deletion/job_builder_test.go:36:3

35 if _, ok := t.updates[tableName][userID]; !ok {
36 t.updates[tableName][userID] = map[string]deletionproto.StorageUpdates{
37 labels: {

pkg/compactor/retention/marker_test.go1

57:35inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

pkg/compactor/retention/marker_test.go:57:35

56 for i := 0; i <= 2000; i++ {
57 require.NoError(t, w.Put([]byte(fmt.Sprintf("%d", i))))
58 }

clients/cmd/fluent-bit/config_test.go1

88:22insecure-url-schemeURL uses insecure http scheme

clients/cmd/fluent-bit/config_test.go:88:22

87 map[string]string{
88 "URL": "http://somewhere.com:3100/loki/api/v1/push",
89 "LineFormat": "key_value",

pkg/engine/handler.go1

37:13interface-method-limitinterface has 24 methods, exceeding the configured design limit of 10

pkg/engine/handler.go:37:13

36
37type Limits interface {
38 querier_limits.Limits

pkg/engine/internal/proto/ulid/ulid.go1

23:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

pkg/engine/internal/proto/ulid/ulid.go:23:7

22// buffer must be at least [ULID.Size] bytes, otherwise MarshalTo panics.
23func (id *ULID) MarshalTo(data []byte) (int, error) {
24 pb := ProtoULID{Value: id[:]}

cmd/migrate/main.go1

355:7max-control-nestingcontrol-flow nesting exceeds 5 levels

cmd/migrate/main.go:355:7

354 for i, chk := range finalChks {
355 if enc, err := chk.Encoded(); err == nil {
356 totalBytes += uint64(len(enc))

pkg/canary/reader/reader.go1

98:6max-parametersfunction has 19 parameters; maximum is 8

pkg/canary/reader/reader.go:98:6

97
98func NewReader(writer io.Writer,
99 receivedChan chan time.Time,

integration/client/client.go1

560:6max-public-structsfile declares more than 5 exported structs

integration/client/client.go:560:6

559
560type Rules struct {
561 Name string

clients/cmd/fluent-bit/loki.go1

194:6modifies-parameterassignment modifies parameter res

clients/cmd/fluent-bit/loki.go:194:6

193 if lValue.IsValid() && model.UTF8Validation.IsValidLabelName(string(lName)) {
194 res[lName] = lValue
195 }

pkg/bloombuild/planner/versioned_range.go1

128:5modifies-value-receiverassignment modifies value receiver t

pkg/bloombuild/planner/versioned_range.go:128:5

127 tok := tsdbToken{through: bounds.Max, version: version}
128 t = append(t, tsdbToken{})
129 copy(t[i+1:], t[i:])

clients/cmd/fluent-bit/loki_test.go1

67:13nested-structsmove nested anonymous struct types to named declarations

clients/cmd/fluent-bit/loki_test.go:67:13

66
67 tests := []struct {
68 name string

pkg/bloombuild/builder/builder.go1

104:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

pkg/bloombuild/builder/builder.go:104:4

103 level.Error(b.logger).Log("msg", "failed to inject orgID into context", "err", err)
104 return nil
105 }

pkg/analytics/stats.go1

198:4nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/analytics/stats.go:198:4

197 }
198 return nil, nil
199 },

pkg/pattern/tee_service.go1

427:7no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/pattern/tee_service.go:427:7

426 )
427 defer cancel()
428

pkg/compactor/deletion/deletion_manifest_builder.go1

250:5no-else-after-returnremove else and unindent its body after the return

pkg/compactor/deletion/deletion_manifest_builder.go:250:5

249 return -1
250 } else if len(a.Requests) > len(b.Requests) {
251 return 1

cmd/chunks-inspect/loki.go1

32:6no-initreplace init with explicit initialization

cmd/chunks-inspect/loki.go:32:6

31
32func init() {
33 castagnoliTable = crc32.MakeTable(crc32.Castagnoli)

pkg/compactor/table_test.go1

443:2no-naked-returnreturn values must be explicit

pkg/compactor/table_test.go:443:2

442
443 return
444}

clients/cmd/docker-driver/main.go1

21:5no-package-varpackage variables introduce mutable global state

clients/cmd/docker-driver/main.go:21:5

20
21var logLevel dslog.Level
22

pkg/storage/stores/shipper/indexshipper/tsdb/index/pool.go1

33:13non-pointer-sync-pool-valuestore a pointer-like value in sync.Pool to avoid an allocation during Put

pkg/storage/stores/shipper/indexshipper/tsdb/index/pool.go:33:13

32 //nolint:staticcheck
33 p.pool.Put(xs)
34}

clients/pkg/logentry/stages/eventlogmessage_test.go1

387:4overwritten-before-usethis value of val is overwritten before use

clients/pkg/logentry/stages/eventlogmessage_test.go:387:4

386 if len(resultKey) > 1 && len(resultKey[1]) > 0 {
387 val = resultKeyValue[1][1:]
388 }

clients/cmd/docker-driver/main.go1

1:9package-commentspackage should have a documentation comment

clients/cmd/docker-driver/main.go:1:9

1package main
2

pkg/dataobj/compaction/v2/calculator_test.go1

1:9package-directory-mismatchpackage compactionv2 does not match directory v2

pkg/dataobj/compaction/v2/calculator_test.go:1:9

1package compactionv2
2

clients/pkg/logentry/stages/geoip.go1

115:51range-value-addresstaking the address of range value e can be misleading

clients/pkg/logentry/stages/geoip.go:115:51

114 for e := range in {
115 g.process(e.Labels, e.Extracted, &e.Timestamp, &e.Line)
116 out <- e

pkg/storage/chunk/cache/snappy.go1

53:7receiver-namingreceiver name c is inconsistent with s

pkg/storage/chunk/cache/snappy.go:53:7

52
53func (c *snappyCache) GetCacheType() stats.CacheType {
54 return c.next.GetCacheType()

pkg/dataobj/internal/dataset/value.go1

60:2redefines-builtin-ididentifier cap shadows a predeclared identifier

pkg/dataobj/internal/dataset/value.go:60:2

59 // cap holds the capacity of the underlying memory in data.
60 cap uint64
61

clients/pkg/logentry/stages/metrics.go1

345:11redundant-conversionconversion from float64 to the identical type is redundant

clients/pkg/logentry/stages/metrics.go:345:11

344 if i {
345 return float64(1), nil
346 }

operator/api/loki/v1beta1/recordingrule_types.go1

4:2redundant-import-aliasimport alias is identical to the package name

operator/api/loki/v1beta1/recordingrule_types.go:4:2

3import (
4 v1 "github.com/grafana/loki/operator/api/loki/v1"
5 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

operator/internal/manifests/gateway_tenants.go1

108:3single-case-switchswitch with one case can be replaced by an if statement

operator/internal/manifests/gateway_tenants.go:108:3

107 for _, o := range objs {
108 switch o.(type) {
109 // Drop Ingress in favor of Route in OpenShift.

pkg/canary/reader/reader.go2

78:7slice-preallocationpreallocate lbls with capacity len(range source) before appending once per iteration

pkg/canary/reader/reader.go:78:7

77 if labels != "" {
78 var lbls []string
79 for _, label := range strings.Split(labels, ",") {
234:46standard-http-method-constantreplace the HTTP method literal with http.MethodGet

pkg/canary/reader/reader.go:234:46

233
234 req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
235 if err != nil {

operator/api/loki/v1/lokistack_types.go1

71:2task-commentFIXME comment should be resolved or linked to an owned work item

operator/api/loki/v1/lokistack_types.go:71:2

70 //
71 // FIXME: Add clear description of ingestion/query performance expectations.
72 SizeOneXMedium LokiStackSizeType = "1x.medium"

clients/cmd/fluent-bit/dque.go1

27:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/cmd/fluent-bit/dque.go:27:1

26
27var defaultDqueConfig = dqueConfig{
28 queueDir: filepath.Join(os.TempDir(), "flb-storage/loki"),

clients/pkg/logentry/metric/counters.go1

92:33unchecked-type-assertionuse the checked two-result form of the type assertion

clients/pkg/logentry/metric/counters.go:92:33

91func (c *Counters) With(labels model.LabelSet) prometheus.Counter {
92 return c.metricVec.With(labels).(prometheus.Counter)
93}

pkg/lokifrontend/frontend/transport/handler.go1

131:2unclosed-http-response-bodylocally acquired HTTP response body is not directly closed or transferred before replacement or function exit

pkg/lokifrontend/frontend/transport/handler.go:131:2

130 startTime := time.Now()
131 resp, err := f.roundTripper.RoundTrip(r)
132 queryResponseTime := time.Since(startTime)

pkg/logql/log/pattern/lexer.rl.go1

36unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:36

35
36var _pattern_index_offsets []byte = []byte{
37 0, 0, 6, 8, 10, 12, 14, 16,

clients/pkg/logentry/stages/json.go1

95:40unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/json.go:95:40

94
95func (j *jsonStage) Run(in chan Entry) chan Entry {
96 out := make(chan Entry)

pkg/columnar/columnartest/equality.go1

96:71unused-parameterparameter mask is unused

pkg/columnar/columnartest/equality.go:96:71

95
96func requireNullArraysEqual(t testing.TB, left, right *columnar.Null, mask memory.Bitmap) {
97 // Nothing to do here; the base checks in RequireArraysEqual covers

clients/pkg/logentry/stages/decolorize.go1

33:7unused-receiverreceiver m is unused

clients/pkg/logentry/stages/decolorize.go:33:7

32// Name implements Stage
33func (m *decolorizeStage) Name() string {
34 return StageTypeDecolorize

clients/cmd/docker-driver/config_test.go1

76:25use-anyuse any instead of interface{}

clients/cmd/docker-driver/config_test.go:76:25

75 map[string]interface{}{
76 "labels": map[string]interface{}{
77 "level": nil,

pkg/bloombuild/builder/config.go1

30:10use-errors-newreplace fmt.Errorf with errors.New for a static message

pkg/bloombuild/builder/config.go:30:10

29 if cfg.PlannerAddress == "" {
30 return fmt.Errorf("planner address is required")
31 }

pkg/bloombuild/planner/strategies/chunksize.go1

156:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

pkg/bloombuild/planner/strategies/chunksize.go:156:2

155 // ensure we sort blocks so deduping iterator works as expected
156 sort.Slice(blocks, func(i, j int) bool {
157 return blocks[i].Bounds.Less(blocks[j].Bounds)

operator/internal/manifests/rules_config_test.go1

15:2var-namingidentifier should use MixedCaps rather than underscores

operator/internal/manifests/rules_config_test.go:15:2

14func TestRulesConfigMap_ReturnsDataEntriesPerRule(t *testing.T) {
15 cm_shards, err := RulesConfigMapShards(testOptions())
16 require.NoError(t, err)

clients/cmd/fluent-bit/config_test.go1

88:22add-constantstring literal "http://somewhere.com:3100/loki/api/v1/push" appears more than twice; define a constant

clients/cmd/fluent-bit/config_test.go:88:22

87 map[string]string{
88 "URL": "http://somewhere.com:3100/loki/api/v1/push",
89 "LineFormat": "key_value",

pkg/querier/queryrange/downstreamer_test.go1

650:2call-to-gcavoid explicit garbage collection

pkg/querier/queryrange/downstreamer_test.go:650:2

649 // Allow goroutines to settle.
650 runtime.GC()
651 require.Eventually(t, func() bool {

clients/cmd/fluent-bit/loki.go1

49:16cognitive-complexityfunction has cognitive complexity 9; maximum is 7

clients/cmd/fluent-bit/loki.go:49:16

48// sendRecord send fluentbit records to loki as an entry.
49func (l *loki) sendRecord(r map[interface{}]interface{}, ts time.Time) error {
50 records := toStringMap(r)

integration/loki_rule_eval_test.go1

40:6confusing-namingname testRuleEval differs from TestRuleEval only by capitalization

integration/loki_rule_eval_test.go:40:6

39// Both the local and the remote rule evaluation modes should produce the same result.
40func testRuleEval(t *testing.T, mode string, useThanosObjstore bool) {
41 clu := cluster.New(nil, cluster.SchemaWithTSDB, func(c *cluster.Cluster) {

pkg/bloomgateway/processor.go1

196:37confusing-resultsadjacent unnamed results of the same type should be named

pkg/bloomgateway/processor.go:196:37

195// It assumes an ascending sorted list of fingerprints.
196func getFirstLast[T any](s []T) (T, T) {
197 var zero T

pkg/bloomgateway/resolver.go1

146:6constructor-interface-returnNewBlockResolver returns interface BlockResolver although its concrete result is consistently *defaultBlockResolver; return the concrete type

pkg/bloomgateway/resolver.go:146:6

145
146func NewBlockResolver(store bloomshipper.StoreBase, logger log.Logger) BlockResolver {
147 return &defaultBlockResolver{

pkg/querier/worker/processor_manager.go1

71:18context-cancel-in-loopcontext.WithCancel is created in a loop but its cancellation function is not called during the iteration

pkg/querier/worker/processor_manager.go:71:18

70 workerID := len(pm.cancels) + 1
71 ctx, cancel := context.WithCancel(pm.ctx)
72 pm.cancels = append(pm.cancels, cancel)

pkg/bloombuild/planner/planner_test.go1

661:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

pkg/bloombuild/planner/planner_test.go:661:2

660 wait atomic.Bool
661 ctx context.Context
662 ctxCancel context.CancelFunc

clients/pkg/logentry/metric/counters.go1

31:6cyclomatic-complexityfunction complexity is 14; maximum is 10

clients/pkg/logentry/metric/counters.go:31:6

30
31func validateCounterConfig(config *CounterConfig) error {
32 if config.Action == "" {

operator/cmd/loki-broker/main.go1

74:3deep-exitprocess-exit calls should be confined to main or init

operator/cmd/loki-broker/main.go:74:3

73 log.Info("-name flag is required")
74 os.Exit(1)
75 }

pkg/ingester/client/client.go1

81:15deprecated-api-usagegoogle.golang.org/grpc.Dial is deprecated: use NewClient instead. Will be supported throughout 1.x.

pkg/ingester/client/client.go:81:15

80 // nolint:staticcheck // grpc.Dial() has been deprecated; we'll address it before upgrading to gRPC 2.
81 conn, err := grpc.Dial(addr, opts...)
82 if err != nil {

clients/cmd/docker-driver/driver.go1

143:5discarded-error-resulterror result returned by level.Debug(lf.logger).Log is discarded

clients/cmd/docker-driver/driver.go:143:5

142 if err == io.EOF || err == os.ErrClosed || strings.Contains(err.Error(), "file already closed") {
143 level.Debug(lf.logger).Log("msg", "shutting down log logger", "id", lf.info.ContainerID, "err", err)
144 return

clients/cmd/fluent-bit/out_grafana_loki.go1

44:1doc-comment-perioddocumentation comment should end with punctuation

clients/cmd/fluent-bit/out_grafana_loki.go:44:1

43
44//export FLBPluginRegister
45func FLBPluginRegister(ctx unsafe.Pointer) int {

cmd/migrate/main.go1

329:9early-returninvert the condition and return early to reduce nesting

cmd/migrate/main.go:329:9

328 onechunk, err = f.FetchChunks(m.ctx, onechunk)
329 if err != nil {
330 if retry == 0 {

clients/pkg/logentry/stages/replace_test.go1

264:14error-stringserror string should not be capitalized or end with punctuation

clients/pkg/logentry/stages/replace_test.go:264:14

263 if (err != nil) && (err.Error() != tt.err.Error()) {
264 t.Errorf("ReplaceConfig.validate() expected error = %v, actual error = %v", tt.err, err)
265 return

pkg/util/errors/errors.go1

97:6error-type-namingerror implementation type should have an Error suffix

pkg/util/errors/errors.go:97:6

96// grouped by the error message.
97type GroupedErrors struct {
98 MultiError

pkg/ingester/replay_controller.go1

84:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

pkg/ingester/replay_controller.go:84:2

83 // Use singleflight to ensure only one flush happens at a time
84 _, _, _ = c.flushSF.Do("flush", func() (interface{}, error) {
85 c.flush()

clients/cmd/docker-driver/logdriver/io.go1

31:27exported-declaration-commentexported function or method should have a comment beginning with its name

clients/cmd/docker-driver/logdriver/io.go:31:27

30
31func (e *logEntryEncoder) Encode(l *LogEntry) error {
32 payload, err := proto.Marshal(l)

integration/loki_micro_services_test.go1

1:1file-length-limitfile has 1175 lines; maximum is 500

integration/loki_micro_services_test.go:1:1

1//go:build integration
2

integration/cluster/cluster.go1

244:24flag-parameterboolean parameter cleanupFiles controls function flow

integration/cluster/cluster.go:244:24

243
244func (c *Cluster) stop(cleanupFiles bool) error {
245 _, cancelFunc := context.WithTimeout(context.Background(), time.Second*3)

clients/cmd/fluent-bit/config_labels_test.go1

1:1formatfile is not formatted

clients/cmd/fluent-bit/config_labels_test.go:1:1

1package main
2
  • Fix (safe): run `strider fmt clients/cmd/fluent-bit/config_labels_test.go`

clients/pkg/logentry/stages/drop.go1

164:21function-lengthfunction has 53 statements and 100 lines; maximum is 50 statements or 75 lines

clients/pkg/logentry/stages/drop.go:164:21

163
164func (m *dropStage) shouldDrop(e Entry) bool {
165 // There are many options for dropping a log and if multiple are defined it's treated like an AND condition

pkg/bloombuild/planner/retention_test.go1

659:6function-result-limitfunction returns 4 values; maximum is 3

pkg/bloombuild/planner/retention_test.go:659:6

658
659func NewMockBloomStore(t *testing.T, logger log.Logger) (*bloomshipper.BloomStore, storageconfig.SchemaConfig, string, error) {
660 workDir := t.TempDir()

clients/pkg/logentry/stages/metrics.go1

333:2identical-switch-branchesswitch repeats a case body

clients/pkg/logentry/stages/metrics.go:333:2

332 return float64(i), nil
333 case int:
334 return float64(i), nil

clients/pkg/logentry/stages/drop_test.go1

15:2import-alias-namingimport alias should contain lower-case letters and digits

clients/pkg/logentry/stages/drop_test.go:15:2

14
15 util_log "github.com/grafana/loki/v3/pkg/util/log"
16)

clients/cmd/docker-driver/loki.go1

25:2import-shadowingidentifier logger shadows an imported package

clients/cmd/docker-driver/loki.go:25:2

24 labels model.LabelSet
25 logger log.Logger
26

pkg/compactor/jobqueue/queue.go1

225:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

pkg/compactor/jobqueue/queue.go:225:4

224 if _, ok := q.processingJobs[job.Id]; !ok {
225 q.processingJobs[job.Id] = &processingJob{
226 job: job,

pkg/compactor/retention/marker_test.go1

143:40inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.FormatInt with base 10

pkg/compactor/retention/marker_test.go:143:40

142 {"happy path", func(dir string) ([]string, []time.Time) {
143 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.UnixNano())))
144 _, _ = os.Create(filepath.Join(dir, "foo"))

clients/cmd/fluent-bit/config_test.go1

106:35insecure-url-schemeURL uses insecure http scheme

clients/cmd/fluent-bit/config_test.go:106:35

105 clientConfig: util.Config{
106 URL: mustParseURL("http://somewhere.com:3100/loki/api/v1/push"),
107 TenantID: "", // empty as not set in fluent-bit plugin config map

pkg/indexgateway/gateway.go1

40:19interface-method-limitinterface has 11 methods, exceeding the configured design limit of 10

pkg/indexgateway/gateway.go:40:19

39
40type IndexQuerier interface {
41 stores.ChunkFetcher

pkg/engine/internal/proto/ulid/ulid.go1

29:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

pkg/engine/internal/proto/ulid/ulid.go:29:7

28// Unmarshal unmarshals a [ProtoULID] from the given data slice.
29func (id *ULID) Unmarshal(data []byte) error {
30 pb := ProtoULID{}

cmd/migrate/main.go1

362:7max-control-nestingcontrol-flow nesting exceeds 5 levels

cmd/migrate/main.go:362:7

361 }
362 if m.sourceUser != m.destUser {
363 // Because the incoming chunks are already encoded, to change the username we have to make a new chunk

pkg/canary/writer/push.go1

67:6max-parametersfunction has 18 parameters; maximum is 8

pkg/canary/writer/push.go:67:6

66// instance which sends log lines to Loki in batches.
67func NewPush(
68 lokiAddr, tenantID string,

integration/client/client.go1

566:6max-public-structsfile declares more than 5 exported structs

integration/client/client.go:566:6

565
566type Header struct {
567 Name, Value string

clients/cmd/fluent-bit/loki.go1

233:5modifies-parameterassignment modifies parameter records

clients/cmd/fluent-bit/loki.go:233:5

232 }
233 records[k] = data
234 }

pkg/bloombuild/planner/versioned_range.go1

130:5modifies-value-receiverassignment modifies value receiver t

pkg/bloombuild/planner/versioned_range.go:130:5

129 copy(t[i+1:], t[i:])
130 t[i] = tok
131 return t, true

clients/cmd/fluent-bit/loki_test.go1

110:13nested-structsmove nested anonymous struct types to named declarations

clients/cmd/fluent-bit/loki_test.go:110:13

109func Test_createLine(t *testing.T) {
110 tests := []struct {
111 name string

pkg/bloombuild/builder/builder.go1

156:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

pkg/bloombuild/builder/builder.go:156:4

155 // Edge case when the builder is shutting down while we check for retries
156 return nil
157 }

pkg/analytics/stats.go1

218:4nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/analytics/stats.go:218:4

217 }
218 return nil, nil
219 },

pkg/querytee/proxy_test.go1

162:5no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/querytee/proxy_test.go:162:5

161 s := httptest.NewServer(b.handler)
162 defer s.Close()
163

pkg/compactor/deletion/deletion_manifest_builder.go1

360:4no-else-after-returnremove else and unindent its body after the return

pkg/compactor/deletion/deletion_manifest_builder.go:360:4

359 return true, nil
360 } else if objectClient.IsObjectNotFoundErr(err) {
361 return false, nil

operator/api/config/v1/projectconfig_types.go1

227:6no-initreplace init with explicit initialization

operator/api/config/v1/projectconfig_types.go:227:6

226
227func init() {
228 SchemeBuilder.Register(&ProjectConfig{})

pkg/dataobj/decoder_metadata.go1

28:2no-naked-returnreturn values must be explicit

pkg/dataobj/decoder_metadata.go:28:2

27 }
28 return
29}

clients/cmd/fluent-bit/buffer.go1

17:5no-package-varpackage variables introduce mutable global state

clients/cmd/fluent-bit/buffer.go:17:5

16
17var defaultBufferConfig = bufferConfig{
18 buffer: false,

pkg/storage/stores/shipper/indexshipper/tsdb/index/postings.go1

245:30non-pointer-sync-pool-valuestore a pointer-like value in sync.Pool to avoid an allocation during Put

pkg/storage/stores/shipper/indexshipper/tsdb/index/postings.go:245:30

244 job = job[:0]
245 ensureOrderBatchPool.Put(job) //nolint:staticcheck // Ignore SA6002 safe to ignore and actually fixing it has some performance penalty.
246 }

pkg/compute/equality_bench_test.go1

39:5overwritten-before-usethis value of result is overwritten before use

pkg/compute/equality_bench_test.go:39:5

38 benchAlloc.Reclaim()
39 result, err := compute.Equals(benchAlloc, left, right, selection)
40 if err != nil {

clients/cmd/fluent-bit/buffer.go1

1:9package-commentspackage should have a documentation comment

clients/cmd/fluent-bit/buffer.go:1:9

1package main
2

pkg/dataobj/compaction/v2/doc.go1

5:9package-directory-mismatchpackage compactionv2 does not match directory v2

pkg/dataobj/compaction/v2/doc.go:5:9

4// batches P runs into ceil(P/K) tasks that each produce one output sequence.
5package compactionv2
6

clients/pkg/logentry/stages/geoip_test.go1

47:30range-value-addresstaking the address of range value tt can be misleading

clients/pkg/logentry/stages/geoip_test.go:47:30

46 for _, tt := range tests {
47 err := validateGeoIPConfig(&tt.config)
48 if err != nil {

pkg/dataobj/internal/util/bitmask/bitmask.go1

7:2redefines-builtin-ididentifier len shadows a predeclared identifier

pkg/dataobj/internal/util/bitmask/bitmask.go:7:2

6type Mask struct {
7 len int
8 b []uint64

clients/pkg/logentry/stages/metrics.go1

347:10redundant-conversionconversion from float64 to the identical type is redundant

clients/pkg/logentry/stages/metrics.go:347:10

346 }
347 return float64(0), nil
348 default:

operator/api/loki/v1beta1/recordingrule_types_test.go1

6:2redundant-import-aliasimport alias is identical to the package name

operator/api/loki/v1beta1/recordingrule_types_test.go:6:2

5
6 v1 "github.com/grafana/loki/operator/api/loki/v1"
7 "github.com/grafana/loki/operator/api/loki/v1beta1"

operator/internal/manifests/gateway_tenants.go1

146:4single-case-switchswitch with one case can be replaced by an if statement

operator/internal/manifests/gateway_tenants.go:146:4

145 for _, o := range objs {
146 switch sa := o.(type) {
147 case *corev1.ServiceAccount:

pkg/chunkenc/memchunk_test.go1

1449:10slice-preallocationpreallocate iters with capacity len(range source) before appending once per iteration

pkg/chunkenc/memchunk_test.go:1449:10

1448 }
1449 var iters []iter.EntryIterator
1450 for _, lbs := range labelsSet {

pkg/canary/reader/reader.go1

328:46standard-http-method-constantreplace the HTTP method literal with http.MethodGet

pkg/canary/reader/reader.go:328:46

327
328 req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
329 if err != nil {

operator/api/loki/v1beta1/lokistack_types.go1

39:2task-commentFIXME comment should be resolved or linked to an owned work item

operator/api/loki/v1beta1/lokistack_types.go:39:2

38 //
39 // FIXME: Add clear description of ingestion/query performance expectations.
40 SizeOneXExtraSmall LokiStackSizeType = "1x.extra-small"

clients/cmd/fluent-bit/out_grafana_loki.go1

36:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/cmd/fluent-bit/out_grafana_loki.go:36:1

35
36type pluginConfig struct {
37 ctx unsafe.Pointer

clients/pkg/logentry/metric/gauges.go1

85:33unchecked-type-assertionuse the checked two-result form of the type assertion

clients/pkg/logentry/metric/gauges.go:85:33

84func (g *Gauges) With(labels model.LabelSet) prometheus.Gauge {
85 return g.metricVec.With(labels).(prometheus.Gauge)
86}

tools/querycomparator/compare.go1

220:2unclosed-http-response-bodylocally acquired HTTP response body is not directly closed or transferred before replacement or function exit

tools/querycomparator/compare.go:220:2

219
220 resp, err := http.DefaultClient.Do(req)
221 if err != nil {

pkg/logql/log/pattern/lexer.rl.go1

41unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:41

40
41var _pattern_indicies []byte = []byte{
42 2, 1, 1, 1, 1, 0, 3, 4,

clients/pkg/logentry/stages/limit.go1

95:41unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/limit.go:95:41

94
95func (m *limitStage) Run(in chan Entry) chan Entry {
96 out := make(chan Entry)

pkg/storage/chunk/dummy.go1

20:28unused-parameterparameter sample is unused

pkg/storage/chunk/dummy.go:20:28

19
20func (chk *dummyChunk) Add(sample model.SamplePair) (Data, error) {
21 return nil, nil

clients/pkg/logentry/stages/drop.go1

266:7unused-receiverreceiver m is unused

clients/pkg/logentry/stages/drop.go:266:7

265// Name implements Stage
266func (m *dropStage) Name() string {
267 return StageTypeDrop

clients/cmd/fluent-bit/config.go1

52:34use-anyuse any instead of interface{}

clients/cmd/fluent-bit/config.go:52:34

51 dropSingleKey bool
52 labelMap map[string]interface{}
53}

pkg/bloombuild/planner/queue/config.go1

27:10use-errors-newreplace fmt.Errorf with errors.New for a static message

pkg/bloombuild/planner/queue/config.go:27:10

26 if cfg.StoreTasksOnDisk && cfg.TasksDiskDirectory == "" {
27 return fmt.Errorf("tasks_disk_directory must be set when store_tasks_on_disk is true")
28 }

pkg/bloombuild/planner/versioned_range.go1

219:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

pkg/bloombuild/planner/versioned_range.go:219:2

218 // for outdated metas (older metas are discarded if they don't change the range).
219 sort.Slice(metas, func(i, j int) bool {
220 a, aExists := metas[i].MostRecentSource()

operator/internal/manifests/rules_config_test.go1

30:2var-namingidentifier should use MixedCaps rather than underscores

operator/internal/manifests/rules_config_test.go:30:2

29 opts := testOptions()
30 cm_shards, err := RulesConfigMapShards(opts)
31 require.NoError(t, err)

clients/cmd/fluent-bit/config_test.go1

90:22add-constantstring literal "warn" appears more than twice; define a constant

clients/cmd/fluent-bit/config_test.go:90:22

89 "LineFormat": "key_value",
90 "LogLevel": "warn",
91 "Labels": `{app="foo"}`,

pkg/querier/queryrange/split_by_interval_test.go1

1923:2call-to-gcavoid explicit garbage collection

pkg/querier/queryrange/split_by_interval_test.go:1923:2

1922 }
1923 runtime.GC()
1924 endingGoroutines := runtime.NumGoroutine()

clients/cmd/fluent-bit/loki.go1

134:6cognitive-complexityfunction has cognitive complexity 8; maximum is 7

clients/cmd/fluent-bit/loki.go:134:6

133
134func autoLabels(records map[string]interface{}, kuberneteslbs model.LabelSet) error {
135 kube, ok := records["kubernetes"]

operator/internal/manifests/storage/configure.go1

80:6confusing-namingname configureDeployment differs from ConfigureDeployment only by capitalization

operator/internal/manifests/storage/configure.go:80:6

79// With this, the deployment will expose credentials specific environment variables.
80func configureDeployment(d *appsv1.Deployment, opts Options) error {
81 p := ensureObjectStoreCredentials(&d.Spec.Template.Spec, opts)

pkg/bloomgateway/util.go1

135:106confusing-resultsadjacent unnamed results of the same type should be named

pkg/bloomgateway/util.go:135:106

134
135func overlappingChunks(from, through, minTs, maxTs model.Time, chunks []*logproto.ShortRef) (model.Time, model.Time, []*logproto.ShortRef) {
136

pkg/chunkenc/dumb_chunk.go1

21:6constructor-interface-returnNewDumbChunk returns interface Chunk although its concrete result is consistently *dumbChunk; return the concrete type

pkg/chunkenc/dumb_chunk.go:21:6

20// NewDumbChunk returns a new chunk that isn't very good.
21func NewDumbChunk() Chunk {
22 return &dumbChunk{}

pkg/bloombuild/planner/task.go1

18:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

pkg/bloombuild/planner/task.go:18:2

17 queueTime time.Time
18 ctx context.Context
19}

clients/pkg/logentry/stages/drop.go1

50:6cyclomatic-complexityfunction complexity is 23; maximum is 10

clients/pkg/logentry/stages/drop.go:50:6

49// validateDropConfig validates the DropConfig for the dropStage
50func validateDropConfig(cfg *DropConfig) error {
51 if cfg == nil ||

operator/cmd/loki-broker/main.go1

78:3deep-exitprocess-exit calls should be confined to main or init

operator/cmd/loki-broker/main.go:78:3

77 log.Info("-namespace flag is required")
78 os.Exit(1)
79 }

pkg/ingester/ingester.go1

1076:42deprecated-api-usagegithub.com/grafana/loki/v3/pkg/logproto.Selector is deprecated: Do not use.

pkg/ingester/ingester.go:1076:42

1075 if req.Plan == nil {
1076 parsed, err := syntax.ParseLogSelector(req.Selector, true)
1077 if err != nil {

clients/cmd/docker-driver/driver.go1

164:4discarded-error-resulterror result returned by level.Error(lf.logger).Log is discarded

clients/cmd/docker-driver/driver.go:164:4

163 if err := lf.lokil.Log(&msg); err != nil {
164 level.Error(lf.logger).Log("msg", "error pushing message to loki", "id", lf.info.ContainerID, "err", err, "message", msg)
165 }

clients/cmd/fluent-bit/out_grafana_loki.go1

52:1doc-comment-perioddocumentation comment should end with punctuation

clients/cmd/fluent-bit/out_grafana_loki.go:52:1

51//
52//export FLBPluginInit
53func FLBPluginInit(ctx unsafe.Pointer) int {

cmd/migrate/main.go1

355:7early-returninvert the condition and return early to reduce nesting

cmd/migrate/main.go:355:7

354 for i, chk := range finalChks {
355 if enc, err := chk.Encoded(); err == nil {
356 totalBytes += uint64(len(enc))

clients/pkg/logentry/stages/stage.go1

222:29error-stringserror string should not be capitalized or end with punctuation

clients/pkg/logentry/stages/stage.go:222:29

221 if !ok {
222 return nil, errors.Errorf("Unknown stage type: %s", stageType)
223 }

pkg/util/server/error_test.go1

30:6error-type-namingerror implementation type should have an Error suffix

pkg/util/server/error_test.go:30:6

29// keeps working.
30type grpcStatusWrappedErr struct {
31 code codes.Code

pkg/limits/store_bench_test.go1

65:5excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

pkg/limits/store_bench_test.go:65:5

64
65 _, _, _, err := s.UpdateCond(tenant, metadata, updateTime)
66 require.NoError(b, err)

clients/cmd/docker-driver/logdriver/io.go1

66:27exported-declaration-commentexported function or method should have a comment beginning with its name

clients/cmd/docker-driver/logdriver/io.go:66:27

65
66func (d *logEntryDecoder) Decode(l *LogEntry) error {
67 if _, err := io.ReadFull(d.r, d.lenBuf); err != nil {

operator/api/loki/v1/lokistack_types.go1

1:1file-length-limitfile has 1625 lines; maximum is 500

operator/api/loki/v1/lokistack_types.go:1:1

1package v1
2

operator/internal/handlers/internal/gateway/gateway.go1

97:28flag-parameterboolean parameter httpEncryption controls function flow

operator/internal/handlers/internal/gateway/gateway.go:97:28

96
97func validatePassthroughCA(httpEncryption bool, stack *lokiv1.LokiStack) *status.DegradedError {
98 if !httpEncryption {

clients/cmd/fluent-bit/config_test.go1

1:1formatfile is not formatted

clients/cmd/fluent-bit/config_test.go:1:1

1package main
2
  • Fix (safe): run `strider fmt clients/cmd/fluent-bit/config_test.go`

clients/pkg/logentry/stages/drop_test.go1

41:6function-lengthfunction has 7 statements and 382 lines; maximum is 50 statements or 75 lines

clients/pkg/logentry/stages/drop_test.go:41:6

40
41func Test_dropStage_Process(t *testing.T) {
42 // Enable debug logging

pkg/bloombuild/planner/retention_test.go1

664:6function-result-limitfunction returns 4 values; maximum is 3

pkg/bloombuild/planner/retention_test.go:664:6

663
664func NewMockBloomStoreWithWorkDir(t *testing.T, workDir string, logger log.Logger) (*bloomshipper.BloomStore, storageconfig.SchemaConfig, string, error) {
665 schemaCfg := storageconfig.SchemaConfig{

clients/pkg/logentry/stages/metrics.go1

335:2identical-switch-branchesswitch repeats a case body

clients/pkg/logentry/stages/metrics.go:335:2

334 return float64(i), nil
335 case uint64:
336 return float64(i), nil

clients/pkg/logentry/stages/eventlogmessage_test.go1

14:2import-alias-namingimport alias should contain lower-case letters and digits

clients/pkg/logentry/stages/eventlogmessage_test.go:14:2

13
14 util_log "github.com/grafana/loki/v3/pkg/util/log"
15)

clients/cmd/docker-driver/loki.go1

34:30import-shadowingidentifier logger shadows an imported package

clients/cmd/docker-driver/loki.go:34:30

33// New create a new Loki logger that forward logs to Loki instance
34func New(logCtx logger.Info, logger log.Logger) (logger.Logger, error) {
35 logger = log.With(logger, "container_id", logCtx.ContainerID)

pkg/compactor/retention/util_test.go1

216:3inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

pkg/compactor/retention/util_test.go:216:3

215 if _, ok := t.chunks[chk.UserID]; !ok {
216 t.chunks[chk.UserID] = make(map[string][]logproto.ChunkRef)
217 }

pkg/compactor/retention/marker_test.go1

145:40inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.FormatInt with base 10

pkg/compactor/retention/marker_test.go:145:40

144 _, _ = os.Create(filepath.Join(dir, "foo"))
145 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.Add(-30*time.Minute).UnixNano())))
146 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.Add(-1*time.Hour).UnixNano())))

cmd/logcli/main.go1

577:87insecure-url-schemeURL uses insecure http scheme

cmd/logcli/main.go:577:87

576
577 app.Flag("addr", "Server address. Can also be set using LOKI_ADDR env var.").Default("http://localhost:3100").Envar("LOKI_ADDR").Action(addressAction).StringVar(&client.Address)
578 app.Flag("username", "Username for HTTP basic auth. Can also be set using LOKI_USERNAME env var.").Default("").Envar("LOKI_USERNAME").StringVar(&client.Username)

pkg/ingester/ingester.go1

215:12interface-method-limitinterface has 14 methods, exceeding the configured design limit of 10

pkg/ingester/ingester.go:215:12

214// Store is the store interface we need on the ingester.
215type Store interface {
216 stores.ChunkWriter

pkg/engine/internal/proto/ulid/ulid.go1

57:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

pkg/engine/internal/proto/ulid/ulid.go:57:7

56// UnmarshalJSON unmarshals a JSON string into a ULID.
57func (id *ULID) UnmarshalJSON(data []byte) error {
58 var text string

cmd/migrate/main.go1

366:8max-control-nestingcontrol-flow nesting exceeds 5 levels

cmd/migrate/main.go:366:8

365 err := nc.Encode()
366 if err != nil {
367 log.Println(threadID, "Failed to encode new chunk with new user:", err)

pkg/dataobj/consumer/service.go1

54:6max-parametersfunction has 10 parameters; maximum is 8

pkg/dataobj/consumer/service.go:54:6

53
54func New(kafkaCfg kafka.Config, cfg Config, mCfg metastore.Config, bucket objstore.Bucket, scratchStore scratch.Store, _ string, _ ring.PartitionRingReader, reg prometheus.Registerer, logger log.Logger, overrides logsobj.TenantOverrides) (*Service, error) {
55 logger = log.With(logger, "component", "dataobj-consumer")

integration/client/client.go1

797:6max-public-structsfile declares more than 5 exported structs

integration/client/client.go:797:6

796
797type TailResult struct {
798 Response loghttp.TailResponse

clients/pkg/logentry/logql/parser.go1

82:3modifies-parameterassignment modifies parameter lval

clients/pkg/logentry/logql/parser.go:82:3

81 var err error
82 lval.str, err = strconv.Unquote(l.TokenText())
83 if err != nil {

pkg/bloombuild/planner/versioned_range.go1

135:5modifies-value-receiverassignment modifies value receiver t

pkg/bloombuild/planner/versioned_range.go:135:5

134 if bounds.Max == preExisting.Max {
135 t[i].through = bounds.Min - 1
136 tok := tsdbToken{through: bounds.Max, version: version}

clients/cmd/fluent-bit/loki_test.go1

174:13nested-structsmove nested anonymous struct types to named declarations

clients/cmd/fluent-bit/loki_test.go:174:13

173func Test_removeKeys(t *testing.T) {
174 tests := []struct {
175 name string

pkg/compactor/deletion/delete_requests_store_boltdb.go1

365:3nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

pkg/compactor/deletion/delete_requests_store_boltdb.go:365:3

364 if err != nil {
365 return deletionproto.DeleteRequest{}, nil
366 }

pkg/analytics/stats.go1

238:4nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/analytics/stats.go:238:4

237 }
238 return nil, nil
239 },

pkg/querytee/proxy_test.go1

319:5no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/querytee/proxy_test.go:319:5

318 s := httptest.NewServer(router)
319 defer s.Close()
320

pkg/compactor/deletion/job_builder_test.go1

547:7no-else-after-returnremove else and unindent its body after the return

pkg/compactor/deletion/job_builder_test.go:547:7

546 return -1
547 } else if len(a.RequestID) > len(b.RequestID) {
548 return 1

operator/api/loki/v1/alertingrule_types.go1

133:6no-initreplace init with explicit initialization

operator/api/loki/v1/alertingrule_types.go:133:6

132
133func init() {
134 SchemeBuilder.Register(&AlertingRule{}, &AlertingRuleList{})

pkg/dataobj/explorer/inspect.go1

52:2no-naked-returnreturn values must be explicit

pkg/dataobj/explorer/inspect.go:52:2

51 }
52 return
53}

clients/cmd/fluent-bit/config.go1

20:5no-package-varpackage variables introduce mutable global state

clients/cmd/fluent-bit/config.go:20:5

19
20var defaultClientCfg = util.Config{}
21

pkg/storage/stores/shipper/indexshipper/tsdb/pool.go1

30:13non-pointer-sync-pool-valuestore a pointer-like value in sync.Pool to avoid an allocation during Put

pkg/storage/stores/shipper/indexshipper/tsdb/pool.go:30:13

29 //nolint:staticcheck
30 p.pool.Put(xs)
31}

pkg/compute/equality_bench_test.go1

62:5overwritten-before-usethis value of result is overwritten before use

pkg/compute/equality_bench_test.go:62:5

61 benchAlloc.Reclaim()
62 result, err := compute.Equals(benchAlloc, left, right, selection)
63 if err != nil {

clients/cmd/fluent-bit/client.go1

1:9package-commentspackage should have a documentation comment

clients/cmd/fluent-bit/client.go:1:9

1package main
2

pkg/dataobj/compaction/v2/output_naming.go1

1:9package-directory-mismatchpackage compactionv2 does not match directory v2

pkg/dataobj/compaction/v2/output_naming.go:1:9

1package compactionv2
2

clients/pkg/logentry/stages/json.go1

100:39range-value-addresstaking the address of range value e can be misleading

clients/pkg/logentry/stages/json.go:100:39

99 for e := range in {
100 err := j.processEntry(e.Extracted, &e.Line)
101 if err != nil && j.cfg.DropMalformed {

pkg/dataobj/sections/logs/row_predicate_order_test.go1

402:2redefines-builtin-ididentifier min shadows a predeclared identifier

pkg/dataobj/sections/logs/row_predicate_order_test.go:402:2

401 size int
402 min int64
403 max int64

clients/pkg/logentry/stages/multiline_test.go1

83:19redundant-conversionconversion from model.LabelValue to the identical type is redundant

clients/pkg/logentry/stages/multiline_test.go:83:19

82 require.Equal(t, "START line 1\nnot a start line 1\nnot a start line 2", out[0].Line)
83 require.Equal(t, model.LabelValue("one"), out[0].Labels["value"])
84

operator/api/loki/v1beta1/rulerconfig_types.go1

4:2redundant-import-aliasimport alias is identical to the package name

operator/api/loki/v1beta1/rulerconfig_types.go:4:2

3import (
4 v1 "github.com/grafana/loki/operator/api/loki/v1"
5 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

operator/internal/manifests/gateway_test.go1

1592:5single-case-switchswitch with one case can be replaced by an if statement

operator/internal/manifests/gateway_test.go:1592:5

1591 for _, obj := range objs {
1592 switch obj.(type) {
1593 case *networkingv1.Ingress:

pkg/chunkenc/memchunk_test.go1

1488:10slice-preallocationpreallocate iters with capacity len(range source) before appending once per iteration

pkg/chunkenc/memchunk_test.go:1488:10

1487 }
1488 var iters []iter.SampleIterator
1489 for _, lbs := range labelsSet {

pkg/canary/writer/push.go1

267:46standard-http-method-constantreplace the HTTP method literal with http.MethodPost

pkg/canary/writer/push.go:267:46

266 defer cancel()
267 req, err := http.NewRequestWithContext(ctx, "POST", p.lokiURL, bytes.NewReader(payload))
268 if err != nil {

operator/api/loki/v1beta1/lokistack_types.go1

47:2task-commentFIXME comment should be resolved or linked to an owned work item

operator/api/loki/v1beta1/lokistack_types.go:47:2

46 //
47 // FIXME: Add clear description of ingestion/query performance expectations.
48 SizeOneXSmall LokiStackSizeType = "1x.small"

clients/pkg/logentry/logql/ast.go1

32:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/pkg/logentry/logql/ast.go:32:1

31
32type filterExpr struct {
33 left Expr

clients/pkg/logentry/metric/histograms.go1

62:33unchecked-type-assertionuse the checked two-result form of the type assertion

clients/pkg/logentry/metric/histograms.go:62:33

61func (h *Histograms) With(labels model.LabelSet) prometheus.Histogram {
62 return h.metricVec.With(labels).(prometheus.Histogram)
63}

pkg/logql/log/pattern/lexer.rl.go1

49unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:49

48
49var _pattern_trans_targs []byte = []byte{
50 9, 1, 9, 9, 0, 2, 4, 10,

clients/pkg/logentry/stages/match.go1

143:43unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/match.go:143:43

142
143func (m *matcherStage) Run(in chan Entry) chan Entry {
144 switch m.action {

pkg/storage/factory.go1

351:111unused-parameterparameter registerer is unused

pkg/storage/factory.go:351:111

350// NewChunkClient makes a new chunk.Client of the desired types.
351func NewChunkClient(name, component string, cfg Config, schemaCfg config.SchemaConfig, p config.PeriodConfig, registerer prometheus.Registerer, clientMetrics ClientMetrics, logger log.Logger) (client.Client, error) {
352 var cc congestion.Controller

clients/pkg/logentry/stages/eventlogmessage.go1

141:7unused-receiverreceiver m is unused

clients/pkg/logentry/stages/eventlogmessage.go:141:7

140
141func (m *eventLogMessageStage) Name() string {
142 return StageTypeEventLogMessage

clients/cmd/fluent-bit/config_test.go1

118:26use-anyuse any instead of interface{}

clients/cmd/fluent-bit/config_test.go:118:26

117 dropSingleKey: false,
118 labelMap: map[string]interface{}{
119 "kubernetes": map[string]interface{}{

pkg/canary/reader/reader.go1

287:14use-errors-newreplace fmt.Errorf with errors.New for a static message

pkg/canary/reader/reader.go:287:14

286 if len(series) == 0 {
287 return 0, fmt.Errorf("expected to receive one sample in the result vector, received 0")
288 }

pkg/bloombuild/planner/versioned_range.go1

266:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

pkg/bloombuild/planner/versioned_range.go:266:2

265 // We need to re-sort them by their FP to match the original order.
266 sort.Slice(upToDate, func(i, j int) bool {
267 return upToDate[i].Bounds.Less(upToDate[j].Bounds)

operator/internal/manifests/rules_config_test.go1

43:2var-namingidentifier should use MixedCaps rather than underscores

operator/internal/manifests/rules_config_test.go:43:2

42func TestRulesConfigMapSharding(t *testing.T) {
43 cm_shards, err := RulesConfigMapShards(testOptions_withSharding())
44 require.NoError(t, err)

clients/cmd/fluent-bit/config_test.go1

94:22add-constantstring literal "1s" appears more than twice; define a constant

clients/cmd/fluent-bit/config_test.go:94:22

93 "BatchWait": "30s",
94 "Timeout": "1s",
95 "RemoveKeys": "buzz,fuzz",

pkg/storage/detected/fields_test.go1

93:3call-to-gcavoid explicit garbage collection

pkg/storage/detected/fields_test.go:93:3

92 t.Run("huge limit doesn't explode the heap", func(t *testing.T) {
93 runtime.GC()
94 var before runtime.MemStats

clients/cmd/fluent-bit/loki.go1

157:6cognitive-complexityfunction has cognitive complexity 10; maximum is 7

clients/cmd/fluent-bit/loki.go:157:6

156
157func extractLabels(records map[string]interface{}, keys []string) model.LabelSet {
158 res := model.LabelSet{}

operator/internal/manifests/storage/configure.go1

112:6confusing-namingname configureStatefulSet differs from ConfigureStatefulSet only by capitalization

operator/internal/manifests/storage/configure.go:112:6

111// With this, the statefulset will expose credentials specific environment variable.
112func configureStatefulSet(s *appsv1.StatefulSet, opts Options) error {
113 p := ensureObjectStoreCredentials(&s.Spec.Template.Spec, opts)

pkg/chunkenc/dumb_chunk.go1

29:42confusing-resultsadjacent unnamed results of the same type should be named

pkg/chunkenc/dumb_chunk.go:29:42

28
29func (c *dumbChunk) Bounds() (time.Time, time.Time) {
30 if len(c.entries) == 0 {

pkg/compactor/client/grpc.go1

42:6constructor-interface-returnNewGRPCClient returns interface CompactorClient although its concrete result is consistently *compactorGRPCClient; return the concrete type

pkg/compactor/client/grpc.go:42:6

41// loading delete requests, cache gen numbers for query time filtering and interacting with job queue for horizontal scaling of compactor.
42func NewGRPCClient(addr string, cfg GRPCConfig, r prometheus.Registerer) (CompactorClient, error) {
43 client := &compactorGRPCClient{

pkg/bloomgateway/multiplexing.go1

68:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

pkg/bloomgateway/multiplexing.go:68:2

67 // the context from the request
68 ctx context.Context
69

clients/pkg/logentry/stages/drop.go1

164:21cyclomatic-complexityfunction complexity is 31; maximum is 10

clients/pkg/logentry/stages/drop.go:164:21

163
164func (m *dropStage) shouldDrop(e Entry) bool {
165 // There are many options for dropping a log and if multiple are defined it's treated like an AND condition

operator/cmd/loki-broker/main.go1

83:3deep-exitprocess-exit calls should be confined to main or init

operator/cmd/loki-broker/main.go:83:3

82 log.Info("-object-storage.s3.endpoint flag is required")
83 os.Exit(1)
84 }

pkg/ingester/ingester.go1

1106:4deprecated-api-usagegithub.com/grafana/loki/v3/pkg/logproto.Selector is deprecated: Do not use.

pkg/ingester/ingester.go:1106:4

1105 storeReq := logql.SelectLogParams{QueryRequest: &logproto.QueryRequest{
1106 Selector: req.Selector,
1107 Direction: req.Direction,

clients/cmd/docker-driver/driver.go1

168:5discarded-error-resulterror result returned by level.Error(lf.logger).Log is discarded

clients/cmd/docker-driver/driver.go:168:5

167 if err := lf.jsonl.Log(&msg); err != nil {
168 level.Error(lf.logger).Log("msg", "error writing log message", "id", lf.info.ContainerID, "err", err, "message", msg)
169 continue

clients/cmd/fluent-bit/out_grafana_loki.go1

107:1doc-comment-perioddocumentation comment should end with punctuation

clients/cmd/fluent-bit/out_grafana_loki.go:107:1

106
107//export FLBPluginFlushCtx
108func FLBPluginFlushCtx(ctx, data unsafe.Pointer, length C.int, _ *C.char) int {

cmd/migrate/main.go1

379:7early-returninvert the condition and return early to reduce nesting

cmd/migrate/main.go:379:7

378 err = m.dest.Put(m.ctx, output)
379 if err != nil {
380 if retry == 0 {

clients/pkg/logentry/stages/util_test.go1

75:12error-stringserror string should not be capitalized or end with punctuation

clients/pkg/logentry/stages/util_test.go:75:12

74 if err != nil {
75 t.Errorf("Failed to get string from float... this shouldn't have happened: %v", err)
76 return

pkg/validation/validate.go1

85:6error-type-namingerror implementation type should have an Error suffix

pkg/validation/validate.go:85:6

84
85type ErrStreamRateLimit struct {
86 RateLimit flagext.ByteSize

pkg/limits/store_bench_test.go1

85:5excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

pkg/limits/store_bench_test.go:85:5

84
85 _, _, _, err := s.UpdateCond(tenant, metadata, updateTime)
86 require.NoError(b, err)

clients/cmd/fluent-bit/config.go1

27:6exported-declaration-commentexported type should have a comment beginning with its name

clients/cmd/fluent-bit/config.go:27:6

26
27type ConfigGetter interface {
28 Get(key string) string

operator/api/loki/v1/rulerconfig_types.go1

1:1file-length-limitfile has 561 lines; maximum is 500

operator/api/loki/v1/rulerconfig_types.go:1:1

1package v1
2

operator/internal/manifests/internal/sizes.go1

303:65flag-parameterboolean parameter useRequestsAsLimits controls function flow

operator/internal/manifests/internal/sizes.go:303:65

302// ResourceRequirementsForSize returns the resource configuration for a specific LokiStack size.
303func ResourceRequirementsForSize(size lokiv1.LokiStackSizeType, useRequestsAsLimits bool) ComponentResources {
304 resources := resourceRequirementsTable[size].DeepCopy()

clients/cmd/fluent-bit/dque.go1

1:1formatfile is not formatted

clients/cmd/fluent-bit/dque.go:1:1

1package main
2
  • Fix (safe): run `strider fmt clients/cmd/fluent-bit/dque.go`

clients/pkg/logentry/stages/eventlogmessage_test.go1

46:6function-lengthfunction has 5 statements and 79 lines; maximum is 50 statements or 75 lines

clients/pkg/logentry/stages/eventlogmessage_test.go:46:6

45
46func TestEventLogMessage_simple(t *testing.T) {
47 t.Parallel()

pkg/bloomgateway/util_test.go1

470:6function-result-limitfunction returns 4 values; maximum is 3

pkg/bloomgateway/util_test.go:470:6

469
470func createBlocks(t *testing.T, tenant string, n int, from, through model.Time, minFp, maxFp model.Fingerprint) ([]bloomshipper.BlockRef, []bloomshipper.Meta, []*v1.Block, [][]v1.SeriesWithBlooms) {
471 t.Helper()

clients/pkg/logentry/stages/metrics.go1

337:2identical-switch-branchesswitch repeats a case body

clients/pkg/logentry/stages/metrics.go:337:2

336 return float64(i), nil
337 case uint32:
338 return float64(i), nil

clients/pkg/logentry/stages/extensions_test.go1

12:2import-alias-namingimport alias should contain lower-case letters and digits

clients/pkg/logentry/stages/extensions_test.go:12:2

11
12 util_log "github.com/grafana/loki/v3/pkg/util/log"
13)

clients/pkg/logentry/stages/stage.go1

52:67import-shadowingidentifier time shadows an imported package

clients/pkg/logentry/stages/stage.go:52:67

51type Processor interface {
52 Process(labels model.LabelSet, extracted map[string]interface{}, time *time.Time, entry *string)
53 Name() string

pkg/compactor/retention/util_test.go1

220:3inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

pkg/compactor/retention/util_test.go:220:3

219 if _, ok := t.chunks[chk.UserID][seriesID]; !ok {
220 t.chunks[chk.UserID][seriesID] = []logproto.ChunkRef{}
221 }

pkg/compactor/retention/marker_test.go1

146:40inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.FormatInt with base 10

pkg/compactor/retention/marker_test.go:146:40

145 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.Add(-30*time.Minute).UnixNano())))
146 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.Add(-1*time.Hour).UnixNano())))
147 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.Add(-3*time.Hour).UnixNano())))

cmd/loki/health.go1

13:21insecure-url-schemeURL uses insecure http scheme

cmd/loki/health.go:13:21

12 healthFlag = "health"
13 defaultHealthURL = "http://localhost:3100/ready"
14 healthTimeout = 5 * time.Second

pkg/ingester/ingester.go1

225:16interface-method-limitinterface has 27 methods, exceeding the configured design limit of 10

pkg/ingester/ingester.go:225:16

224// Interface is an interface for the Ingester
225type Interface interface {
226 services.Service

pkg/loghttp/push/otlplabels/config.go1

160:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

pkg/loghttp/push/otlplabels/config.go:160:7

159
160func (c AttributesConfig) MarshalJSON() ([]byte, error) {
161 aux := getMarshableAttributesConfig(c)

cmd/migrate/main.go1

379:7max-control-nestingcontrol-flow nesting exceeds 5 levels

cmd/migrate/main.go:379:7

378 err = m.dest.Put(m.ctx, output)
379 if err != nil {
380 if retry == 0 {

pkg/dataobj/index/indexobj/builder.go1

159:19max-parametersfunction has 9 parameters; maximum is 8

pkg/dataobj/index/indexobj/builder.go:159:19

158// AppendStat records a per-sort-key aggregate for a data object section.
159func (b *Builder) AppendStat(tenantID, objectPath string, sectionIdx int64,
160 sortSchema string, labels map[string]string, minTs, maxTs time.Time, rows int, uncompressedSize int64) error {

operator/api/config/v1/projectconfig_types.go1

184:6max-public-structsfile declares more than 5 exported structs

operator/api/config/v1/projectconfig_types.go:184:6

183// ControllerHealth defines the health configs.
184type ControllerHealth struct {
185 // HealthProbeBindAddress is the TCP address that the controller should bind to

clients/pkg/logentry/logql/parser.go1

99:2modifies-parameterassignment modifies parameter lval

clients/pkg/logentry/logql/parser.go:99:2

98
99 lval.str = l.TokenText()
100 return IDENTIFIER

pkg/bloombuild/planner/versioned_range.go1

137:5modifies-value-receiverassignment modifies value receiver t

pkg/bloombuild/planner/versioned_range.go:137:5

136 tok := tsdbToken{through: bounds.Max, version: version}
137 t = append(t, tsdbToken{})
138 copy(t[i+2:], t[i+1:])

clients/cmd/fluent-bit/loki_test.go1

196:13nested-structsmove nested anonymous struct types to named declarations

clients/cmd/fluent-bit/loki_test.go:196:13

195func Test_extractLabels(t *testing.T) {
196 tests := []struct {
197 name string

pkg/compactor/deletion/deletion_manifest_builder.go1

361:3nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

pkg/compactor/deletion/deletion_manifest_builder.go:361:3

360 } else if objectClient.IsObjectNotFoundErr(err) {
361 return false, nil
362 }

pkg/analytics/stats.go1

289:4nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/analytics/stats.go:289:4

288 }
289 return nil, nil
290 },

pkg/querytee/proxy_test.go1

349:5no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/querytee/proxy_test.go:349:5

348
349 defer res.Body.Close()
350 body, err := io.ReadAll(res.Body)

pkg/compactor/index_set.go1

387:5no-else-after-returnremove else and unindent its body after the return

pkg/compactor/index_set.go:387:5

386 return nil
387 } else {
388 return err

operator/api/loki/v1/lokistack_types.go1

1610:6no-initreplace init with explicit initialization

operator/api/loki/v1/lokistack_types.go:1610:6

1609
1610func init() {
1611 SchemeBuilder.Register(&LokiStack{}, &LokiStackList{})

pkg/dataobj/internal/dataset/page_compress_writer.go1

53:2no-naked-returnreturn values must be explicit

pkg/dataobj/internal/dataset/page_compress_writer.go:53:2

52 c.rawBytes += n
53 return
54}

clients/cmd/fluent-bit/dque.go1

27:5no-package-varpackage variables introduce mutable global state

clients/cmd/fluent-bit/dque.go:27:5

26
27var defaultDqueConfig = dqueConfig{
28 queueDir: filepath.Join(os.TempDir(), "flb-storage/loki"),

pkg/storage/stores/shipper/indexshipper/tsdb/pool.go1

47:13non-pointer-sync-pool-valuestore a pointer-like value in sync.Pool to avoid an allocation during Put

pkg/storage/stores/shipper/indexshipper/tsdb/pool.go:47:13

46 //nolint:staticcheck
47 p.pool.Put(xs)
48}

pkg/compute/filter_bench_test.go1

30:5overwritten-before-usethis value of result is overwritten before use

pkg/compute/filter_bench_test.go:30:5

29 benchAlloc.Reclaim()
30 result, err := compute.Filter(benchAlloc, input, mask)
31 if err != nil {

clients/cmd/fluent-bit/config.go1

1:9package-commentspackage should have a documentation comment

clients/cmd/fluent-bit/config.go:1:9

1package main
2

pkg/dataobj/compaction/v2/output_naming_test.go1

1:9package-directory-mismatchpackage compactionv2 does not match directory v2

pkg/dataobj/compaction/v2/output_naming_test.go:1:9

1package compactionv2
2

clients/pkg/logentry/stages/metrics.go1

151:37range-value-addresstaking the address of range value e can be misleading

clients/pkg/logentry/stages/metrics.go:151:37

150 for e := range in {
151 m.Process(e.Labels, e.Extracted, &e.Timestamp, &e.Line)
152 out <- e

pkg/dataobj/sections/logs/row_predicate_order_test.go1

403:2redefines-builtin-ididentifier max shadows a predeclared identifier

pkg/dataobj/sections/logs/row_predicate_order_test.go:403:2

402 min int64
403 max int64
404}

clients/pkg/logentry/stages/multiline_test.go1

86:19redundant-conversionconversion from model.LabelValue to the identical type is redundant

clients/pkg/logentry/stages/multiline_test.go:86:19

85 require.Equal(t, "START line 1", out[1].Line)
86 require.Equal(t, model.LabelValue("two"), out[1].Labels["value"])
87

operator/api/loki/v1beta1/rulerconfig_types_test.go1

6:2redundant-import-aliasimport alias is identical to the package name

operator/api/loki/v1beta1/rulerconfig_types_test.go:6:2

5
6 v1 "github.com/grafana/loki/operator/api/loki/v1"
7 "github.com/grafana/loki/operator/api/loki/v1beta1"

operator/internal/manifests/openshift/dashboards_test.go1

16:3single-case-switchswitch with one case can be replaced by an if statement

operator/internal/manifests/openshift/dashboards_test.go:16:3

15 for _, d := range objs {
16 switch d.(type) {
17 case *corev1.ConfigMap:

pkg/columnar/concat_test.go1

18:6slice-preallocationpreallocate in with capacity len(range source) before appending once per iteration

pkg/columnar/concat_test.go:18:6

17
18 var in []columnar.Array
19 for _, l := range []int{10, 5, 32} {

pkg/labelaccess/aggregated_metrics_test.go1

144:32standard-http-method-constantreplace the HTTP method literal with http.MethodGet

pkg/labelaccess/aggregated_metrics_test.go:144:32

143 // Create a request with the query
144 req, err := http.NewRequest("GET", "/loki/api/v1/query_range", nil)
145 require.NoError(t, err)

operator/api/loki/v1beta1/lokistack_types.go1

55:2task-commentFIXME comment should be resolved or linked to an owned work item

operator/api/loki/v1beta1/lokistack_types.go:55:2

54 //
55 // FIXME: Add clear description of ingestion/query performance expectations.
56 SizeOneXMedium LokiStackSizeType = "1x.medium"

clients/pkg/logentry/logql/parser.go1

53:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/pkg/logentry/logql/parser.go:53:1

52
53var tokens = map[string]int{
54 ",": COMMA,

clients/pkg/logentry/stages/drop.go1

112:15unchecked-type-assertionuse the checked two-result form of the type assertion

clients/pkg/logentry/stages/drop.go:112:15

111 for i := range s {
112 r[i] = s[i].(string)
113 }

pkg/logql/log/pattern/lexer.rl.go1

54unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:54

53
54var _pattern_trans_actions []byte = []byte{
55 13, 0, 7, 9, 0, 0, 0, 5,

clients/pkg/logentry/stages/metrics.go1

145:42unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/metrics.go:145:42

144
145func (m *metricStage) Run(in chan Entry) chan Entry {
146 out := make(chan Entry)

clients/pkg/logentry/stages/extensions.go1

56:7unused-receiverreceiver c is unused

clients/pkg/logentry/stages/extensions.go:56:7

55// implement Stage interface
56func (c *cri) Name() string {
57 return "cri"

clients/cmd/fluent-bit/config_test.go1

119:31use-anyuse any instead of interface{}

clients/cmd/fluent-bit/config_test.go:119:31

118 labelMap: map[string]interface{}{
119 "kubernetes": map[string]interface{}{
120 "container_name": "container",

pkg/canary/writer/push.go1

87:15use-errors-newreplace fmt.Errorf with errors.New for a static message

pkg/canary/writer/push.go:87:15

86 if logBatchSize < 0 {
87 return nil, fmt.Errorf("logBatchSize must be >= 0")
88 }

pkg/bloomgateway/bloomgateway.go1

385:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

pkg/bloomgateway/bloomgateway.go:385:2

384 // sort responses by fingerprint
385 sort.Slice(responses, func(i, j int) bool { return responses[i].Fp < responses[j].Fp })
386

pkg/compression/codec.go1

19:2var-namingidentifier should use MixedCaps rather than underscores

pkg/compression/codec.go:19:2

18 Dumb // not supported
19 LZ4_64k
20 Snappy

clients/cmd/fluent-bit/config_test.go1

98:22add-constantstring literal "1ms" appears more than twice; define a constant

clients/cmd/fluent-bit/config_test.go:98:22

97 "DropSingleKey": "false",
98 "MinBackoff": "1ms",
99 "MaxBackoff": "5m",

pkg/storage/detected/fields_test.go1

100:3call-to-gcavoid explicit garbage collection

pkg/storage/detected/fields_test.go:100:3

99
100 runtime.GC()
101 var after runtime.MemStats

clients/cmd/fluent-bit/loki.go1

179:6cognitive-complexityfunction has cognitive complexity 13; maximum is 7

clients/cmd/fluent-bit/loki.go:179:6

178// mapLabels convert records into labels using a json map[string]interface{} mapping
179func mapLabels(records map[string]interface{}, mapping map[string]interface{}, res model.LabelSet) {
180 for k, v := range mapping {

pkg/bloombuild/planner/retention_test.go1

734:30confusing-namingname StreamRetention differs from streamRetention only by capitalization

pkg/bloombuild/planner/retention_test.go:734:30

733
734func (m mockRetentionLimits) StreamRetention(tenant string) []validation.StreamRetention {
735 return m.streamRetention[tenant]

pkg/chunkenc/facade.go1

44:38confusing-resultsadjacent unnamed results of the same type should be named

pkg/chunkenc/facade.go:44:38

43
44func (f Facade) Bounds() (time.Time, time.Time) {
45 return f.c.Bounds()

pkg/compactor/client/http.go1

50:6constructor-interface-returnNewHTTPClient returns interface CompactorClient although its concrete result is consistently *compactorHTTPClient; return the concrete type

pkg/compactor/client/http.go:50:6

49// It uses provided TLS config which creating HTTP client.
50func NewHTTPClient(addr string, cfg HTTPConfig) (CompactorClient, error) {
51 u, err := url.Parse(addr)

pkg/compactor/deletion/job_builder.go1

506:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

pkg/compactor/deletion/job_builder.go:506:2

505type storageUpdatesIterator struct {
506 ctx context.Context
507 manifestPath string

clients/pkg/logentry/stages/eventlogmessage.go1

90:32cyclomatic-complexityfunction complexity is 14; maximum is 10

clients/pkg/logentry/stages/eventlogmessage.go:90:32

89// entries into the extracted map
90func (m *eventLogMessageStage) processEntry(extracted map[string]interface{}, key string) error {
91 value, ok := extracted[key]

operator/cmd/loki-broker/main.go1

87:3deep-exitprocess-exit calls should be confined to main or init

operator/cmd/loki-broker/main.go:87:3

86 log.Info("-object-storage.s3.buckets flag is required")
87 os.Exit(1)
88 }

pkg/ingester/ingester.go1

1106:15deprecated-api-usagegithub.com/grafana/loki/v3/pkg/logproto.Selector is deprecated: Do not use.

pkg/ingester/ingester.go:1106:15

1105 storeReq := logql.SelectLogParams{QueryRequest: &logproto.QueryRequest{
1106 Selector: req.Selector,
1107 Direction: req.Direction,

clients/cmd/docker-driver/driver.go1

206:6discarded-error-resulterror result returned by w.Close is discarded

clients/cmd/docker-driver/driver.go:206:6

205 if !ok {
206 w.Close()
207 return

clients/cmd/fluent-bit/out_grafana_loki.go1

154:1doc-comment-perioddocumentation comment should end with punctuation

clients/cmd/fluent-bit/out_grafana_loki.go:154:1

153
154//export FLBPluginExit
155func FLBPluginExit() int {

pkg/bloombuild/planner/planner.go1

550:5early-returninvert the condition and return early to reduce nesting

pkg/bloombuild/planner/planner.go:550:5

549 if err := client.DeleteBlocks(ctx, []bloomshipper.BlockRef{block}); err != nil {
550 if client.IsObjectNotFoundErr(err) {
551 level.Debug(logger).Log("msg", "block not found while attempting delete, continuing")

clients/pkg/logentry/stages/util_test.go1

80:12error-stringserror string should not be capitalized or end with punctuation

clients/pkg/logentry/stages/util_test.go:80:12

79 if err != nil {
80 t.Errorf("Failed to get string from float... this shouldn't have happened: %v", err)
81 return

pkg/limits/store_bench_test.go1

109:6excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

pkg/limits/store_bench_test.go:109:6

108
109 _, _, _, err := s.UpdateCond(tenant, metadata, updateTime)
110 require.NoError(b, err)

clients/pkg/logentry/logql/ast.go1

24:24exported-declaration-commentexported function or method should have a comment beginning with its name

clients/pkg/logentry/logql/ast.go:24:24

23
24func (e *matchersExpr) Matchers() []*labels.Matcher {
25 return e.matchers

operator/api/loki/v1beta1/lokistack_types.go1

1:1file-length-limitfile has 1390 lines; maximum is 500

operator/api/loki/v1beta1/lokistack_types.go:1:1

1package v1beta1
2

operator/internal/manifests/networkpolicy.go1

658:51flag-parameterboolean parameter openShiftEnabled controls function flow

operator/internal/manifests/networkpolicy.go:658:51

657
658func getEndpointPort(storageOpts storage.Options, openShiftEnabled bool) []int32 {
659 // Many self-hosted object storage solutions use S3 API endpoints

clients/cmd/fluent-bit/loki.go1

1:1formatfile is not formatted

clients/cmd/fluent-bit/loki.go:1:1

1package main
2
  • Fix (safe): run `strider fmt clients/cmd/fluent-bit/loki.go`

clients/pkg/logentry/stages/eventlogmessage_test.go1

174:6function-lengthfunction has 5 statements and 102 lines; maximum is 50 statements or 75 lines

clients/pkg/logentry/stages/eventlogmessage_test.go:174:6

173
174func TestEventLogMessage_Real(t *testing.T) {
175 t.Parallel()

pkg/chunkenc/memchunk.go1

1533:29function-result-limitfunction returns 4 values; maximum is 3

pkg/chunkenc/memchunk.go:1533:29

1532// moveNext moves the buffer to the next entry
1533func (si *bufferedIterator) moveNext() (int64, []byte, labels.Labels, bool) {
1534 var decompressedBytes int64

clients/pkg/logentry/stages/metrics.go1

339:2identical-switch-branchesswitch repeats a case body

clients/pkg/logentry/stages/metrics.go:339:2

338 return float64(i), nil
339 case uint:
340 return float64(i), nil

clients/pkg/logentry/stages/json_test.go1

13:2import-alias-namingimport alias should contain lower-case letters and digits

clients/pkg/logentry/stages/json_test.go:13:2

12
13 util_log "github.com/grafana/loki/v3/pkg/util/log"
14)

clients/pkg/logentry/stages/template.go1

106:2import-shadowingidentifier template shadows an imported package

clients/pkg/logentry/stages/template.go:106:2

105 logger log.Logger
106 template *template.Template
107}

pkg/compactor/retention/util_test.go1

278:5inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

pkg/compactor/retention/util_test.go:278:5

277 if _, ok := t.tables[tableName]; !ok {
278 t.tables[tableName] = newTable(tableName)
279 }

pkg/compactor/retention/marker_test.go1

147:40inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.FormatInt with base 10

pkg/compactor/retention/marker_test.go:147:40

146 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.Add(-1*time.Hour).UnixNano())))
147 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.Add(-3*time.Hour).UnixNano())))
148 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.Add(-2*time.Hour).UnixNano())))

integration/cluster/cluster.go1

323:21insecure-url-schemeURL uses insecure http scheme

integration/cluster/cluster.go:323:21

322func (c *Component) HTTPURL() string {
323 return fmt.Sprintf("http://localhost:%s", port(c.loki.Server.HTTPListenAddr().String()))
324}

pkg/ingester/limiter.go1

29:13interface-method-limitinterface has 17 methods, exceeding the configured design limit of 10

pkg/ingester/limiter.go:29:13

28
29type Limits interface {
30 UseOwnedStreamCount(userID string) bool

pkg/loghttp/push/otlplabels/config.go1

165:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

pkg/loghttp/push/otlplabels/config.go:165:7

164
165func (c AttributesConfig) MarshalYAML() (any, error) {
166 return getMarshableAttributesConfig(c), nil

cmd/migrate/main.go1

380:8max-control-nestingcontrol-flow nesting exceeds 5 levels

cmd/migrate/main.go:380:8

379 if err != nil {
380 if retry == 0 {
381 log.Println(threadID, "Final error sending chunks to new store, giving up:", err)

pkg/distributor/distributor.go1

346:6max-parametersfunction has 18 parameters; maximum is 8

pkg/distributor/distributor.go:346:6

345// New a distributor creates.
346func New(
347 cfg Config,

operator/api/config/v1/projectconfig_types.go1

193:6max-public-structsfile declares more than 5 exported structs

operator/api/config/v1/projectconfig_types.go:193:6

192// ControllerWebhook defines the webhook server for the controller.
193type ControllerWebhook struct {
194 // Port is the port that the webhook server serves at.

clients/pkg/logentry/metric/counters.go1

35:2modifies-parameterassignment modifies parameter config

clients/pkg/logentry/metric/counters.go:35:2

34 }
35 config.Action = strings.ToLower(config.Action)
36 if config.Action != CounterInc && config.Action != CounterAdd {

pkg/bloombuild/planner/versioned_range.go1

139:5modifies-value-receiverassignment modifies value receiver t

pkg/bloombuild/planner/versioned_range.go:139:5

138 copy(t[i+2:], t[i+1:])
139 t[i+1] = tok
140 return t, true

clients/cmd/fluent-bit/loki_test.go1

219:13nested-structsmove nested anonymous struct types to named declarations

clients/cmd/fluent-bit/loki_test.go:219:13

218func Test_toStringMap(t *testing.T) {
219 tests := []struct {
220 name string

pkg/compactor/deletion/job_runner.go1

98:5nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

pkg/compactor/deletion/job_runner.go:98:5

97 level.Warn(util_log.Logger).Log("msg", "skipping processing missing chunk", "chunk_id", chunkID)
98 return nil
99 }

pkg/analytics/stats.go1

390:4nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/analytics/stats.go:390:4

389 }
390 return nil, nil
391 },

pkg/ruler/base/client_pool_test.go1

46:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/ruler/base/client_pool_test.go:46:3

45 require.NoError(t, err)
46 defer client.Close() //nolint:errcheck
47

pkg/compactor/index_set_test.go1

92:6no-else-after-returnremove else and unindent its body after the return

pkg/compactor/index_set_test.go:92:6

91 return -1
92 } else if a.GetFrom() > b.GetFrom() {
93 return 1

operator/api/loki/v1/recordingrule_types.go1

118:6no-initreplace init with explicit initialization

operator/api/loki/v1/recordingrule_types.go:118:6

117
118func init() {
119 SchemeBuilder.Register(&RecordingRule{}, &RecordingRuleList{})

pkg/dataobj/internal/dataset/row_reader.go1

961:3no-naked-returnreturn values must be explicit

pkg/dataobj/internal/dataset/row_reader.go:961:3

960 if stats == nil {
961 return
962 }

clients/cmd/fluent-bit/loki.go1

26:2no-package-varpackage variables introduce mutable global state

clients/cmd/fluent-bit/loki.go:26:2

25var (
26 lineReplacer = strings.NewReplacer(`\n`, "\n", `\t`, "\t")
27 keyReplacer = strings.NewReplacer("/", "_", ".", "_", "-", "_")

pkg/compute/filter_bench_test.go1

52:5overwritten-before-usethis value of result is overwritten before use

pkg/compute/filter_bench_test.go:52:5

51 benchAlloc.Reclaim()
52 result, err := compute.Filter(benchAlloc, input, mask)
53 if err != nil {

clients/cmd/fluent-bit/dque.go1

1:9package-commentspackage should have a documentation comment

clients/cmd/fluent-bit/dque.go:1:9

1package main
2

pkg/dataobj/compaction/v2/plan.go1

1:9package-directory-mismatchpackage compactionv2 does not match directory v2

pkg/dataobj/compaction/v2/plan.go:1:9

1package compactionv2
2

clients/pkg/logentry/stages/metrics.go1

151:51range-value-addresstaking the address of range value e can be misleading

clients/pkg/logentry/stages/metrics.go:151:51

150 for e := range in {
151 m.Process(e.Labels, e.Extracted, &e.Timestamp, &e.Line)
152 out <- e

pkg/engine/internal/scheduler/wire/wire_local.go1

39:2redefines-builtin-ididentifier close shadows a predeclared identifier

pkg/engine/internal/scheduler/wire/wire_local.go:39:2

38 alive context.Context
39 close context.CancelFunc
40

clients/pkg/logentry/stages/multiline_test.go1

89:19redundant-conversionconversion from model.LabelValue to the identical type is redundant

clients/pkg/logentry/stages/multiline_test.go:89:19

88 require.Equal(t, "START line 2", out[2].Line)
89 require.Equal(t, model.LabelValue("two"), out[2].Labels["value"])
90

operator/internal/handlers/internal/gateway/cleanup.go1

16:2redundant-import-aliasimport alias is identical to the package name

operator/internal/handlers/internal/gateway/cleanup.go:16:2

15
16 v1 "github.com/grafana/loki/operator/api/loki/v1"
17 "github.com/grafana/loki/operator/internal/external/k8s"

pkg/dataobj/sections/logs/iter.go1

119:4single-case-switchswitch with one case can be replaced by an if statement

pkg/dataobj/sections/logs/iter.go:119:4

118 if columnValue.IsNil() || columnValue.IsZero() {
119 switch column.Type {
120 case ColumnTypeMessage:

pkg/columnar/concat_test.go1

332:7slice-preallocationpreallocate in with capacity len(range source) before appending once per iteration

pkg/columnar/concat_test.go:332:7

331
332 var in []columnar.Array
333 for _, builder := range builders {

pkg/labelaccess/aggregated_metrics_test.go1

292:32standard-http-method-constantreplace the HTTP method literal with http.MethodGet

pkg/labelaccess/aggregated_metrics_test.go:292:32

291 // Create a request with the requisite headers for extracting the policy
292 req, err := http.NewRequest("GET", "/loki/api/v1/query_range", nil)
293 require.NoError(t, err)

operator/internal/controller/loki/alertingrule_controller.go1

34:1task-commentTODO comment should be resolved or linked to an owned work item

operator/internal/controller/loki/alertingrule_controller.go:34:1

33// move the current state of the cluster closer to the desired state.
34// TODO(user): Modify the Reconcile function to compare the state specified by
35// the AlertingRule object against the actual cluster state, and then

clients/pkg/logentry/metric/counters.go1

61:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/pkg/logentry/metric/counters.go:61:1

60// Counters is a vec tor of counters for a each log stream.
61type Counters struct {
62 *metricVec

clients/pkg/logentry/stages/match.go1

124:42unchecked-type-assertionuse the checked two-result form of the type assertion

clients/pkg/logentry/stages/match.go:124:42

123 if existing, ok := err.(prometheus.AlreadyRegisteredError); ok {
124 dropCount = existing.ExistingCollector.(*prometheus.CounterVec)
125 } else {

pkg/logql/log/pattern/lexer.rl.go1

59unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:59

58
59var _pattern_to_state_actions []byte = []byte{
60 0, 0, 0, 0, 0, 0, 0, 0,

clients/pkg/logentry/stages/multiline.go1

101:45unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/multiline.go:101:45

100
101func (m *multilineStage) Run(in chan Entry) chan Entry {
102 out := make(chan Entry)

clients/pkg/logentry/stages/geoip.go1

123:7unused-receiverreceiver g is unused

clients/pkg/logentry/stages/geoip.go:123:7

122// Name implements Stage
123func (g *geoIPStage) Name() string {
124 return StageTypeGeoIP

clients/cmd/fluent-bit/config_test.go1

124:28use-anyuse any instead of interface{}

clients/cmd/fluent-bit/config_test.go:124:28

123 "pod_name": "instance",
124 "labels": map[string]interface{}{
125 "component": "component",

pkg/chunkenc/memchunk.go1

1550:14use-errors-newreplace fmt.Errorf with errors.New for a static message

pkg/chunkenc/memchunk.go:1550:14

1549 if si.readBufValid == lastAttempt { // Got EOF and could not parse same data last time.
1550 si.err = fmt.Errorf("invalid data in chunk")
1551 return 0, nil, labels.EmptyLabels(), false

pkg/bloomgateway/client.go1

242:3use-slices-sortuse slices.Sort or slices.SortFunc when possible

pkg/bloomgateway/client.go:242:3

241
242 sort.Slice(rs.groups, func(i, j int) bool {
243 return rs.groups[i].Fingerprint < rs.groups[j].Fingerprint

pkg/compression/codec.go1

21:2var-namingidentifier should use MixedCaps rather than underscores

pkg/compression/codec.go:21:2

20 Snappy
21 LZ4_256k
22 LZ4_1M

clients/cmd/fluent-bit/config_test.go1

99:22add-constantstring literal "5m" appears more than twice; define a constant

clients/cmd/fluent-bit/config_test.go:99:22

98 "MinBackoff": "1ms",
99 "MaxBackoff": "5m",
100 "MaxRetries": "10",

pkg/storage/detected/fields_test.go1

151:3call-to-gcavoid explicit garbage collection

pkg/storage/detected/fields_test.go:151:3

150 t.Run("huge limit doesn't explode the heap", func(t *testing.T) {
151 runtime.GC()
152 var before runtime.MemStats

clients/cmd/fluent-bit/loki.go1

221:16cognitive-complexityfunction has cognitive complexity 28; maximum is 7

clients/cmd/fluent-bit/loki.go:221:16

220
221func (l *loki) createLine(records map[string]interface{}, f format) (string, error) {
222 switch f {

pkg/bloomgateway/multiplexing.go1

102:15confusing-namingname Done differs from done only by capitalization

pkg/bloomgateway/multiplexing.go:102:15

101
102func (t Task) Done() <-chan struct{} {
103 return t.done

pkg/chunkenc/memchunk.go1

184:39confusing-resultsadjacent unnamed results of the same type should be named

pkg/chunkenc/memchunk.go:184:39

183
184func (hb *headBlock) Bounds() (int64, int64) { return hb.mint, hb.maxt }
185

pkg/compactor/deletion/delete_requests_client.go1

47:6constructor-interface-returnNewDeleteRequestsClient returns interface DeleteRequestsClient although its concrete result is consistently *deleteRequestsClient; return the concrete type

pkg/compactor/deletion/delete_requests_client.go:47:6

46
47func NewDeleteRequestsClient(compactorClient CompactorClient, deleteClientMetrics *DeleteRequestClientMetrics, clientType string, opts ...DeleteRequestsStoreOption) (DeleteRequestsClient, error) {
48 client := &deleteRequestsClient{

pkg/compactor/index_set.go1

67:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

pkg/compactor/index_set.go:67:2

66type indexSet struct {
67 ctx context.Context
68 tableName, userID string

clients/pkg/logentry/stages/eventlogmessage.go1

152:6cyclomatic-complexityfunction complexity is 11; maximum is 10

clients/pkg/logentry/stages/eventlogmessage.go:152:6

151// TODO: switch to prometheus/prometheus/util/strutil/SanitizeFullLabelName
152func SanitizeFullLabelName(input string) string {
153 if len(input) == 0 {

operator/cmd/loki-broker/main.go1

92:3deep-exitprocess-exit calls should be confined to main or init

operator/cmd/loki-broker/main.go:92:3

91 log.Info("-with-prometheus-alerts flag requires -with-service-monitors")
92 os.Exit(1)
93 }

pkg/ingester/ingester.go1

1143:41deprecated-api-usagegithub.com/grafana/loki/v3/pkg/logproto.Selector is deprecated: Do not use.

pkg/ingester/ingester.go:1143:41

1142 if req.Plan == nil {
1143 parsed, err := syntax.ParseSampleExpr(req.Selector)
1144 if err != nil {

clients/cmd/docker-driver/driver.go1

216:10discarded-error-resulterror result returned by w.CloseWithError is discarded

clients/cmd/docker-driver/driver.go:216:10

215 if err := enc.Encode(&buf); err != nil {
216 _ = w.CloseWithError(err)
217 return

clients/pkg/logentry/metric/counters.go1

114:1doc-comment-perioddocumentation comment should end with punctuation

clients/pkg/logentry/metric/counters.go:114:1

113
114// HasExpired implements Expirable
115func (e *expiringCounter) HasExpired(currentTimeSec int64, maxAgeSec int64) bool {

pkg/bloombuild/planner/planner.go1

564:4early-returninvert the condition and return early to reduce nesting

pkg/bloombuild/planner/planner.go:564:4

563 if err != nil {
564 if client.IsObjectNotFoundErr(err) {
565 level.Debug(logger).Log("msg", "meta not found while attempting delete, continuing", "meta", meta.String())

clients/pkg/logentry/stages/util_test.go1

85:12error-stringserror string should not be capitalized or end with punctuation

clients/pkg/logentry/stages/util_test.go:85:12

84 if err != nil {
85 t.Errorf("Failed to get string from float... this shouldn't have happened: %v", err)
86 return

pkg/limits/store_bench_test.go1

131:6excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

pkg/limits/store_bench_test.go:131:6

130
131 _, _, _, err := s.UpdateCond(tenant, metadata, updateTime)
132 require.NoError(b, err)

clients/pkg/logentry/logql/ast.go1

28:24exported-declaration-commentexported function or method should have a comment beginning with its name

clients/pkg/logentry/logql/ast.go:28:24

27
28func (e *matchersExpr) Filter() (Filter, error) {
29 return nil, nil

operator/api/loki/v1beta1/lokistack_types_test.go1

1:1file-length-limitfile has 1268 lines; maximum is 500

operator/api/loki/v1beta1/lokistack_types_test.go:1:1

1package v1beta1_test
2

operator/internal/manifests/openshift/configure.go1

146:70flag-parameterboolean parameter withTLS controls function flow

operator/internal/manifests/openshift/configure.go:146:70

145// the sidecar metrics.
146func ConfigureGatewayServiceMonitor(sm *monitoringv1.ServiceMonitor, withTLS bool) error {
147 var opaEndpoint monitoringv1.Endpoint

clients/cmd/fluent-bit/loki_test.go1

1:1formatfile is not formatted

clients/cmd/fluent-bit/loki_test.go:1:1

1//go:build cgo
2
  • Fix (safe): run `strider fmt clients/cmd/fluent-bit/loki_test.go`

clients/pkg/logentry/stages/extensions_test.go1

96:6function-lengthfunction has 3 statements and 123 lines; maximum is 50 statements or 75 lines

clients/pkg/logentry/stages/extensions_test.go:96:6

95
96func TestCRI_tags(t *testing.T) {
97 cases := []struct {

pkg/dataobj/index/builder_test.go1

536:30function-result-limitfunction returns 4 values; maximum is 3

pkg/dataobj/index/builder_test.go:536:30

535
536func (c *blockingCalculator) Flush() (*dataobj.Object, io.Closer, []multitenancy.TimeRange, error) {
537 return nil, nil, nil, fmt.Errorf("unexpected flush")

clients/pkg/logentry/stages/util.go1

183:2identical-switch-branchesswitch repeats a case body

clients/pkg/logentry/stages/util.go:183:2

182 return strconv.FormatUint(uint64(i), 10), nil
183 case uint:
184 return strconv.FormatUint(uint64(i), 10), nil

clients/pkg/logentry/stages/labelallow_test.go1

12:2import-alias-namingimport alias should contain lower-case letters and digits

clients/pkg/logentry/stages/labelallow_test.go:12:2

11
12 util_log "github.com/grafana/loki/v3/pkg/util/log"
13)

clients/pkg/util/client.go1

388:2import-shadowingidentifier backoff shadows an imported package

clients/pkg/util/client.go:388:2

387
388 backoff := backoff.New(c.ctx, c.cfg.BackoffConfig)
389 var status int

pkg/dataobj/consumer/logsobj/builder.go1

270:3inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

pkg/dataobj/consumer/logsobj/builder.go:270:3

269 sb.SetTenant(tenant)
270 b.streams[tenant] = sb
271 }

pkg/compactor/retention/marker_test.go1

148:40inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.FormatInt with base 10

pkg/compactor/retention/marker_test.go:148:40

147 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.Add(-3*time.Hour).UnixNano())))
148 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.Add(-2*time.Hour).UnixNano())))
149 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.Add(-48*time.Hour).UnixNano())))

integration/cluster/cluster.go1

465:38insecure-url-schemeURL uses insecure http scheme

integration/cluster/cluster.go:465:38

464
465 req := httptest.NewRequest("GET", "http://localhost/ready", nil)
466 w := httptest.NewRecorder()

pkg/logcli/client/client.go1

55:13interface-method-limitinterface has 14 methods, exceeding the configured design limit of 10

pkg/logcli/client/client.go:55:13

54// Client contains all the methods to query a Loki instance, it's an interface to allow multiple implementations.
55type Client interface {
56 Query(queryStr string, limit int, time time.Time, direction logproto.Direction, quiet bool) (*loghttp.QueryResponse, error)

pkg/loghttp/query.go1

402:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

pkg/loghttp/query.go:402:7

401
402func (s *Scalar) UnmarshalJSON(b []byte) error {
403 var v model.Scalar

operator/internal/handlers/internal/networkpolicy/service.go1

133:7max-control-nestingcontrol-flow nesting exceeds 5 levels

operator/internal/handlers/internal/networkpolicy/service.go:133:7

132 case intstr.Int:
133 if p.Port != nil && *p.Port == svcPort.TargetPort.IntVal {
134 return *p.Port

pkg/distributor/http_test.go1

173:22max-parametersfunction has 9 parameters; maximum is 8

pkg/distributor/http_test.go:173:22

172
173func (p *fakeParser) parseRequest(
174 _ string,

operator/api/config/v1/projectconfig_types.go1

203:6max-public-structsfile declares more than 5 exported structs

operator/api/config/v1/projectconfig_types.go:203:6

202// ControllerManagerConfiguration is the Schema for the GenericControllerManagerConfigurations API.
203type ControllerManagerConfiguration struct {
204 metav1.TypeMeta `json:",inline"`

clients/pkg/logentry/metric/gauges.go1

33:2modifies-parameterassignment modifies parameter config

clients/pkg/logentry/metric/gauges.go:33:2

32 }
33 config.Action = strings.ToLower(config.Action)
34 if config.Action != GaugeSet &&

pkg/bloombuild/planner/versioned_range.go1

146:4modifies-value-receiverassignment modifies value receiver t

pkg/bloombuild/planner/versioned_range.go:146:4

145 tok := tsdbToken{through: bounds.Max, version: version}
146 t = append(t, tsdbToken{}, tsdbToken{})
147 copy(t[i+2:], t[i:])

clients/cmd/fluent-bit/loki_test.go1

242:13nested-structsmove nested anonymous struct types to named declarations

clients/cmd/fluent-bit/loki_test.go:242:13

241func Test_labelMapping(t *testing.T) {
242 tests := []struct {
243 name string

pkg/compactor/deletion/job_runner.go1

136:5nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

pkg/compactor/deletion/job_runner.go:136:5

135 updates.RebuiltChunks[chunkID] = nil
136 return nil
137 }

pkg/analytics/stats.go1

449:4nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/analytics/stats.go:449:4

448 }
449 return nil, nil
450 },

pkg/storage/chunk/client/ibmcloud/cos_object_client_test.go1

276:4no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/storage/chunk/client/ibmcloud/cos_object_client_test.go:276:4

275 require.NoError(t, err)
276 defer os.Remove(file.Name())
277

pkg/compactor/table_test.go1

619:8no-else-after-returnremove else and unindent its body after the return

pkg/compactor/table_test.go:619:8

618 return -1
619 } else if a.GetFrom() > b.GetFrom() {
620 return 1

operator/api/loki/v1/rulerconfig_types.go1

555:6no-initreplace init with explicit initialization

operator/api/loki/v1/rulerconfig_types.go:555:6

554
555func init() {
556 SchemeBuilder.Register(&RulerConfig{}, &RulerConfigList{})

pkg/dataobj/internal/dataset/row_reader.go1

969:2no-naked-returnreturn values must be explicit

pkg/dataobj/internal/dataset/row_reader.go:969:2

968 }
969 return
970}

clients/cmd/fluent-bit/loki.go1

27:2no-package-varpackage variables introduce mutable global state

clients/cmd/fluent-bit/loki.go:27:2

26 lineReplacer = strings.NewReplacer(`\n`, "\n", `\t`, "\t")
27 keyReplacer = strings.NewReplacer("/", "_", ".", "_", "-", "_")
28)

pkg/compute/filter_bench_test.go1

74:5overwritten-before-usethis value of result is overwritten before use

pkg/compute/filter_bench_test.go:74:5

73 benchAlloc.Reclaim()
74 result, err := compute.Filter(benchAlloc, input, mask)
75 if err != nil {

clients/cmd/fluent-bit/loki.go1

1:9package-commentspackage should have a documentation comment

clients/cmd/fluent-bit/loki.go:1:9

1package main
2

pkg/dataobj/compaction/v2/plan_test.go1

1:9package-directory-mismatchpackage compactionv2 does not match directory v2

pkg/dataobj/compaction/v2/plan_test.go:1:9

1package compactionv2
2

operator/api/loki/v1beta1/alertingrule_types.go1

156:15range-value-addresstaking the address of range value r can be misleading

operator/api/loki/v1beta1/alertingrule_types.go:156:15

155 for j, r := range sRules {
156 rules[j] = &v1.AlertingRuleGroupSpec{
157 Alert: r.Alert,

pkg/engine/internal/scheduler/wire/wire_local.go1

132:2redefines-builtin-ididentifier close shadows a predeclared identifier

pkg/engine/internal/scheduler/wire/wire_local.go:132:2

131 alive context.Context
132 close context.CancelFunc
133

clients/pkg/logentry/stages/multiline_test.go1

92:19redundant-conversionconversion from model.LabelValue to the identical type is redundant

clients/pkg/logentry/stages/multiline_test.go:92:19

91 require.Equal(t, "START line 2\nnot a start line 1", out[3].Line)
92 require.Equal(t, model.LabelValue("one"), out[3].Labels["value"])
93}

operator/internal/handlers/internal/rules/cleanup.go1

14:2redundant-import-aliasimport alias is identical to the package name

operator/internal/handlers/internal/rules/cleanup.go:14:2

13
14 v1 "github.com/grafana/loki/operator/api/loki/v1"
15 "github.com/grafana/loki/operator/internal/external/k8s"

pkg/distributor/distributor.go1

1539:4single-case-switchswitch with one case can be replaced by an if statement

pkg/distributor/distributor.go:1539:4

1538 if e, ok := status.FromError(err); ok {
1539 switch e.Code() {
1540 case codes.DeadlineExceeded:

pkg/compactor/deletion/delete_request.go1

219:6slice-preallocationpreallocate result with capacity len(range source) before appending once per iteration

pkg/compactor/deletion/delete_request.go:219:6

218 }
219 var result []string
220 for _, m := range d.matchers {

pkg/logcli/client/client.go1

337:30standard-http-method-constantreplace the HTTP method literal with http.MethodGet

pkg/logcli/client/client.go:337:30

336
337 req, err := http.NewRequest("GET", us, nil)
338 if err != nil {

operator/internal/controller/loki/recordingrule_controller.go1

34:1task-commentTODO comment should be resolved or linked to an owned work item

operator/internal/controller/loki/recordingrule_controller.go:34:1

33// move the current state of the cluster closer to the desired state.
34// TODO(user): Modify the Reconcile function to compare the state specified by
35// the RecordingRule object against the actual cluster state, and then

clients/pkg/logentry/metric/gauges.go1

54:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/pkg/logentry/metric/gauges.go:54:1

53// Gauges is a vector of gauges for a each log stream.
54type Gauges struct {
55 *metricVec

clients/pkg/logentry/stages/metrics_test.go1

444:52unchecked-type-assertionuse the checked two-result form of the type assertion

clients/pkg/logentry/stages/metrics_test.go:444:52

443 }
444 assert.Equal(t, int64(5*time.Minute.Seconds()), ms.(*metricStage).cfg["total_keys"].maxIdleSec)
445}

pkg/logql/log/pattern/lexer.rl.go1

64unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:64

63
64var _pattern_from_state_actions []byte = []byte{
65 0, 0, 0, 0, 0, 0, 0, 0,

clients/pkg/logentry/stages/pack.go1

151:40unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/pack.go:151:40

150
151func (m *packStage) Run(in chan Entry) chan Entry {
152 out := make(chan Entry)

clients/pkg/logentry/stages/geoip.go1

254:7unused-receiverreceiver g is unused

clients/pkg/logentry/stages/geoip.go:254:7

253
254func (g *geoIPStage) populateLabelsWithASNData(labels model.LabelSet, record *geoip2.ASN) {
255 autonomousSystemNumber := record.AutonomousSystemNumber

clients/cmd/fluent-bit/dque.go1

40:25use-anyuse any instead of interface{}

clients/cmd/fluent-bit/dque.go:40:25

39
40func dqueEntryBuilder() interface{} {
41 return &dqueEntry{}

pkg/chunkenc/memchunk.go1

1623:14use-errors-newreplace fmt.Errorf with errors.New for a static message

pkg/chunkenc/memchunk.go:1623:14

1622 if si.readBufValid == lastAttempt { // Got EOF and could not parse same data last time.
1623 si.err = fmt.Errorf("invalid data in chunk")
1624 return 0, nil, labels.EmptyLabels(), false

pkg/bloomgateway/client.go1

295:3use-slices-sortuse slices.Sort or slices.SortFunc when possible

pkg/bloomgateway/client.go:295:3

294 for _, inp := range input {
295 sort.Slice(inp, func(i, j int) bool { return inp[i].Fingerprint < inp[j].Fingerprint })
296 iters = append(iters, iter.NewPeekIter(iter.NewSliceIter(inp)))

pkg/compression/codec.go1

22:2var-namingidentifier should use MixedCaps rather than underscores

pkg/compression/codec.go:22:2

21 LZ4_256k
22 LZ4_1M
23 LZ4_4M

clients/cmd/fluent-bit/config_test.go1

109:40add-constantstring literal "30s" appears more than twice; define a constant

clients/cmd/fluent-bit/config_test.go:109:40

108 BatchSize: 100,
109 BatchWait: mustParseDuration("30s"),
110 Timeout: mustParseDuration("1s"),

pkg/storage/detected/fields_test.go1

159:3call-to-gcavoid explicit garbage collection

pkg/storage/detected/fields_test.go:159:3

158
159 runtime.GC()
160 var after runtime.MemStats

clients/cmd/fluent-bit/out_grafana_loki.go1

108:6cognitive-complexityfunction has cognitive complexity 9; maximum is 7

clients/cmd/fluent-bit/out_grafana_loki.go:108:6

107//export FLBPluginFlushCtx
108func FLBPluginFlushCtx(ctx, data unsafe.Pointer, length C.int, _ *C.char) int {
109 plugin := output.FLBPluginGetContext(ctx).(*loki)

pkg/bloomgateway/multiplexing.go1

106:15confusing-namingname Err differs from err only by capitalization

pkg/bloomgateway/multiplexing.go:106:15

105
106func (t Task) Err() error {
107 return t.err.err

pkg/chunkenc/unordered.go1

83:48confusing-resultsadjacent unnamed results of the same type should be named

pkg/chunkenc/unordered.go:83:48

82
83func (hb *unorderedHeadBlock) Bounds() (int64, int64) {
84 return hb.mint, hb.maxt

pkg/compactor/deletion/delete_requests_client.go1

152:6constructor-interface-returnNewNoOpDeleteRequestsClient returns interface DeleteRequestsClient although its concrete result is consistently *noOpDeleteRequestsClient; return the concrete type

pkg/compactor/deletion/delete_requests_client.go:152:6

151
152func NewNoOpDeleteRequestsClient() DeleteRequestsClient {
153 return &noOpDeleteRequestsClient{}

pkg/compactor/retention/marker.go1

160:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

pkg/compactor/retention/marker.go:160:2

159
160 ctx context.Context
161 cancel context.CancelFunc

clients/pkg/logentry/stages/geoip.go1

132:22cyclomatic-complexityfunction complexity is 14; maximum is 10

clients/pkg/logentry/stages/geoip.go:132:22

131
132func (g *geoIPStage) process(labels model.LabelSet, extracted map[string]interface{}, _ *time.Time, _ *string) {
133 var ip net.IP

operator/internal/controller/loki/lokistack_controller_test.go1

51:2deep-exitprocess-exit calls should be confined to main or init

operator/internal/controller/loki/lokistack_controller_test.go:51:2

50
51 os.Exit(m.Run())
52}

pkg/ingester/ingester.go1

1172:32deprecated-api-usagegithub.com/grafana/loki/v3/pkg/logproto.Selector is deprecated: Do not use.

pkg/ingester/ingester.go:1172:32

1171 sp.AddEvent("finished instance query sample", trace.WithAttributes(
1172 attribute.String("selector", req.Selector),
1173 attribute.String("start", req.Start.String()),

clients/cmd/docker-driver/driver.go1

220:9discarded-error-resulterror result returned by w.CloseWithError is discarded

clients/cmd/docker-driver/driver.go:220:9

219 case err := <-watcher.Err:
220 _ = w.CloseWithError(err)
221 return

clients/pkg/logentry/metric/gauges.go1

114:1doc-comment-perioddocumentation comment should end with punctuation

clients/pkg/logentry/metric/gauges.go:114:1

113// Add adds the given value to the Gauge. (The value can be negative,
114// resulting in a decrease of the Gauge.)
115func (g *expiringGauge) Add(val float64) {

pkg/compactor/retention/retention.go1

347:3early-returninvert the condition and return early to reduce nesting

pkg/compactor/retention/retention.go:347:3

346 if err != nil {
347 if errors.Is(err, context.DeadlineExceeded) && errors.Is(iterCtx.Err(), context.DeadlineExceeded) {
348 // Deletes timed out. Don't return an error so compaction can continue and deletes can be retried

integration/loki_rule_eval_test.go1

126:14error-stringserror string should not be capitalized or end with punctuation

integration/loki_rule_eval_test.go:126:14

125 if r.URL.Path != "/api/v1/write" {
126 t.Errorf("Expected to request '/api/v1/write', got: %s", r.URL.Path)
127 }

pkg/logqlanalyzer/analyzer.go1

121:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

pkg/logqlanalyzer/analyzer.go:121:2

120 stream := log.NewStreamPipeline(stageRecorders, p.origin.LabelsBuilder().ForLabels(p.streamLabels, labels.StableHash(p.streamLabels)))
121 _, _, _ = stream.ProcessString(time.Now().UnixMilli(), line, labels.EmptyLabels())
122 return records

clients/pkg/logentry/logql/ast.go1

38:22exported-declaration-commentexported function or method should have a comment beginning with its name

clients/pkg/logentry/logql/ast.go:38:22

37
38func (e *filterExpr) Matchers() []*labels.Matcher {
39 return e.left.Matchers()

operator/api/loki/v1beta1/rulerconfig_types.go1

1:1file-length-limitfile has 1002 lines; maximum is 500

operator/api/loki/v1beta1/rulerconfig_types.go:1:1

1package v1beta1
2

operator/internal/manifests/openshift/configure.go1

249:50flag-parameterboolean parameter am controls function flow

operator/internal/manifests/openshift/configure.go:249:50

248// ConfigureOptions applies default configuration for the use of the cluster monitoring alertmanager.
249func ConfigureOptions(configOpt *config.Options, am, uwam bool, token, caPath, monitorServerName string) error {
250 if am {

clients/cmd/fluent-bit/out_grafana_loki.go1

1:1formatfile is not formatted

clients/cmd/fluent-bit/out_grafana_loki.go:1:1

1package main
2
  • Fix (safe): run `strider fmt clients/cmd/fluent-bit/out_grafana_loki.go`

clients/pkg/logentry/stages/json.go1

110:21function-lengthfunction has 41 statements and 76 lines; maximum is 50 statements or 75 lines

clients/pkg/logentry/stages/json.go:110:21

109
110func (j *jsonStage) processEntry(extracted map[string]interface{}, entry *string) error {
111 // If a source key is provided, the json stage should process it

pkg/dataobj/index/calculate.go1

116:22function-result-limitfunction returns 4 values; maximum is 3

pkg/dataobj/index/calculate.go:116:22

115// add the reprocessed bytes on top of the stale count.
116func (c *Calculator) Flush() (*dataobj.Object, io.Closer, []multitenancy.TimeRange, error) {
117 ranges := c.TimeRanges()

operator/internal/manifests/build_test.go1

422:3identical-switch-branchesswitch repeats a case body

operator/internal/manifests/build_test.go:422:3

421 lps = o.Spec.Template.Spec.Containers[0].LivenessProbe.HTTPGet.Scheme
422 case *appsv1.StatefulSet:
423 name = o.Name

clients/pkg/logentry/stages/labeldrop_test.go1

12:2import-alias-namingimport alias should contain lower-case letters and digits

clients/pkg/logentry/stages/labeldrop_test.go:12:2

11
12 util_log "github.com/grafana/loki/v3/pkg/util/log"
13)

cmd/logcli/main.go1

556:2import-shadowingidentifier client shadows an imported package

cmd/logcli/main.go:556:2

555
556 client := &client.DefaultClient{
557 TLSConfig: config.TLSConfig{},

pkg/dataobj/consumer/logsobj/builder.go1

310:3inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

pkg/dataobj/consumer/logsobj/builder.go:310:3

309 lb.SetTenant(tenant)
310 b.logs[tenant] = lb
311 }

pkg/compactor/retention/marker_test.go1

149:40inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.FormatInt with base 10

pkg/compactor/retention/marker_test.go:149:40

148 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.Add(-2*time.Hour).UnixNano())))
149 _, _ = os.Create(filepath.Join(dir, fmt.Sprintf("%d", now.Add(-48*time.Hour).UnixNano())))
150 return []string{

operator/api/loki/v1beta1/lokistack_types_test.go1

220:25insecure-url-schemeURL uses insecure http scheme

operator/api/loki/v1beta1/lokistack_types_test.go:220:25

219 },
220 IssuerURL: "http://go-to-issuer",
221 RedirectURL: "http://bring-me-back",

pkg/logql/evaluator.go1

40:13interface-method-limitinterface has 11 methods, exceeding the configured design limit of 10

pkg/logql/evaluator.go:40:13

39// Params details the parameters associated with a loki request
40type Params interface {
41 QueryString() string

pkg/logproto/compat.go1

167:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

pkg/logproto/compat.go:167:7

166// UnmarshalJSON implements json.Unmarshaler.
167func (s *LegacySample) UnmarshalJSON(b []byte) error {
168 var t model.Time

operator/internal/handlers/internal/networkpolicy/service.go1

137:7max-control-nestingcontrol-flow nesting exceeds 5 levels

operator/internal/handlers/internal/networkpolicy/service.go:137:7

136 case intstr.String:
137 if p.Name != nil && *p.Name == svcPort.TargetPort.StrVal {
138 return *p.Port

pkg/distributor/validator.go1

206:20max-parametersfunction has 9 parameters; maximum is 8

pkg/distributor/validator.go:206:20

205
206func (v Validator) reportDiscardedDataWithTracker(ctx context.Context, reason string, vCtx validationContext, labels labels.Labels, retentionHours string, policy string, entrySize, entryCount int, format string) {
207 v.reportDiscardedData(reason, vCtx, retentionHours, policy, entrySize, entryCount, format)

operator/api/config/v1/projectconfig_types.go1

218:6max-public-structsfile declares more than 5 exported structs

operator/api/config/v1/projectconfig_types.go:218:6

217// ProjectConfig is the Schema for the projectconfigs API
218type ProjectConfig struct {
219 metav1.TypeMeta `json:",inline"`

clients/pkg/logentry/stages/drop.go1

60:3modifies-parameterassignment modifies parameter cfg

clients/pkg/logentry/stages/drop.go:60:3

59 }
60 cfg.source = &src
61 }

pkg/bloombuild/planner/versioned_range.go1

148:4modifies-value-receiverassignment modifies value receiver t

pkg/bloombuild/planner/versioned_range.go:148:4

147 copy(t[i+2:], t[i:])
148 t[i+1] = tok
149 t[i].through = bounds.Min - 1

clients/cmd/fluent-bit/loki_test.go1

311:13nested-structsmove nested anonymous struct types to named declarations

clients/cmd/fluent-bit/loki_test.go:311:13

310func Test_AutoKubernetesLabels(t *testing.T) {
311 tests := []struct {
312 name string

pkg/compactor/retention/retention.go1

512:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

pkg/compactor/retention/retention.go:512:4

511 level.Info(util_log.Logger).Log("msg", "Delete request filterFunc leaves an empty chunk", "chunk ref", ce.ChunkID)
512 return false, true, nil
513 }

pkg/bloombuild/protos/compat.go1

53:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/bloombuild/protos/compat.go:53:3

52 if task == nil {
53 return nil, nil
54 }

pkg/storage/chunk/client/ibmcloud/trusted_profile_authentication_provider_test.go1

61:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/storage/chunk/client/ibmcloud/trusted_profile_authentication_provider_test.go:61:3

60 mockAuthServer := mockAuthServer(tt.token, tokenType)
61 defer mockAuthServer.Close()
62

pkg/compactor/table_test.go1

663:8no-else-after-returnremove else and unindent its body after the return

pkg/compactor/table_test.go:663:8

662 return -1
663 } else if a.GetFrom() > b.GetFrom() {
664 return 1

operator/api/loki/v1beta1/alertingrule_types.go1

134:6no-initreplace init with explicit initialization

operator/api/loki/v1beta1/alertingrule_types.go:134:6

133
134func init() {
135 SchemeBuilder.Register(&AlertingRule{}, &AlertingRuleList{})

pkg/dataobj/internal/dataset/value_encoding_bitmap_test.go1

392:2no-naked-returnreturn values must be explicit

pkg/dataobj/internal/dataset/value_encoding_bitmap_test.go:392:2

391 w.n += int64(n)
392 return
393}

clients/cmd/fluent-bit/loki_test.go1

19:5no-package-varpackage variables introduce mutable global state

clients/cmd/fluent-bit/loki_test.go:19:5

18
19var now = time.Now()
20

pkg/compute/logical_bench_test.go1

24:5overwritten-before-usethis value of result is overwritten before use

pkg/compute/logical_bench_test.go:24:5

23 benchAlloc.Reclaim()
24 result, err := compute.And(benchAlloc, left, right, selection)
25 if err != nil {

clients/cmd/fluent-bit/out_grafana_loki.go1

1:9package-commentspackage should have a documentation comment

clients/cmd/fluent-bit/out_grafana_loki.go:1:9

1package main
2

pkg/dataobj/compaction/v2/result_record.go1

1:9package-directory-mismatchpackage compactionv2 does not match directory v2

pkg/dataobj/compaction/v2/result_record.go:1:9

1package compactionv2
2

operator/api/loki/v1beta1/alertingrule_types.go1

165:24range-value-addresstaking the address of range value g can be misleading

operator/api/loki/v1beta1/alertingrule_types.go:165:24

164
165 dst.Spec.Groups[i] = &v1.AlertingRuleGroup{
166 Name: g.Name,

pkg/engine/internal/util/queue/fair/fair.go1

48:2redefines-builtin-ididentifier len shadows a predeclared identifier

pkg/engine/internal/util/queue/fair/fair.go:48:2

47
48 len int
49 root node[T]

clients/pkg/logentry/stages/sampling.go1

18:27redundant-conversionconversion from uint64 to the identical type is redundant

clients/pkg/logentry/stages/sampling.go:18:27

17)
18const maxRandomNumber = ^(uint64(1) << 63) // i.e. 0x7fffffffffffffff
19

operator/internal/manifests/ingester_test.go1

12:2redundant-import-aliasimport alias is identical to the package name

operator/internal/manifests/ingester_test.go:12:2

11
12 v1 "github.com/grafana/loki/operator/api/config/v1"
13 lokiv1 "github.com/grafana/loki/operator/api/loki/v1"

pkg/engine/handler.go1

452:3single-case-switchswitch with one case can be replaced by an if statement

pkg/engine/handler.go:452:3

451 sampleExpr.Walk(func(e syntax.Expr) bool {
452 switch rangeExpr := e.(type) {
453 case *syntax.LogRangeExpr:

pkg/compactor/deletion/delete_request_batch.go1

108:6slice-preallocationpreallocate filterFuncs with capacity len(range source) before appending once per iteration

pkg/compactor/deletion/delete_request_batch.go:108:6

107
108 var filterFuncs []filter.Func
109

pkg/logcli/client/client.go1

439:30standard-http-method-constantreplace the HTTP method literal with http.MethodPost

pkg/logcli/client/client.go:439:30

438
439 req, err := http.NewRequest("POST", us, nil)
440 if err != nil {

operator/internal/handlers/internal/gateway/gateway.go1

99:3task-commentTODO comment should be resolved or linked to an owned work item

operator/internal/handlers/internal/gateway/gateway.go:99:3

98 if !httpEncryption {
99 // TODO(JoaoBraveCoding): Discuss with @xperimental if this makes sense or if we should always require
100 // mTLS with the client

clients/pkg/logentry/metric/histograms.go1

30:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/pkg/logentry/metric/histograms.go:30:1

29// Histograms is a vector of histograms for a each log stream.
30type Histograms struct {
31 *metricVec

clients/pkg/logentry/stages/pipeline_test.go1

88:34unchecked-type-assertionuse the checked two-result form of the type assertion

clients/pkg/logentry/stages/pipeline_test.go:88:34

87 }
88 return config["pipeline_stages"].([]interface{})
89}

pkg/logql/log/pattern/lexer.rl.go1

69unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:69

68
69var _pattern_eof_trans []byte = []byte{
70 0, 1, 0, 0, 0, 0, 0, 0,

clients/pkg/logentry/stages/pipeline.go1

69:61unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/pipeline.go:69:61

68// RunWith will reads from the input channel entries, mutate them with the process function and returns them via the output channel.
69func RunWith(input chan Entry, process func(e Entry) Entry) chan Entry {
70 out := make(chan Entry)

clients/pkg/logentry/stages/json.go1

188:7unused-receiverreceiver j is unused

clients/pkg/logentry/stages/json.go:188:7

187// Name implements Stage
188func (j *jsonStage) Name() string {
189 return StageTypeJSON

clients/cmd/fluent-bit/loki.go1

49:33use-anyuse any instead of interface{}

clients/cmd/fluent-bit/loki.go:49:33

48// sendRecord send fluentbit records to loki as an entry.
49func (l *loki) sendRecord(r map[interface{}]interface{}, ts time.Time) error {
50 records := toStringMap(r)

pkg/chunkenc/memchunk.go1

1696:15use-errors-newreplace fmt.Errorf with errors.New for a static message

pkg/chunkenc/memchunk.go:1696:15

1695 if si.readBufValid == lastAttempt { // Got EOF and could not parse same data last time.
1696 si.err = fmt.Errorf("invalid data in chunk")
1697 return 0, nil, labels.EmptyLabels(), false

pkg/bloomgateway/querier_test.go1

36:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

pkg/bloomgateway/querier_test.go:36:2

35 }
36 sort.SliceStable(result, func(i, j int) bool {
37 return result[i].Fingerprint < result[j].Fingerprint

pkg/compression/codec.go1

23:2var-namingidentifier should use MixedCaps rather than underscores

pkg/compression/codec.go:23:2

22 LZ4_1M
23 LZ4_4M
24 Flate

clients/cmd/fluent-bit/config_test.go1

111:72add-constantstring literal "foo" appears more than twice; define a constant

clients/cmd/fluent-bit/config_test.go:111:72

110 Timeout: mustParseDuration("1s"),
111 ExternalLabels: lokiflag.LabelSet{LabelSet: model.LabelSet{"app": "foo"}},
112 BackoffConfig: backoff.Config{MinBackoff: mustParseDuration("1ms"), MaxBackoff: mustParseDuration("5m"), MaxRetries: 10},

clients/pkg/logentry/logql/ast.go1

51:22cognitive-complexityfunction has cognitive complexity 8; maximum is 7

clients/pkg/logentry/logql/ast.go:51:22

50
51func (e *filterExpr) Filter() (Filter, error) {
52 var f func([]byte) bool

pkg/chunkenc/memchunk.go1

398:6confusing-namingname newByteChunk differs from NewByteChunk only by capitalization

pkg/chunkenc/memchunk.go:398:6

397
398func newByteChunk(b []byte, blockSize, targetSize int, fromCheckpoint bool) (*MemChunk, error) {
399 bc := &MemChunk{

pkg/compactor/deletion/request_handler.go1

222:68confusing-resultsadjacent unnamed results of the same type should be named

pkg/compactor/deletion/request_handler.go:222:68

221
222func mergeData(deletes []deletionproto.DeleteRequest) (model.Time, model.Time, deletionproto.DeleteRequestStatus) {
223 var (

pkg/compactor/deletion/tenant_delete_requests_client.go1

24:6constructor-interface-returnNewPerTenantDeleteRequestsClient returns interface DeleteRequestsClient although its concrete result is consistently *perTenantDeleteRequestsClient; return the concrete type

pkg/compactor/deletion/tenant_delete_requests_client.go:24:6

23
24func NewPerTenantDeleteRequestsClient(c DeleteRequestsClient, l Limits) DeleteRequestsClient {
25 return &perTenantDeleteRequestsClient{

pkg/compactor/table.go1

100:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

pkg/compactor/table.go:100:2

99
100 ctx context.Context
101}

clients/pkg/logentry/stages/geoip.go1

193:22cyclomatic-complexityfunction complexity is 23; maximum is 10

clients/pkg/logentry/stages/geoip.go:193:22

192
193func (g *geoIPStage) populateLabelsWithCityData(labels model.LabelSet, record *geoip2.City) {
194 for field, label := range fields {

operator/internal/handlers/lokistack_create_or_update_test.go1

92:2deep-exitprocess-exit calls should be confined to main or init

operator/internal/handlers/lokistack_create_or_update_test.go:92:2

91
92 os.Exit(m.Run())
93}

pkg/ingester/ingester.go1

1181:4deprecated-api-usagegithub.com/grafana/loki/v3/pkg/logproto.Selector is deprecated: Do not use.

pkg/ingester/ingester.go:1181:4

1180 End: end,
1181 Selector: req.Selector,
1182 Shards: req.Shards,

clients/cmd/docker-driver/http.go1

60:7discarded-error-resulterror result returned by json.NewEncoder(w).Encode is discarded

clients/cmd/docker-driver/http.go:60:7

59 h.HandleFunc("/LogDriver.Capabilities", func(w http.ResponseWriter, _ *http.Request) {
60 _ = json.NewEncoder(w).Encode(&CapabilitiesResponse{
61 Cap: logger.Capability{ReadLogs: true},

clients/pkg/logentry/metric/gauges.go1

121:1doc-comment-perioddocumentation comment should end with punctuation

clients/pkg/logentry/metric/gauges.go:121:1

120// Sub subtracts the given value from the Gauge. (The value can be
121// negative, resulting in an increase of the Gauge.)
122func (g *expiringGauge) Sub(val float64) {

pkg/dataobj/internal/dataset/row_reader.go1

839:2early-returninvert the condition and return early to reduce nesting

pkg/dataobj/internal/dataset/row_reader.go:839:2

838 // Get the wrapped column so that the result of c.ListPages can be cached.
839 if idx, ok := r.origColumnLookup[c]; ok {
840 c = r.allColumns()[idx]

operator/api/loki/v1/v1.go1

51:38error-stringserror string should not be capitalized or end with punctuation

operator/api/loki/v1/v1.go:51:38

50 // ErrGroupNamesNotUnique is the error type when loki groups have not unique names.
51 ErrGroupNamesNotUnique = errors.New("Group names are not unique")
52 // ErrInvalidRecordMetricName when any loki recording rule has a invalid PromQL metric name.

pkg/storage/bloom/v1/versioned_builder_test.go1

44:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

pkg/storage/bloom/v1/versioned_builder_test.go:44:2

43 // we simply create the same data twice.
44 _, unmodifiedData, _, _ := setup(V3)
45

clients/pkg/logentry/logql/ast.go1

51:22exported-declaration-commentexported function or method should have a comment beginning with its name

clients/pkg/logentry/logql/ast.go:51:22

50
51func (e *filterExpr) Filter() (Filter, error) {
52 var f func([]byte) bool

operator/api/loki/v1beta1/rulerconfig_types_test.go1

1:1file-length-limitfile has 1038 lines; maximum is 500

operator/api/loki/v1beta1/rulerconfig_types_test.go:1:1

1package v1beta1_test
2

operator/internal/manifests/openshift/configure.go1

249:54flag-parameterboolean parameter uwam controls function flow

operator/internal/manifests/openshift/configure.go:249:54

248// ConfigureOptions applies default configuration for the use of the cluster monitoring alertmanager.
249func ConfigureOptions(configOpt *config.Options, am, uwam bool, token, caPath, monitorServerName string) error {
250 if am {

clients/pkg/logentry/logql/parser_test.go1

1:1formatfile is not formatted

clients/pkg/logentry/logql/parser_test.go:1:1

1package logql
2
  • Fix (safe): run `strider fmt clients/pkg/logentry/logql/parser_test.go`

clients/pkg/logentry/stages/json_test.go1

118:6function-lengthfunction has 4 statements and 76 lines; maximum is 50 statements or 75 lines

clients/pkg/logentry/stages/json_test.go:118:6

117
118func TestJSONConfig_validate(t *testing.T) {
119 t.Parallel()

pkg/dataobj/index/indexer_test.go1

325:26function-result-limitfunction returns 4 values; maximum is 3

pkg/dataobj/index/indexer_test.go:325:26

324
325func (c *mockCalculator) Flush() (*dataobj.Object, io.Closer, []multitenancy.TimeRange, error) {
326 c.flushCallCount++

operator/internal/manifests/build_test.go1

495:3identical-switch-branchesswitch repeats a case body

operator/internal/manifests/build_test.go:495:3

494 lps = o.Spec.Template.Spec.Containers[0].LivenessProbe.HTTPGet.Scheme
495 case *appsv1.StatefulSet:
496 name = o.Name

clients/pkg/logentry/stages/labels_test.go1

16:2import-alias-namingimport alias should contain lower-case letters and digits

clients/pkg/logentry/stages/labels_test.go:16:2

15
16 util_log "github.com/grafana/loki/v3/pkg/util/log"
17)

cmd/loki-canary/main.go1

36:2import-shadowingidentifier writer shadows an imported package

cmd/loki-canary/main.go:36:2

35
36 writer *writer.Writer
37 reader *reader.Reader

pkg/dataobj/consumer/multi_builder.go1

47:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

pkg/dataobj/consumer/multi_builder.go:47:4

46 if _, ok := streamsByTimeWindows[w]; !ok {
47 streamsByTimeWindows[w] = logproto.Stream{
48 Labels: stream.Labels,

pkg/compactor/retention/marker_test.go1

151:6inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.FormatInt with base 10

pkg/compactor/retention/marker_test.go:151:6

150 return []string{
151 fmt.Sprintf("%d", now.Add(-48*time.Hour).UnixNano()), // oldest should be first
152 fmt.Sprintf("%d", now.Add(-3*time.Hour).UnixNano()),

operator/api/loki/v1beta1/lokistack_types_test.go1

221:25insecure-url-schemeURL uses insecure http scheme

operator/api/loki/v1beta1/lokistack_types_test.go:221:25

220 IssuerURL: "http://go-to-issuer",
221 RedirectURL: "http://bring-me-back",
222 GroupClaim: "workgroups",

pkg/logql/syntax/ast.go1

2491:19interface-method-limitinterface has 15 methods, exceeding the configured design limit of 10

pkg/logql/syntax/ast.go:2491:19

2490//sumtype:decl
2491type VariantsExpr interface {
2492 Extractors() ([]SampleExtractor, error)

pkg/logql/syntax/linefilter.go1

40:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

pkg/logql/syntax/linefilter.go:40:7

39
40func (lf *LineFilter) Unmarshal(b []byte) error {
41 buf := encoding.DecWith(b)

pkg/chunkenc/memchunk_test.go1

940:8max-control-nestingcontrol-flow nesting exceeds 5 levels

pkg/chunkenc/memchunk_test.go:940:8

939 entry.Line = testdata.LogString(i)
940 if withStructuredMetadata {
941 entry.StructuredMetadata = []logproto.LabelAdapter{

pkg/engine/internal/proto/testutils/reflect.go1

24:6max-parametersfunction has 9 parameters; maximum is 8

pkg/engine/internal/proto/testutils/reflect.go:24:6

23// to its original value.
24func CheckEnumLookup[Proto, Native comparable](
25 t *testing.T,

operator/api/loki/v1/alertingrule_types.go1

127:6max-public-structsfile declares more than 5 exported structs

operator/api/loki/v1/alertingrule_types.go:127:6

126// AlertingRuleList contains a list of AlertingRule
127type AlertingRuleList struct {
128 metav1.TypeMeta `json:",inline"`

clients/pkg/logentry/stages/drop.go1

63:3modifies-parameterassignment modifies parameter cfg

clients/pkg/logentry/stages/drop.go:63:3

62 if cfg.DropReason == nil || *cfg.DropReason == "" {
63 cfg.DropReason = &defaultDropReason
64 }

pkg/bloombuild/planner/versioned_range.go1

149:4modifies-value-receiverassignment modifies value receiver t

pkg/bloombuild/planner/versioned_range.go:149:4

148 t[i+1] = tok
149 t[i].through = bounds.Min - 1
150 return t, true

clients/pkg/logentry/logql/parser_test.go1

13:23nested-structsmove nested anonymous struct types to named declarations

clients/pkg/logentry/logql/parser_test.go:13:23

12func TestLex(t *testing.T) {
13 for _, tc := range []struct {
14 input string

pkg/compactor/retention/retention.go1

572:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

pkg/compactor/retention/retention.go:572:4

571 // nothing to migrate
572 return nil
573 }

pkg/bloombuild/protos/compat.go1

178:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/bloombuild/protos/compat.go:178:3

177 if result == nil {
178 return nil, nil
179 }

pkg/storage/chunk/client/ibmcloud/trusted_profile_authentication_provider_test.go1

66:4no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/storage/chunk/client/ibmcloud/trusted_profile_authentication_provider_test.go:66:4

65 require.NoError(t, err)
66 defer os.Remove(file.Name())
67 tt.crTokenFilePath = file.Name()

pkg/compactor/table_test.go1

708:8no-else-after-returnremove else and unindent its body after the return

pkg/compactor/table_test.go:708:8

707 return -1
708 } else if a.GetFrom() > b.GetFrom() {
709 return 1

operator/api/loki/v1beta1/lokistack_types.go1

828:6no-initreplace init with explicit initialization

operator/api/loki/v1beta1/lokistack_types.go:828:6

827
828func init() {
829 SchemeBuilder.Register(&LokiStack{}, &LokiStackList{})

pkg/dataobj/sections/indexpointers/reader.go1

295:2no-naked-returnreturn values must be explicit

pkg/dataobj/sections/indexpointers/reader.go:295:2

294 }
295 return
296}

clients/cmd/fluent-bit/out_grafana_loki.go1

26:2no-package-varpackage variables introduce mutable global state

clients/cmd/fluent-bit/out_grafana_loki.go:26:2

25 // registered loki plugin instances, required for disposal during shutdown
26 plugins []*loki
27 logger log.Logger

pkg/compute/logical_bench_test.go1

47:5overwritten-before-usethis value of result is overwritten before use

pkg/compute/logical_bench_test.go:47:5

46 benchAlloc.Reclaim()
47 result, err := compute.Or(benchAlloc, left, right, selection)
48 if err != nil {

clients/pkg/logentry/logql/ast.go1

1:9package-commentspackage should have a documentation comment

clients/pkg/logentry/logql/ast.go:1:9

1package logql
2

pkg/dataobj/compaction/v2/result_record_test.go1

1:9package-directory-mismatchpackage compactionv2 does not match directory v2

pkg/dataobj/compaction/v2/result_record_test.go:1:9

1package compactionv2
2

operator/api/loki/v1beta1/alertingrule_types.go1

194:15range-value-addresstaking the address of range value r can be misleading

operator/api/loki/v1beta1/alertingrule_types.go:194:15

193 for j, r := range sRules {
194 rules[j] = &AlertingRuleGroupSpec{
195 Alert: r.Alert,

pkg/engine/metrics.go1

52:2redefines-builtin-ididentifier close shadows a predeclared identifier

pkg/engine/metrics.go:52:2

51 other *prometheus.HistogramVec // {query_type}
52 close *prometheus.HistogramVec // {query_type}
53}

clients/pkg/logentry/stages/structuredmetadata_test.go1

158:47redundant-conversionconversion from model.LabelName to the identical type is redundant

clients/pkg/logentry/stages/structuredmetadata_test.go:158:47

157 expectedStructuredMetadata: push.LabelsAdapter{push.LabelAdapter{Name: "app", Value: "loki"}},
158 expectedLabels: model.LabelSet{model.LabelName("component"): model.LabelValue("ingester")},
159 },

pkg/bloombuild/builder/batch.go1

17:2redundant-import-aliasimport alias is identical to the package name

pkg/bloombuild/builder/batch.go:17:2

16 logql_log "github.com/grafana/loki/v3/pkg/logql/log"
17 v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1"
18 "github.com/grafana/loki/v3/pkg/storage/chunk"

pkg/engine/internal/planner/logical/logical.go1

123:3single-case-switchswitch with one case can be replaced by an if statement

pkg/engine/internal/planner/logical/logical.go:123:3

122 for _, inst := range p.Instructions {
123 switch inst := inst.(type) {
124 case *Return:

pkg/compactor/deletion/delete_requests_store_boltdb.go1

471:6slice-preallocationpreallocate userCacheGens with capacity len(range source) before appending once per iteration

pkg/compactor/deletion/delete_requests_store_boltdb.go:471:6

470 cacheGenNums := map[string]string{}
471 var userCacheGens []userCacheGen
472 for _, shard := range shards {

pkg/logcli/client/client.go1

538:30standard-http-method-constantreplace the HTTP method literal with http.MethodDelete

pkg/logcli/client/client.go:538:30

537
538 req, err := http.NewRequest("DELETE", us, nil)
539 if err != nil {

operator/internal/handlers/internal/gateway/gateway.go1

112:2task-commentTODO comment should be resolved or linked to an owned work item

operator/internal/handlers/internal/gateway/gateway.go:112:2

111
112 // TODO(JoaoBraveCoding): Once we merge https://github.com/grafana/loki/pull/20325 we should rebase
113 // and add a call to validateConfigRef to validate that the CA actually exists in the cluster

clients/pkg/logentry/stages/drop.go1

143:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/pkg/logentry/stages/drop.go:143:1

142// dropStage applies Label matchers to determine if the include stages should be run
143type dropStage struct {
144 logger log.Logger

clients/pkg/logentry/stages/pipeline_test.go1

202:68unchecked-type-assertionuse the checked two-result form of the type assertion

clients/pkg/logentry/stages/pipeline_test.go:202:68

201
202 p, err := NewPipeline(util_log.Logger, config["pipeline_stages"].([]interface{}), nil, prometheus.DefaultRegisterer)
203 require.NoError(t, err)

pkg/logql/log/pattern/lexer.rl.go1

101unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:101

100 {
101 var _klen int
102 var _trans int

clients/pkg/logentry/stages/pipeline.go1

81:73unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/pipeline.go:81:73

80// RunWithSkip same as RunWith, except it skip sending it to output channel, if `process` functions returns `skip` true.
81func RunWithSkip(input chan Entry, process func(e Entry) (Entry, bool)) chan Entry {
82 out := make(chan Entry)

clients/pkg/logentry/stages/labelallow.go1

63:7unused-receiverreceiver l is unused

clients/pkg/logentry/stages/labelallow.go:63:7

62// Name implements Stage
63func (l *labelAllowStage) Name() string {
64 return StageTypeLabelAllow

clients/cmd/fluent-bit/loki.go1

49:45use-anyuse any instead of interface{}

clients/cmd/fluent-bit/loki.go:49:45

48// sendRecord send fluentbit records to loki as an entry.
49func (l *loki) sendRecord(r map[interface{}]interface{}, ts time.Time) error {
50 records := toStringMap(r)

pkg/chunkenc/symbols.go1

404:18use-errors-newreplace fmt.Errorf with errors.New for a static message

pkg/chunkenc/symbols.go:404:18

403 if readBufValid == 0 { // Got EOF and no data in the buffer.
404 return nil, fmt.Errorf("got unexpected EOF")
405 }

pkg/chunkenc/memchunk_test.go1

796:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

pkg/chunkenc/memchunk_test.go:796:2

795 }
796 sort.Slice(result, func(i, j int) bool {
797 return result[i].ratio > result[j].ratio

pkg/compression/pool.go1

40:2var-namingidentifier should use MixedCaps rather than underscores

pkg/compression/pool.go:40:2

39 // lz4_* are the lz4 compression pools
40 lz4_64k = LZ4Pool{bufferSize: 1 << 16} // lz4_64k is the l4z compression pool, with 64k buffer size
41 lz4_256k = LZ4Pool{bufferSize: 1 << 18} // lz4_256k uses 256k buffer

clients/cmd/fluent-bit/config_test.go1

133:33add-constantstring literal "URL" appears more than twice; define a constant

clients/cmd/fluent-bit/config_test.go:133:33

132 false},
133 {"bad url", map[string]string{"URL": "::doh.com"}, nil, true},
134 {"bad BatchWait", map[string]string{"BatchWait": "30sa"}, nil, true},

clients/pkg/logentry/stages/drop.go1

50:6cognitive-complexityfunction has cognitive complexity 20; maximum is 7

clients/pkg/logentry/stages/drop.go:50:6

49// validateDropConfig validates the DropConfig for the dropStage
50func validateDropConfig(cfg *DropConfig) error {
51 if cfg == nil ||

pkg/chunkenc/memchunk.go1

618:20confusing-namingname writeTo differs from WriteTo only by capitalization

pkg/chunkenc/memchunk.go:618:20

617// they were checkpointed (which would cause new blocks to be cut early).
618func (c *MemChunk) writeTo(w io.Writer, forCheckpoint bool) (int64, error) {
619 crc32Hash := crc32HashPool.Get().(hash.Hash32)

pkg/compactor/retention/retention.go1

147:151confusing-resultsadjacent unnamed results of the same type should be named

pkg/compactor/retention/retention.go:147:151

146// FindAndMarkChunksForDeletion finds expired chunks using the ExpirationChecker from the given table and marks them for deletion.
147func (t *Marker) FindAndMarkChunksForDeletion(ctx context.Context, tableName, userID string, indexProcessor IndexProcessor, logger log.Logger) (bool, bool, error) {
148 start := time.Now()

pkg/compactor/retention/expiration.go1

52:6constructor-interface-returnNewExpirationChecker returns interface ExpirationChecker although its concrete result is consistently *expirationChecker; return the concrete type

pkg/compactor/retention/expiration.go:52:6

51
52func NewExpirationChecker(limits Limits, r prometheus.Registerer) ExpirationChecker {
53 return &expirationChecker{

pkg/compactor/testutil.go1

222:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

pkg/compactor/testutil.go:222:2

221type tableCompactor struct {
222 ctx context.Context
223 commonIndexSet IndexSet

clients/pkg/logentry/stages/json.go1

110:21cyclomatic-complexityfunction complexity is 21; maximum is 10

clients/pkg/logentry/stages/json.go:110:21

109
110func (j *jsonStage) processEntry(extracted map[string]interface{}, entry *string) error {
111 // If a source key is provided, the json stage should process it

pkg/distributor/distributor_ring.go1

45:3deep-exitprocess-exit calls should be confined to main or init

pkg/distributor/distributor_ring.go:45:3

44 level.Error(util_log.Logger).Log("msg", "failed to get hostname", "err", err)
45 os.Exit(1)
46 }

pkg/ingester/ingester.go1

1181:14deprecated-api-usagegithub.com/grafana/loki/v3/pkg/logproto.Selector is deprecated: Do not use.

pkg/ingester/ingester.go:1181:14

1180 End: end,
1181 Selector: req.Selector,
1182 Shards: req.Shards,

clients/cmd/docker-driver/http.go1

81:10discarded-error-resulterror result returned by io.Copy is discarded

clients/cmd/docker-driver/http.go:81:10

80 wf := ioutils.NewWriteFlusher(w)
81 _, _ = io.Copy(wf, stream)
82 })

clients/pkg/logentry/metric/gauges.go1

133:1doc-comment-perioddocumentation comment should end with punctuation

clients/pkg/logentry/metric/gauges.go:133:1

132
133// HasExpired implements Expirable
134func (g *expiringGauge) HasExpired(currentTimeSec int64, maxAgeSec int64) bool {

pkg/distributor/field_detection.go1

224:9early-returninvert the condition and return early to reduce nesting

pkg/distributor/field_detection.go:224:9

223 v = getLevelUsingJSONParser(lineBytes, l.allowedLevelLabelsMap, l.logLevelFromJSONMaxDepth)
224 } else if isLogFmt(lineBytes) {
225 v = getValueUsingLogfmtParser(lineBytes, l.allowedLevelLabels)

operator/api/loki/v1/v1.go1

53:42error-stringserror string should not be capitalized or end with punctuation

operator/api/loki/v1/v1.go:53:42

52 // ErrInvalidRecordMetricName when any loki recording rule has a invalid PromQL metric name.
53 ErrInvalidRecordMetricName = errors.New("Failed to parse record metric name")
54 // ErrParseAlertForPeriod when any loki alerting rule for period is not a valid PromQL duration.

pkg/storage/chunk/cache/memcached_test.go1

50:4excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

pkg/storage/chunk/cache/memcached_test.go:50:4

49
50 _, _, _, err = m.Fetch(ctx, keys) // will try to write to `intputChan` and shouldn't panic
51 require.NoError(t, err)

clients/pkg/logentry/logql/parser.go1

41:6exported-declaration-commentexported function or method should have a comment beginning with its name

clients/pkg/logentry/logql/parser.go:41:6

40// anything else it will return an error.
41func ParseMatchers(input string) ([]*labels.Matcher, error) {
42 expr, err := ParseExpr(input)

operator/internal/handlers/internal/gateway/modes_test.go1

1:1file-length-limitfile has 675 lines; maximum is 500

operator/internal/handlers/internal/gateway/modes_test.go:1:1

1package gateway
2

operator/internal/manifests/openshift/opa_openshift.go1

27:110flag-parameterboolean parameter withTLS controls function flow

operator/internal/manifests/openshift/opa_openshift.go:27:110

26
27func newOPAOpenShiftContainer(mode lokiv1.ModeType, secretVolumeName, tlsDir, minTLSVersion, ciphers string, withTLS bool, adminGroups []string) corev1.Container {
28 var (

clients/pkg/logentry/metric/counters.go1

1:1formatfile is not formatted

clients/pkg/logentry/metric/counters.go:1:1

1package metric
2
  • Fix (safe): run `strider fmt clients/pkg/logentry/metric/counters.go`

clients/pkg/logentry/stages/json_test.go1

214:6function-lengthfunction has 4 statements and 135 lines; maximum is 50 statements or 75 lines

clients/pkg/logentry/stages/json_test.go:214:6

213
214func TestJSONParser_Parse(t *testing.T) {
215 t.Parallel()

pkg/dataobj/sections/logs/table_merge.go1

286:6function-result-limitfunction returns 4 values; maximum is 3

pkg/dataobj/sections/logs/table_merge.go:286:6

285// valuesForRows returns the streamID and timestamp values from rows a and b.
286func valuesForRows(a, b dataset.Row) (aStreamID int64, bStreamID int64, aTimestamp int64, bTimestamp int64) {
287 aStreamID = a.Values[0].Int64()

operator/internal/manifests/build_test.go1

657:5identical-switch-branchesswitch repeats a case body

operator/internal/manifests/build_test.go:657:5

656 spec = &obj.Spec.Template.Spec
657 case *appsv1.StatefulSet:
658 name = obj.Name

clients/pkg/logentry/stages/limit_test.go1

12:2import-alias-namingimport alias should contain lower-case letters and digits

clients/pkg/logentry/stages/limit_test.go:12:2

11
12 util_log "github.com/grafana/loki/v3/pkg/util/log"
13)

cmd/loki-canary/main.go1

37:2import-shadowingidentifier reader shadows an imported package

cmd/loki-canary/main.go:37:2

36 writer *writer.Writer
37 reader *reader.Reader
38 comparator *comparator.Comparator

pkg/dataobj/index/indexobj/builder.go1

138:3inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

pkg/dataobj/index/indexobj/builder.go:138:3

137 sb.SetTenant(tenantID)
138 b.stats[tenantID] = sb
139 }

pkg/compactor/retention/marker_test.go1

152:6inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.FormatInt with base 10

pkg/compactor/retention/marker_test.go:152:6

151 fmt.Sprintf("%d", now.Add(-48*time.Hour).UnixNano()), // oldest should be first
152 fmt.Sprintf("%d", now.Add(-3*time.Hour).UnixNano()),
153 fmt.Sprintf("%d", now.Add(-2*time.Hour).UnixNano()),

operator/api/loki/v1beta1/lokistack_types_test.go1

233:25insecure-url-schemeURL uses insecure http scheme

operator/api/loki/v1beta1/lokistack_types_test.go:233:25

232 },
233 IssuerURL: "http://go-to-issuer",
234 RedirectURL: "http://bring-me-back",

pkg/logql/syntax/visit.go1

7:18interface-method-limitinterface has 21 methods, exceeding the configured design limit of 10

pkg/logql/syntax/visit.go:7:18

6
7type RootVisitor interface {
8 SampleExprVisitor

pkg/push/types.go1

78:7marshal-receivermarshal and unmarshal methods should use a consistent receiver type

pkg/push/types.go:78:7

77// Should be kept in sync with Prometheus's labels.Labels implementation.
78func (ls *LabelsAdapter) UnmarshalJSON(b []byte) error {
79 var m map[string]string

pkg/chunkenc/unordered_test.go1

250:9max-control-nestingcontrol-flow nesting exceeds 5 levels

pkg/chunkenc/unordered_test.go:250:9

249 if !dup { // only set dup if it's not already true
250 if tmpdup { // can't examine duplicates until we start getting all the data
251 dup = true

pkg/ingester/ingester.go1

313:6max-parametersfunction has 12 parameters; maximum is 8

pkg/ingester/ingester.go:313:6

312// New makes a new Ingester.
313func New(cfg Config, clientConfig client.Config, store Store, limits Limits, configs *runtime.TenantConfigs, registerer prometheus.Registerer, writeFailuresCfg writefailures.Cfg, metricsNamespace string, logger log.Logger, customStreamsTracker push.UsageTracker, readRing ring.ReadRing, partitionRingWatcher ring.PartitionRingReader) (*Ingester, error) {
314 if cfg.ingesterClientFactory == nil {

operator/api/loki/v1/lokistack_types.go1

155:6max-public-structsfile declares more than 5 exported structs

operator/api/loki/v1/lokistack_types.go:155:6

154// for a secret living in the same namespace as the LokiStack custom resource.
155type TenantSecretSpec struct {
156 // Name of a secret in the namespace configured for tenant secrets.

clients/pkg/logentry/stages/drop.go1

66:3modifies-parameterassignment modifies parameter cfg

clients/pkg/logentry/stages/drop.go:66:3

65 if cfg.Separator == nil {
66 cfg.Separator = &defaultSeparator
67 }

pkg/bloombuild/planner/versioned_range.go1

159:4modifies-value-receiverassignment modifies value receiver t

pkg/bloombuild/planner/versioned_range.go:159:4

158 if preExisting.Min == bounds.Min {
159 t[i].version = version
160 bounds.Min = preExisting.Max + 1

clients/pkg/logentry/logql/parser_test.go1

48:23nested-structsmove nested anonymous struct types to named declarations

clients/pkg/logentry/logql/parser_test.go:48:23

47func TestParse(t *testing.T) {
48 for _, tc := range []struct {
49 in string

pkg/compactor/tables_manager.go1

371:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

pkg/compactor/tables_manager.go:371:4

370 level.Error(util_log.Logger).Log("msg", "skipping compaction since we can't find schema for table", "table", tableName)
371 return nil
372 }

pkg/bloomgateway/processor_test.go1

77:2nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

pkg/bloomgateway/processor_test.go:77:2

76func (s *dummyStore) Fetcher(_ model.Time) (*bloomshipper.Fetcher, error) {
77 return nil, nil
78}

pkg/storage/stores/shipper/indexshipper/tsdb/head_manager.go1

876:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

pkg/storage/stores/shipper/indexshipper/tsdb/head_manager.go:876:3

875 t.locks[i].RLock()
876 defer t.locks[i].RUnlock()
877

pkg/compute/compute_test.go1

26:5no-else-after-returnremove else and unindent its body after the return

pkg/compute/compute_test.go:26:5

25 return nil
26 } else if filepath.Ext(d.Name()) != ".test" {
27 return nil

operator/api/loki/v1beta1/recordingrule_types.go1

112:6no-initreplace init with explicit initialization

operator/api/loki/v1beta1/recordingrule_types.go:112:6

111
112func init() {
113 SchemeBuilder.Register(&RecordingRule{}, &RecordingRuleList{})

pkg/dataobj/sections/logs/reader.go1

306:2no-naked-returnreturn values must be explicit

pkg/dataobj/sections/logs/reader.go:306:2

305 }
306 return
307}

clients/cmd/fluent-bit/out_grafana_loki.go1

27:2no-package-varpackage variables introduce mutable global state

clients/cmd/fluent-bit/out_grafana_loki.go:27:2

26 plugins []*loki
27 logger log.Logger
28)

pkg/compute/logical_bench_test.go1

69:5overwritten-before-usethis value of result is overwritten before use

pkg/compute/logical_bench_test.go:69:5

68 benchAlloc.Reclaim()
69 result, err := compute.Not(benchAlloc, input, selection)
70 if err != nil {

clients/pkg/logentry/logql/parser.go1

1:9package-commentspackage should have a documentation comment

clients/pkg/logentry/logql/parser.go:1:9

1package logql
2

pkg/engine/internal/scheduler/wire/arrow/arrow.go1

1:9package-directory-mismatchpackage arrowcodec does not match directory arrow

pkg/engine/internal/scheduler/wire/arrow/arrow.go:1:9

1package arrowcodec
2

operator/api/loki/v1beta1/alertingrule_types.go1

203:24range-value-addresstaking the address of range value g can be misleading

operator/api/loki/v1beta1/alertingrule_types.go:203:24

202
203 dst.Spec.Groups[i] = &AlertingRuleGroup{
204 Name: g.Name,

pkg/ingester/chunk_test.go1

49:3redefines-builtin-ididentifier new shadows a predeclared identifier

pkg/ingester/chunk_test.go:49:3

48 name string
49 new func() chunkenc.Chunk
50 }{

clients/pkg/logentry/stages/structuredmetadata_test.go1

158:77redundant-conversionconversion from model.LabelValue to the identical type is redundant

clients/pkg/logentry/stages/structuredmetadata_test.go:158:77

157 expectedStructuredMetadata: push.LabelsAdapter{push.LabelAdapter{Name: "app", Value: "loki"}},
158 expectedLabels: model.LabelSet{model.LabelName("component"): model.LabelValue("ingester")},
159 },

pkg/bloombuild/builder/batch_test.go1

11:2redundant-import-aliasimport alias is identical to the package name

pkg/bloombuild/builder/batch_test.go:11:2

10
11 v2 "github.com/grafana/loki/v3/pkg/iter/v2"
12 v1 "github.com/grafana/loki/v3/pkg/storage/bloom/v1"

pkg/engine/internal/planner/logical/planner.go1

402:2single-case-switchswitch with one case can be replaced by an if statement

pkg/engine/internal/planner/logical/planner.go:402:2

401
402 switch e.Operation {
403 // case syntax.OpRangeTypeBytesRate:

pkg/compactor/deletion/job_builder.go1

278:6slice-preallocationpreallocate manifests with capacity len(range source) before appending once per iteration

pkg/compactor/deletion/job_builder.go:278:6

277 // Filter for manifest directories (they are named with Unix timestamps)
278 var manifests []string
279 for _, commonPrefix := range commonPrefixes {

pkg/loki/format_query_handler_test.go1

40:32standard-http-method-constantreplace the HTTP method literal with http.MethodGet

pkg/loki/format_query_handler_test.go:40:32

39 t.Run(tc.name, func(t *testing.T) {
40 req, err := http.NewRequest("GET", fmt.Sprintf("http://localhost:808?query=%s", tc.query), nil)
41 require.NoError(t, err)

operator/internal/manifests/compactor.go1

171:8task-commentTODO comment should be resolved or linked to an owned work item

operator/internal/manifests/compactor.go:171:8

170 AccessModes: []corev1.PersistentVolumeAccessMode{
171 // TODO: should we verify that this is possible with the given storage class first?
172 corev1.ReadWriteOnce,

clients/pkg/logentry/stages/drop_test.go1

444:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

clients/pkg/logentry/stages/drop_test.go:444:1

443
444var (
445 dropInvalidDur = "10y"

clients/pkg/logentry/stages/pipeline_test.go1

275:66unchecked-type-assertionuse the checked two-result form of the type assertion

clients/pkg/logentry/stages/pipeline_test.go:275:66

274 }
275 p, err := NewPipeline(util_log.Logger, config["pipeline_stages"].([]interface{}), nil, prometheus.DefaultRegisterer)
276 if err != nil {

pkg/logql/log/pattern/lexer.rl.go1

102unexported-namingunexported identifier should not begin with an underscore

pkg/logql/log/pattern/lexer.rl.go:102

101 var _klen int
102 var _trans int
103 var _acts int

clients/pkg/logentry/stages/pipeline.go1

98:85unexported-returnexported function returns an unexported type

clients/pkg/logentry/stages/pipeline.go:98:85

97// RunWithSkiporSendMany same as RunWithSkip, except it can either skip sending it to output channel, if `process` functions returns `skip` true. Or send many entries.
98func RunWithSkipOrSendMany(input chan Entry, process func(e Entry) ([]Entry, bool)) chan Entry {
99 out := make(chan Entry)

clients/pkg/logentry/stages/labeldrop.go1

56:7unused-receiverreceiver l is unused

clients/pkg/logentry/stages/labeldrop.go:56:7

55// Name implements Stage
56func (l *labelDropStage) Name() string {
57 return StageTypeLabelDrop

clients/cmd/fluent-bit/loki.go1

95:28use-anyuse any instead of interface{}

clients/cmd/fluent-bit/loki.go:95:28

94// converting them to strings
95func toStringSlice(slice []interface{}) []interface{} {
96 var s []interface{}

pkg/chunkenc/symbols.go1

407:18use-errors-newreplace fmt.Errorf with errors.New for a static message

pkg/chunkenc/symbols.go:407:18

406 if readBufValid == lastAttempt { // Got EOF and could not parse same data last time.
407 return nil, fmt.Errorf("invalid structured metadata block in chunk")
408 }

pkg/compactor/compactor.go1

635:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

pkg/compactor/compactor.go:635:2

634
635 sort.Slice(tables, func(i, j int) bool {
636 // less than if start time is after produces a most recent first sort order

pkg/compression/pool.go1

41:2var-namingidentifier should use MixedCaps rather than underscores

pkg/compression/pool.go:41:2

40 lz4_64k = LZ4Pool{bufferSize: 1 << 16} // lz4_64k is the l4z compression pool, with 64k buffer size
41 lz4_256k = LZ4Pool{bufferSize: 1 << 18} // lz4_256k uses 256k buffer
42 lz4_1M = LZ4Pool{bufferSize: 1 << 20} // lz4_1M uses 1M buffer

clients/cmd/fluent-bit/config_test.go1

134:39add-constantstring literal "BatchWait" appears more than twice; define a constant

clients/cmd/fluent-bit/config_test.go:134:39

133 {"bad url", map[string]string{"URL": "::doh.com"}, nil, true},
134 {"bad BatchWait", map[string]string{"BatchWait": "30sa"}, nil, true},
135 {"bad BatchSize", map[string]string{"BatchSize": "a"}, nil, true},

clients/pkg/logentry/stages/drop.go1

164:21cognitive-complexityfunction has cognitive complexity 63; maximum is 7

clients/pkg/logentry/stages/drop.go:164:21

163
164func (m *dropStage) shouldDrop(e Entry) bool {
165 // There are many options for dropping a log and if multiple are defined it's treated like an AND condition

pkg/chunkenc/memchunk.go1

1294:16confusing-namingname Offset differs from offset only by capitalization

pkg/chunkenc/memchunk.go:1294:16

1293
1294func (b block) Offset() int {
1295 return b.offset

pkg/compactor/retention/retention.go1

164:132confusing-resultsadjacent unnamed results of the same type should be named

pkg/compactor/retention/retention.go:164:132

163
164func (t *Marker) markTable(ctx context.Context, tableName, userID string, indexProcessor IndexProcessor, logger log.Logger) (bool, bool, error) {
165 markerWriter, err := NewMarkerWriter(t.markerStorageClient)

pkg/compactor/retention/marker.go1

49:6constructor-interface-returnNewMarkerWriter returns interface MarkerStorageWriter although its concrete result is consistently *markerStorageWriter; return the concrete type

pkg/compactor/retention/marker.go:49:6

48
49func NewMarkerWriter(markerStorageClient client.ObjectClient) (MarkerStorageWriter, error) {
50 msw := &markerStorageWriter{

pkg/dataobj/index/indexer.go1

31:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

pkg/dataobj/index/indexer.go:31:2

30 trigger triggerType
31 ctx context.Context
32 resultChan chan buildResult

clients/pkg/logentry/stages/logfmt.go1

96:23cyclomatic-complexityfunction complexity is 15; maximum is 10

clients/pkg/logentry/stages/logfmt.go:96:23

95// Process implements Stage
96func (j *logfmtStage) Process(_ model.LabelSet, extracted map[string]interface{}, _ *time.Time, entry *string) {
97 // If a source key is provided, the logfmt stage should process it

pkg/logcli/detected/fields.go1

45:3deep-exitprocess-exit calls should be confined to main or init

pkg/logcli/detected/fields.go:45:3

44 if err != nil {
45 log.Fatalf("Error doing request: %+v", err)
46 }

pkg/ingester/ingester.go1

1399:6deprecated-api-usagegithub.com/grafana/loki/v3/pkg/logproto.Selector is deprecated: Do not use.

pkg/ingester/ingester.go:1399:6

1398 QueryRequest: &logproto.QueryRequest{
1399 Selector: group,
1400 Limit: 1,

clients/cmd/docker-driver/http.go1

94:6discarded-error-resulterror result returned by json.NewEncoder(w).Encode is discarded

clients/cmd/docker-driver/http.go:94:6

93 }
94 _ = json.NewEncoder(w).Encode(&res)
95}

clients/pkg/logentry/metric/histograms.go1

76:1doc-comment-perioddocumentation comment should end with punctuation

clients/pkg/logentry/metric/histograms.go:76:1

75
76// HasExpired implements Expirable
77func (h *expiringHistogram) HasExpired(currentTimeSec int64, maxAgeSec int64) bool {

pkg/engine/internal/workflow/workflow_planner.go1

331:4early-returninvert the condition and return early to reduce nesting

pkg/engine/internal/workflow/workflow_planner.go:331:4

330 if err != nil {
331 if errors.Is(err, context.DeadlineExceeded) {
332 level.Debug(logger).Log(