Skip to content

[release-6.6] test(metrics): add functional tests verifying component_sent_bytes_total carries component_id labels - #3382

Merged
openshift-merge-bot[bot] merged 1 commit into
openshift:release-6.6from
openshift-cherrypick-robot:cherry-pick-3379-to-release-6.6
Jul 30, 2026
Merged

[release-6.6] test(metrics): add functional tests verifying component_sent_bytes_total carries component_id labels#3382
openshift-merge-bot[bot] merged 1 commit into
openshift:release-6.6from
openshift-cherrypick-robot:cherry-pick-3379-to-release-6.6

Conversation

@openshift-cherrypick-robot

Copy link
Copy Markdown

This is an automated cherry-pick of #3379

/assign Clee2691

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 2c872d06-1b8a-49ca-91b0-0b9ee9670f28

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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

@openshift-ci
openshift-ci Bot requested review from alanconway and vparfonov July 30, 2026 18:10
@qodo-for-rh-openshift

qodo-for-rh-openshift Bot commented Jul 30, 2026

Copy link
Copy Markdown

PR Summary by Qodo

Add functional metrics tests for component_sent_bytes_total label coverage

🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Add framework helpers to grant RBAC and scrape collector /metrics in tests.
• Add regression tests for AWS sinks ensuring component_sent_bytes_total keeps component_id labels.
• Add HTTP output metrics test as a positive control and tidy HTTP tuning setup.
Diagram

graph TD
  T["Functional output tests"] --> F["CollectorFunctionalFramework"] --> K["Kubernetes API"] --> R[("Cluster RBAC")]
  F --> C["Collector pod"] --> M["/metrics endpoint"]
  F --> P["CollectMetricLines (curl)"] --> M
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Use a Prometheus text parser and stricter label assertions
  • ➕ More robust than substring checks (avoids false positives/negatives)
  • ➕ Can assert exact label sets and detect duplicate series reliably
  • ➖ Adds parsing complexity/dependencies in the test framework
  • ➖ May be overkill for a targeted regression guard
2. Scrape metrics via port-forward from the test runner instead of in-cluster curl
  • ➕ Avoids cluster-scoped RBAC creation in tests
  • ➕ Potentially simpler debugging from the runner environment
  • ➖ More moving parts (port-forward lifecycle, local networking)
  • ➖ Can be flakier in CI and harder to parallelize safely
3. Centralize RBAC lifecycle in the framework (auto-create + auto-cleanup)
  • ➕ Reduces repetition across CloudWatch/S3/HTTP tests
  • ➕ Less risk of forgetting cleanup in future tests
  • ➖ May create RBAC even for tests that never scrape metrics
  • ➖ Needs careful naming/ownership to keep parallel runs isolated

Recommendation: The PR’s approach (in-cluster curl with minimal RBAC + polling until the metric appears) is pragmatic and fits functional testing constraints. If these metrics checks expand, consider parsing the Prometheus exposition format to assert exact labelsets and reliably detect unlabeled duplicate series, but for a LOG-7893 regression guard the current substring-based validation is an acceptable tradeoff.

Files changed (4) +221 / -17

Tests (4) +221 / -17
metrics.goAdd RBAC setup and metric-scraping helpers for functional tests +87/-0

Add RBAC setup and metric-scraping helpers for functional tests

• Introduces SetupMetricsRBAC to create cluster-scoped permissions for GET /metrics and token review delegation. Adds CollectMetricLines, which polls the collector metrics endpoint via curl and returns matching metric lines once an expected label fragment appears.

test/framework/functional/metrics.go

forward_to_cloudwatch_test.goAdd CloudWatch metrics regression test for [LOG-7893](https://redhat.atlassian.net/browse/LOG-7893) +45/-0

Add CloudWatch metrics regression test for LOG-7893

• Adds a new context that provisions metrics-scrape RBAC, deploys a CloudWatch output, and asserts component_sent_bytes_total includes component_id (and region for the CloudWatch series). Also checks for unlabeled transport-layer duplicate series by requiring component_id on all matching lines.

test/functional/outputs/aws/cloudwatch/forward_to_cloudwatch_test.go

forward_to_s3_test.goAdd S3 metrics regression test for [LOG-7893](https://redhat.atlassian.net/browse/LOG-7893) +46/-0

Add S3 metrics regression test for LOG-7893

• Adds a new context that provisions metrics-scrape RBAC, deploys an S3 output, and asserts component_sent_bytes_total includes component_id (and region for the S3 series). Ensures no unlabeled duplicate series are emitted by requiring component_id on all matching metric lines.

test/functional/outputs/aws/s3/forward_to_s3_test.go

forward_to_http_test.goAdd HTTP output metrics positive-control test and simplify tuning setup +43/-17

Add HTTP output metrics positive-control test and simplify tuning setup

• Refactors the compression tuning setup to directly mutate the output spec and inject the HTTP destination container inline. Adds a metrics test that verifies component_sent_bytes_total carries component_id for the HTTP output as a positive control alongside the AWS regression coverage.

test/functional/outputs/http/forward_to_http_test.go

@Clee2691

Copy link
Copy Markdown
Contributor

@Clee2691

Copy link
Copy Markdown
Contributor

/assign @jcantrill

@qodo-for-rh-openshift

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (3) 📘 Rule violations (0) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 9 rules

Grey Divider


Remediation recommended

1. Overbroad metric matching 🐞 Bug ☼ Reliability
Description
CollectMetricLines selects lines using strings.Contains(line, metricName), which can accidentally
include non-target series whose names merely contain the substring (e.g., similarly named metrics),
making the new tests brittle and potentially failing for unrelated metric lines. The repo’s
canonical metric name is vector_component_sent_bytes_total, but the new tests pass the shorter
component_sent_bytes_total substring, relying on this imprecise matching.
Code

test/framework/functional/metrics.go[R68-75]

+		for _, line := range strings.Split(raw, "\n") {
+			if strings.HasPrefix(line, "#") {
+				continue
+			}
+			if strings.Contains(line, metricName) {
+				matched = append(matched, line)
+			}
+		}
Relevance

●● Moderate

Exact-metric-token matching was suggested in PR #3379, but no prior accepted precedent for
tightening Contains-based matching.

PR-#3379

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The helper currently adds any non-comment line that merely contains metricName, and the new tests
pass only the substring component_sent_bytes_total while the metric allowlist/docs use the full
vector_component_sent_bytes_total name, demonstrating the mismatch and brittleness.

test/framework/functional/metrics.go[54-82]
test/functional/outputs/aws/cloudwatch/forward_to_cloudwatch_test.go[245-286]
internal/metrics/relabel.go[19-37]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`CollectMetricLines()` currently uses substring matching (`strings.Contains`) to collect metric lines. This can unintentionally match other series that merely contain the substring, making tests flaky/brittle and diagnostics confusing.

### Issue Context
The repo’s canonical metric name is `vector_component_sent_bytes_total`, but the new tests call `CollectMetricLines("component_sent_bytes_total", ...)`, depending on substring matching.

### Fix Focus Areas
- test/framework/functional/metrics.go[54-82]
- test/functional/outputs/aws/cloudwatch/forward_to_cloudwatch_test.go[245-286]

### Implementation guidance
- Parse the metric token (the substring before the first `{` or whitespace) and compare it to an **exact** metric name.
- Update call sites to pass the full metric name (e.g. `vector_component_sent_bytes_total`) and match with `HasPrefix(line, metricName+"{")` / token parse.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. RBAC setup leaks on failure 🐞 Bug ☼ Reliability
Description
SetupMetricsRBAC returns early on create errors without deleting any previously created
cluster-scoped RBAC objects, so a mid-way failure leaves ClusterRoles/ClusterRoleBindings behind.
Since caller cleanup is only registered after SetupMetricsRBAC returns successfully, partial
failures are not cleaned up.
Code

test/framework/functional/metrics.go[R24-49]

+	metricsReaderRole = runtime.NewClusterRole(
+		roleName,
+		runtime.NewNonResourceURLPolicyRule([]string{"/metrics"}, []string{"get"}),
+	)
+	if err = f.Test.Create(metricsReaderRole); err != nil {
+		return nil, nil, nil, err
+	}
+
+	metricsReaderBinding = runtime.NewClusterRoleBinding(
+		roleName,
+		runtime.NewClusterRoleRef(roleName),
+		runtime.NewServiceAccountSubject("default", f.Namespace),
+	)
+	if err = f.Test.Create(metricsReaderBinding); err != nil {
+		return nil, nil, nil, err
+	}
+
+	tokenReviewName := fmt.Sprintf("%s-%s-token-reviewer", f.Test.NS.Name, f.Name)
+	tokenReviewBinding = runtime.NewClusterRoleBinding(
+		tokenReviewName,
+		runtime.NewClusterRoleRef("system:auth-delegator"),
+		runtime.NewServiceAccountSubject("default", f.Namespace),
+	)
+	if err = f.Test.Create(tokenReviewBinding); err != nil {
+		return nil, nil, nil, err
+	}
Relevance

●● Moderate

Rollback-on-failure was flagged in PR #3379 review, but no evidence it was actually fixed/accepted
historically.

PR-#3379

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The function creates the ClusterRole, then the ClusterRoleBinding(s), and returns err immediately
on failure without any rollback, which leaks cluster-scoped resources when a later create fails.

test/framework/functional/metrics.go[24-49]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`SetupMetricsRBAC()` creates multiple cluster-scoped RBAC resources sequentially. If creation fails mid-way, earlier-created resources are leaked because the function returns immediately and callers only register cleanup after a successful return.

### Issue Context
This affects functional test runs by leaving cluster-wide RBAC artifacts behind on transient failures (API errors, timeouts, AlreadyExists, etc.).

### Fix Focus Areas
- test/framework/functional/metrics.go[24-49]

### Implementation guidance
- Track successfully-created objects and, on any subsequent error, delete the already-created ones before returning.
- Alternatively, register internal deferred rollback logic within `SetupMetricsRBAC()`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

3. Misleading cleanup comment 🐞 Bug ⚙ Maintainability
Description
SetupMetricsRBAC’s doc comment claims it “returns a function” that deletes created resources, but
the function actually returns RBAC objects and an error. This mismatch can mislead future callers
into missing required cleanup.
Code

test/framework/functional/metrics.go[R16-22]

+// SetupMetricsRBAC creates the cluster-scoped RBAC resources needed to scrape
+// the collector's /metrics endpoint from within a test pod. Names are prefixed
+// with the framework's namespace so parallel test packages cannot collide.
+// The returned function deletes all created resources and should be registered
+// with DeferCleanup or called in AfterEach.
+func (f *CollectorFunctionalFramework) SetupMetricsRBAC() (metricsReaderRole *rbacv1.ClusterRole, metricsReaderBinding *rbacv1.ClusterRoleBinding, tokenReviewBinding *rbacv1.ClusterRoleBinding, err error) {
+	roleName := fmt.Sprintf("%s-%s-metrics-reader", f.Test.NS.Name, f.Name)
Relevance

●●● Strong

Team frequently accepts doc/comment correctness updates (e.g., accepted wording fixes in PR #3251).

PR-#3251

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The comment explicitly describes returning a cleanup function, but the signature returns three RBAC
objects; the contradiction is in the newly added helper itself.

test/framework/functional/metrics.go[16-22]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
The doc comment for `SetupMetricsRBAC` states it returns a cleanup function, but the function signature returns RBAC objects. This is misleading and can cause future misuse/leaks.

### Issue Context
Call sites currently perform cleanup themselves.

### Fix Focus Areas
- test/framework/functional/metrics.go[16-22]

### Implementation guidance
- Update the comment to describe that the function returns the created objects and the caller must delete them, OR change the API to actually return a cleanup function.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

Comment on lines +68 to +75
for _, line := range strings.Split(raw, "\n") {
if strings.HasPrefix(line, "#") {
continue
}
if strings.Contains(line, metricName) {
matched = append(matched, line)
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Remediation recommended

1. Overbroad metric matching 🐞 Bug ☼ Reliability

CollectMetricLines selects lines using strings.Contains(line, metricName), which can accidentally
include non-target series whose names merely contain the substring (e.g., similarly named metrics),
making the new tests brittle and potentially failing for unrelated metric lines. The repo’s
canonical metric name is vector_component_sent_bytes_total, but the new tests pass the shorter
component_sent_bytes_total substring, relying on this imprecise matching.
Agent Prompt
### Issue description
`CollectMetricLines()` currently uses substring matching (`strings.Contains`) to collect metric lines. This can unintentionally match other series that merely contain the substring, making tests flaky/brittle and diagnostics confusing.

### Issue Context
The repo’s canonical metric name is `vector_component_sent_bytes_total`, but the new tests call `CollectMetricLines("component_sent_bytes_total", ...)`, depending on substring matching.

### Fix Focus Areas
- test/framework/functional/metrics.go[54-82]
- test/functional/outputs/aws/cloudwatch/forward_to_cloudwatch_test.go[245-286]

### Implementation guidance
- Parse the metric token (the substring before the first `{` or whitespace) and compare it to an **exact** metric name.
- Update call sites to pass the full metric name (e.g. `vector_component_sent_bytes_total`) and match with `HasPrefix(line, metricName+"{")` / token parse.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +24 to +49
metricsReaderRole = runtime.NewClusterRole(
roleName,
runtime.NewNonResourceURLPolicyRule([]string{"/metrics"}, []string{"get"}),
)
if err = f.Test.Create(metricsReaderRole); err != nil {
return nil, nil, nil, err
}

metricsReaderBinding = runtime.NewClusterRoleBinding(
roleName,
runtime.NewClusterRoleRef(roleName),
runtime.NewServiceAccountSubject("default", f.Namespace),
)
if err = f.Test.Create(metricsReaderBinding); err != nil {
return nil, nil, nil, err
}

tokenReviewName := fmt.Sprintf("%s-%s-token-reviewer", f.Test.NS.Name, f.Name)
tokenReviewBinding = runtime.NewClusterRoleBinding(
tokenReviewName,
runtime.NewClusterRoleRef("system:auth-delegator"),
runtime.NewServiceAccountSubject("default", f.Namespace),
)
if err = f.Test.Create(tokenReviewBinding); err != nil {
return nil, nil, nil, err
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Remediation recommended

2. Rbac setup leaks on failure 🐞 Bug ☼ Reliability

SetupMetricsRBAC returns early on create errors without deleting any previously created
cluster-scoped RBAC objects, so a mid-way failure leaves ClusterRoles/ClusterRoleBindings behind.
Since caller cleanup is only registered after SetupMetricsRBAC returns successfully, partial
failures are not cleaned up.
Agent Prompt
### Issue description
`SetupMetricsRBAC()` creates multiple cluster-scoped RBAC resources sequentially. If creation fails mid-way, earlier-created resources are leaked because the function returns immediately and callers only register cleanup after a successful return.

### Issue Context
This affects functional test runs by leaving cluster-wide RBAC artifacts behind on transient failures (API errors, timeouts, AlreadyExists, etc.).

### Fix Focus Areas
- test/framework/functional/metrics.go[24-49]

### Implementation guidance
- Track successfully-created objects and, on any subsequent error, delete the already-created ones before returning.
- Alternatively, register internal deferred rollback logic within `SetupMetricsRBAC()`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment on lines +16 to +22
// SetupMetricsRBAC creates the cluster-scoped RBAC resources needed to scrape
// the collector's /metrics endpoint from within a test pod. Names are prefixed
// with the framework's namespace so parallel test packages cannot collide.
// The returned function deletes all created resources and should be registered
// with DeferCleanup or called in AfterEach.
func (f *CollectorFunctionalFramework) SetupMetricsRBAC() (metricsReaderRole *rbacv1.ClusterRole, metricsReaderBinding *rbacv1.ClusterRoleBinding, tokenReviewBinding *rbacv1.ClusterRoleBinding, err error) {
roleName := fmt.Sprintf("%s-%s-metrics-reader", f.Test.NS.Name, f.Name)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Informational

3. Misleading cleanup comment 🐞 Bug ⚙ Maintainability

SetupMetricsRBAC’s doc comment claims it “returns a function” that deletes created resources, but
the function actually returns RBAC objects and an error. This mismatch can mislead future callers
into missing required cleanup.
Agent Prompt
### Issue description
The doc comment for `SetupMetricsRBAC` states it returns a cleanup function, but the function signature returns RBAC objects. This is misleading and can cause future misuse/leaks.

### Issue Context
Call sites currently perform cleanup themselves.

### Fix Focus Areas
- test/framework/functional/metrics.go[16-22]

### Implementation guidance
- Update the comment to describe that the function returns the created objects and the caller must delete them, OR change the API to actually return a cleanup function.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

@openshift-ci

openshift-ci Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

@openshift-cherrypick-robot: all tests passed!

Full PR test history. Your PR dashboard.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. I understand the commands that are listed here.

@jcantrill

Copy link
Copy Markdown
Contributor

/approve
/lgtm

@openshift-ci openshift-ci Bot added the lgtm Indicates that a PR is ready to be merged. label Jul 30, 2026
@openshift-ci

openshift-ci Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: jcantrill, openshift-cherrypick-robot

The full list of commands accepted by this bot can be found here.

The pull request process is described here

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@openshift-ci openshift-ci Bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Jul 30, 2026
@openshift-merge-bot
openshift-merge-bot Bot merged commit 2093483 into openshift:release-6.6 Jul 30, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files. lgtm Indicates that a PR is ready to be merged. release/6.6

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants