Skip to content

chore(modernize): use slices.Backward where applicable#20103

Open
rhybrillou wants to merge 2 commits intomasterfrom
yann/modernize-backward-slices
Open

chore(modernize): use slices.Backward where applicable#20103
rhybrillou wants to merge 2 commits intomasterfrom
yann/modernize-backward-slices

Conversation

@rhybrillou
Copy link
Copy Markdown
Contributor

Description

Prepare for stricter modernize linting.

User-facing documentation

Testing and quality

  • the change is production ready: the change is GA, or otherwise the functionality is gated by a feature flag
  • CI results are inspected

Automated testing

  • modified existing tests

How I validated my change

CI run.

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've left some high level feedback:

  • In the loops converted to for i, v := range slices.Backward(...) (e.g., in filterProcesses and filterViolations), verify that the loop index is still correct for any subsequent indexing into the original slice, since range slices.Backward yields indices 0..n-1 of the reversed view rather than the original slice indices.
  • The change in combineStrings to for index := range slices.Backward(indices) alters the loop order semantics (and index now refers to the reversed-view index, not the original slice index) and also introduces a missing slices import in this file; consider either keeping the original index-based reverse loop or explicitly mapping the reversed iteration index back to the original slice index.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the loops converted to `for i, v := range slices.Backward(...)` (e.g., in `filterProcesses` and `filterViolations`), verify that the loop index is still correct for any subsequent indexing into the original slice, since `range slices.Backward` yields indices 0..n-1 of the reversed view rather than the original slice indices.
- The change in `combineStrings` to `for index := range slices.Backward(indices)` alters the loop order semantics (and `index` now refers to the reversed-view index, not the original slice index) and also introduces a missing `slices` import in this file; consider either keeping the original index-based reverse loop or explicitly mapping the reversed iteration index back to the original slice index.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Apr 20, 2026

📝 Walkthrough

Summary by CodeRabbit

  • Refactor
    • Enhanced code maintainability across multiple modules by simplifying iteration patterns while preserving all existing functionality and public APIs.

Walkthrough

This pull request refactors reverse-loop iterations across seven files in the Go codebase, replacing manual decrementing index loops with the standard library's slices.Backward() function. The control flow and behavior remain functionally identical while standardizing the reverse iteration pattern.

Changes

Cohort / File(s) Summary
Core Service & Utility Refactoring
central/policy/service/service_impl.go, pkg/httputil/interceptor.go, pkg/stringutils/empty.go
Replaced explicit reverse-index for loops with slices.Backward() iteration in combineStrings, interceptor chaining, and LastNonEmpty functions respectively, maintaining identical control flow semantics.
Test & Notification Pruning
central/resourcecollection/datastore/datastore_impl_postgres_test.go, pkg/notifiers/prune.go
Converted reverse iteration in test cleanup and filtering operations (filterProcesses, filterViolations) to use slices.Backward(), directly marshaling elements instead of index-based access.
Kubernetes & Upgrade Context
sensor/kubernetes/networkpolicies/apply_tx.go, sensor/upgrader/upgradectx/context.go
Replaced manual reverse-index loops with slices.Backward() in rollback action execution, modification recording, and canonical GVK version resolution, preserving reverse-order semantics.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely describes the main change: modernizing code by replacing manual reverse loops with slices.Backward throughout the codebase.
Description check ✅ Passed The description provides context (stricter linting preparation), indicates no user-facing changes are needed, marks testing status, and notes CI validation was performed.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch yann/modernize-backward-slices

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
pkg/notifiers/prune.go (1)

60-66: ⚠️ Potential issue | 🟠 Major

Assign the sanitized process before pruning.

Line 62 drops the new ProcessIndicator returned by cleanProcessIndicator, so Line 66 still marshals and later returns the original process objects. This can keep fields that pruning is meant to strip from notifications.

Proposed fix
-	for _, p := range processes {
-		cleanProcessIndicator(p)
+	for i, p := range processes {
+		processes[i] = cleanProcessIndicator(p)
 	}
 
 	for i, p := range slices.Backward(processes) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pkg/notifiers/prune.go` around lines 60 - 66, The loop calling
cleanProcessIndicator currently discards its return value, so later pruning
still uses the original ProcessIndicator; modify the code to assign the
sanitized result back into the slice before the backward-prune loop (e.g.,
replace each processes[i] = cleanProcessIndicator(processes[i]) or otherwise
store the returned ProcessIndicator), then use slices.Backward(processes) and
jsonutil.MarshalToCompactString on the sanitized entries so pruned/stripped
fields are not preserved in notifications.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@pkg/notifiers/prune.go`:
- Around line 60-66: The loop calling cleanProcessIndicator currently discards
its return value, so later pruning still uses the original ProcessIndicator;
modify the code to assign the sanitized result back into the slice before the
backward-prune loop (e.g., replace each processes[i] =
cleanProcessIndicator(processes[i]) or otherwise store the returned
ProcessIndicator), then use slices.Backward(processes) and
jsonutil.MarshalToCompactString on the sanitized entries so pruned/stripped
fields are not preserved in notifications.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Central YAML (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: d87ce37d-4568-4070-b03d-f546a30d5f6c

📥 Commits

Reviewing files that changed from the base of the PR and between b20d233 and 6eda7b2.

📒 Files selected for processing (7)
  • central/policy/service/service_impl.go
  • central/resourcecollection/datastore/datastore_impl_postgres_test.go
  • pkg/httputil/interceptor.go
  • pkg/notifiers/prune.go
  • pkg/stringutils/empty.go
  • sensor/kubernetes/networkpolicies/apply_tx.go
  • sensor/upgrader/upgradectx/context.go

@codecov
Copy link
Copy Markdown

codecov bot commented Apr 20, 2026

Codecov Report

❌ Patch coverage is 50.00000% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 49.69%. Comparing base (487e4d0) to head (5ebf6a5).
⚠️ Report is 9 commits behind head on master.

Files with missing lines Patch % Lines
pkg/stringutils/empty.go 0.00% 3 Missing ⚠️
pkg/httputil/interceptor.go 0.00% 2 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master   #20103   +/-   ##
=======================================
  Coverage   49.68%   49.69%           
=======================================
  Files        2766     2766           
  Lines      209299   209299           
=======================================
+ Hits       103994   104002    +8     
+ Misses      97613    97606    -7     
+ Partials     7692     7691    -1     
Flag Coverage Δ
go-unit-tests 49.69% <50.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Apr 20, 2026

🚀 Build Images Ready

Images are ready for commit 5ebf6a5. To use with deploy scripts:

export MAIN_IMAGE_TAG=4.11.x-698-g5ebf6a5bd0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant