Skip to content

Optimize Network.Check single-IP path to reduce allocations#49588

Open
Copilot wants to merge 3 commits intomainfrom
copilot/optimize-network-check-ip-path
Open

Optimize Network.Check single-IP path to reduce allocations#49588
Copilot wants to merge 3 commits intomainfrom
copilot/optimize-network-check-ip-path

Conversation

Copy link
Contributor

Copilot AI commented Mar 20, 2026

Network.Check called extractIP on every event value, unconditionally allocating a []net.IP slice even for the dominant single-IP case. This adds ~40 B and 2 allocs per op on a hot path.

Changes:

  • Replace extractIP + slices.ContainsFunc with a type switch in Check that fast-paths string and net.IP without slice construction
  • Add containsAny/containsAnyStr helpers for []net.IP and []string slice cases
  • Remove now-unused extractIP function and slices import
// Before: always allocates []net.IP
ipList := extractIP(value)
if !slices.ContainsFunc(ipList, network.Contains) { ... }

// After: no allocation for single-IP types
switch v := value.(type) {
case string:
    ip := net.ParseIP(v)
    if ip == nil || !network.Contains(ip) { return false }
case net.IP:
    if !network.Contains(v) { return false }
case []net.IP:
    if len(v) == 0 || !containsAny(v, network.Contains) { return false }
case []string:
    if len(v) == 0 || !containsAnyStr(v, network.Contains) { return false }
}

Benchmark (10 runs): ~181 → ~139 ns/op, 40 → 16 B/op, 2 → 1 allocs/op.

Original prompt

This section details on the original issue you should resolve

<issue_title>[performance-profiler] Optimize Network.Check single-IP path to reduce allocations and CPU</issue_title>
<issue_description>## Hot Path
libbeat/conditions/network.go in (*Network).Check currently calls extractIP for every event value and then scans the returned slice.

Relevant code paths:

  • libbeat/conditions/network.go:153-209 (Check)
  • libbeat/conditions/network.go:208-225 (extractIP)
  • Benchmark: libbeat/conditions/network_test.go:301-323 (BenchmarkNetworkCondition)

Profiling Data

Before:

go test ./libbeat/conditions -run '^$' -bench '^BenchmarkNetworkCondition$' -benchmem -count=10

BenchmarkNetworkCondition-4   6691453   181.8 ns/op   40 B/op   2 allocs/op
BenchmarkNetworkCondition-4   5696349   182.5 ns/op   40 B/op   2 allocs/op
BenchmarkNetworkCondition-4   6652167   180.4 ns/op   40 B/op   2 allocs/op
BenchmarkNetworkCondition-4   6576028   180.7 ns/op   40 B/op   2 allocs/op
BenchmarkNetworkCondition-4   6604658   181.2 ns/op   40 B/op   2 allocs/op
BenchmarkNetworkCondition-4   6624548   182.5 ns/op   40 B/op   2 allocs/op
BenchmarkNetworkCondition-4   6617449   180.4 ns/op   40 B/op   2 allocs/op
BenchmarkNetworkCondition-4   6587047   180.8 ns/op   40 B/op   2 allocs/op
BenchmarkNetworkCondition-4   6591918   183.1 ns/op   40 B/op   2 allocs/op
BenchmarkNetworkCondition-4   6225799   180.5 ns/op   40 B/op   2 allocs/op

Proposed Change

Avoid per-call slice construction in the common single-IP path by handling concrete types directly in Check:

  • Fast-path string and net.IP without building []net.IP.
  • Keep loop semantics for []string and []net.IP.
  • Preserve behavior for invalid/empty values.

Representative diff:

- ipList := extractIP(value)
- if len(ipList) == 0 { ... }
- if !slices.ContainsFunc(ipList, network.Contains) { ... }
+ switch v := value.(type) {
+ case string:
+   if !network.Contains(net.ParseIP(v)) { return false }
+ case net.IP:
+   if !network.Contains(v) { return false }
+ case []net.IP:
+   // any-match loop
+ case []string:
+   // parse + any-match loop
+ default:
+   return false
+ }

Results

After:

go test ./libbeat/conditions -run '^$' -bench '^BenchmarkNetworkCondition$' -benchmem -count=10

BenchmarkNetworkCondition-4   8108420   141.5 ns/op   16 B/op   1 allocs/op
BenchmarkNetworkCondition-4   8422035   141.3 ns/op   16 B/op   1 allocs/op
BenchmarkNetworkCondition-4   8605186   139.9 ns/op   16 B/op   1 allocs/op
BenchmarkNetworkCondition-4   8111130   142.6 ns/op   16 B/op   1 allocs/op
BenchmarkNetworkCondition-4   8505433   142.3 ns/op   16 B/op   1 allocs/op
BenchmarkNetworkCondition-4   8527528   141.4 ns/op   16 B/op   1 allocs/op
BenchmarkNetworkCondition-4   8518203   147.3 ns/op   16 B/op   1 allocs/op
BenchmarkNetworkCondition-4   8579733   142.4 ns/op   16 B/op   1 allocs/op
BenchmarkNetworkCondition-4   8500126   141.1 ns/op   16 B/op   1 allocs/op
BenchmarkNetworkCondition-4   8486481   140.2 ns/op   16 B/op   1 allocs/op

Improvement:

  • Time: ~22% faster (about 181 ns/op -> 141 ns/op)
  • Memory: 60% less bytes/op (40 -> 16)
  • Allocations: 50% fewer allocs/op (2 -> 1)

Verification

  • Tests run: go test ./libbeat/conditions -run '^TestNetwork'
  • Result: pass
  • Behavior preservation: same network matching semantics for string, net.IP, []string, and []net.IP; invalid values still fail.

Evidence

Commands run:

  • go test ./libbeat/conditions -run '^$' -bench '^BenchmarkNetworkCondition$' -benchmem -count=10 (before)
  • go test ./libbeat/conditions -run '^TestNetwork'
  • go test ./libbeat/conditions -run '^$' -bench '^BenchmarkNetworkCondition$' -benchmem -count=10 (after)

Duplicate check:

  • Compared against /tmp/previous-findings.json; this hot path is distinct from prior filed items (e.g., dissect suffix allocations, diskqueue decoder buffer reuse, memqueue producer allocations).

What is this? | From workflow: Performance Profiler

Give us feedback! React with 🚀 if perfect, 👍 if helpful, 👎 if not.

  • expires on Mar 26, 2026, 2:34 PM UTC

Comments on the Issue (you are @copilot in this section)

@strawgate /ai how frequently is this called? is this a useful optimization? what is it in the hot path for

📱 Kick off Copilot coding agent tasks wherever you are with GitHub Mobile, available on iOS and Android.

@botelastic botelastic bot added the needs_team Indicates that the issue/PR needs a Team:* label label Mar 20, 2026
@mergify
Copy link
Contributor

mergify bot commented Mar 20, 2026

This pull request does not have a backport label.
If this is a bug or security fix, could you label this PR @copilot? 🙏.
For such, you'll need to label your PR with:

  • The upcoming major version of the Elastic Stack
  • The upcoming minor version of the Elastic Stack (if you're not pushing a breaking change)

To fixup this pull request, you need to add the backport labels for the needed
branches, such as:

  • backport-8./d is the label to automatically backport to the 8./d branch. /d is the digit
  • backport-active-all is the label that automatically backports to all active branches.
  • backport-active-8 is the label that automatically backports to all active minor branches for the 8 major.
  • backport-active-9 is the label that automatically backports to all active minor branches for the 9 major.

Avoid per-call slice construction in the common single-IP path by
handling concrete types directly in Check via a type switch:
- Fast-path string and net.IP without building []net.IP
- Keep loop semantics for []string and []net.IP
- Preserve behavior for invalid/empty values

Remove now-unused extractIP function and slices import.

Benchmark improvement: ~22% faster, 60% less memory, 50% fewer allocs.

Co-authored-by: strawgate <6384545+strawgate@users.noreply.github.com>
Agent-Logs-Url: https://github.com/elastic/beats/sessions/6a9f4491-418d-484d-a4d0-ac8777846040
Copilot AI changed the title [WIP] Optimize Network.Check single-IP path to reduce allocations and CPU Optimize Network.Check single-IP path to reduce allocations Mar 20, 2026
Copilot AI requested a review from strawgate March 20, 2026 18:21
@strawgate strawgate marked this pull request as ready for review March 20, 2026 18:50
@strawgate strawgate requested a review from a team as a code owner March 20, 2026 18:50
@strawgate strawgate requested a review from faec March 20, 2026 18:50
@coderabbitai
Copy link

coderabbitai bot commented Mar 20, 2026

📝 Walkthrough

Walkthrough

The PR modifies the Network.Check method in libbeat/conditions/network.go to directly handle different input types (string, net.IP, []net.IP, []string) via type assertion instead of using a universal extractIP function followed by slices.ContainsFunc. New helper functions containsAny and containsAnyStr were introduced, and the previous extractIP utility was removed. The change preserves existing behavior for all supported types while handling invalid values consistently.

🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR implements all objectives from #49574: type-switch fast-path for string/net.IP, loop handling for slices, extractIP removal, and demonstrates 22% faster, 60% less memory, 50% fewer allocations.
Out of Scope Changes check ✅ Passed All changes (type switch, helper functions, extractIP removal, slices import removal) are directly scoped to optimize Network.Check's single-IP path as specified in #49574.

✏️ 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 copilot/optimize-network-check-ip-path
  • 🛠️ Update Documentation: Commit on current branch
  • 🛠️ Update Documentation: Create PR

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

Copy link

@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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@libbeat/conditions/network.go`:
- Around line 166-176: The net.IP branch in the matcher (inside Check) does not
guard against nil or zero-length IPs, so calls like network.Contains(v) can
treat invalid IPs as matches; update the net.IP case to first reject nil or
len(v) == 0 and return false, and similarly ensure containsAny (and
containsAnyStr for string slices) skips or rejects empty/invalid entries in the
[]net.IP and []string branches before calling network.Contains (i.e., add a
nil/len==0 check for v in the net.IP case and ensure containsAny handles
zero-length net.IP elements).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9740e2e9-20f7-424e-83c6-9136c930797e

📥 Commits

Reviewing files that changed from the base of the PR and between d09baaf and 70d5cb6.

📒 Files selected for processing (1)
  • libbeat/conditions/network.go

Comment on lines +166 to +176
case net.IP:
if !network.Contains(v) {
return false
}
case []net.IP:
if len(v) == 0 || !containsAny(v, network.Contains) {
return false
}
case []string:
if len(v) == 0 || !containsAnyStr(v, network.Contains) {
return false
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Invalid net.IP values can incorrectly match public and pass Check.

On Line 166 and Line 188, net.IP(nil) / zero-length IPs are not rejected before network.Contains(...). For the public matcher, invalid IPs can evaluate as a match, causing false positives.

Proposed fix
 func (c *Network) Check(event ValuesMap) bool {
@@
 		case net.IP:
-			if !network.Contains(v) {
+			if v == nil || v.To16() == nil || !network.Contains(v) {
 				return false
 			}
@@
 func containsAny(ips []net.IP, match func(net.IP) bool) bool {
 	for _, ip := range ips {
+		if ip == nil || ip.To16() == nil {
+			continue
+		}
 		if match(ip) {
 			return true
 		}
 	}
 	return false
 }

Also applies to: 188-193

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libbeat/conditions/network.go` around lines 166 - 176, The net.IP branch in
the matcher (inside Check) does not guard against nil or zero-length IPs, so
calls like network.Contains(v) can treat invalid IPs as matches; update the
net.IP case to first reject nil or len(v) == 0 and return false, and similarly
ensure containsAny (and containsAnyStr for string slices) skips or rejects
empty/invalid entries in the []net.IP and []string branches before calling
network.Contains (i.e., add a nil/len==0 check for v in the net.IP case and
ensure containsAny handles zero-length net.IP elements).

@pierrehilbert pierrehilbert added the Team:Elastic-Agent-Data-Plane Label for the Agent Data Plane team label Mar 23, 2026
@elasticmachine
Copy link
Contributor

Pinging @elastic/elastic-agent-data-plane (Team:Elastic-Agent-Data-Plane)

@botelastic botelastic bot removed the needs_team Indicates that the issue/PR needs a Team:* label label Mar 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Team:Elastic-Agent-Data-Plane Label for the Agent Data Plane team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[performance-profiler] Optimize Network.Check single-IP path to reduce allocations and CPU

4 participants