Skip to content

BTP: add backend-targeted BackendTrafficPolicy - #8890

Closed
muwaqar-cflt wants to merge 19 commits into
envoyproxy:mainfrom
muwaqar:backend-level-btp
Closed

muwaqar-cflt wants to merge 19 commits into
envoyproxy:mainfrom
muwaqar:backend-level-btp

Conversation

@muwaqar-cflt

@muwaqar-cflt muwaqar-cflt commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR extends BackendTrafficPolicy to support a third target level — Backend (Service, ServiceImport, EG Backend) — so a Service Owner can create one Backend-targeted BTP to specify CDS configuration (health checks, circuit breakers, load balancer, etc.) for their service. The translator applies those settings to every cluster generated for routes pointing to that backend, eliminating per-route duplication.

Design doc: #8844

Key changes

  • Feature flag: MergeBackends on EnvoyProxy.spec (follows MergeGateways pattern)
  • CEL validation: Backend kinds (Service, ServiceImport, Backend) allowed in targetRef/targetRefs with group-kind pair validation; RDS fields rejected; sectionName rejected
  • Translator: New processing phase between Route and Listener phases; 3-level merge hierarchy (Gateway → Backend → Route) with mergeType support
  • Per-rule merge: Backend BTP lookup happens per route rule during translation — different rules on the same route can merge with different backend BTPs based on which backend each rule points to
  • Conflict detection: Backend-to-backend ownership conflicts via backendPolicyMap winner check; multi-backend route rule rejection
  • Status reporting: Accepted, Merged, Disabled conditions on BTP ancestors; UnsupportedBackendTrafficPolicy on routes with multiple backendRefs per rule

Multi-backend route rule limitation

Route rules with multiple backendRefs are rejected when mergeBackends is enabled. This is an interim measure (Solution 1 from the design doc §7.5). The recommended long-term solution (Solution 4) is to produce per-backend clusters with weighted routing — consistent with how EG already uses weighted clusters via NeedsClusterPerSetting() for other triggers. See §7.5 for the full analysis.

@muwaqar-cflt
muwaqar-cflt requested a review from a team as a code owner April 29, 2026 18:54
@netlify

netlify Bot commented Apr 29, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for cerulean-figolla-1f9435 ready!

Name Link
🔨 Latest commit d87ae16
🔍 Latest deploy log https://app.netlify.com/projects/cerulean-figolla-1f9435/deploys/6a316d6f7fbc4d0008cbb1c0
😎 Deploy Preview https://deploy-preview-8890--cerulean-figolla-1f9435.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3f4f44d8ba

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@@ -39,10 +39,21 @@ type BackendTrafficPolicy struct {
// BackendTrafficPolicySpec defines the desired state of BackendTrafficPolicy.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nit: It might be worth adding some sentences here to clarify which fields apply to which types of targets. Then the generated API docs can give users clearer guidance on how to use BackendTrafficPolicy with Backends versus Routes or Gateways.

// +kubebuilder:validation:XValidation:rule="has(self.targetRefs) ? self.targetRefs.all(ref, ref.group == 'gateway.networking.k8s.io') : true ", message="this policy can only have a targetRefs[*].group of gateway.networking.k8s.io"
// +kubebuilder:validation:XValidation:rule="has(self.targetRefs) ? self.targetRefs.all(ref, ref.kind in ['Gateway', 'HTTPRoute', 'GRPCRoute', 'UDPRoute', 'TCPRoute', 'TLSRoute']) : true ", message="this policy can only have a targetRefs[*].kind of Gateway/HTTPRoute/GRPCRoute/TCPRoute/UDPRoute/TLSRoute"
// +kubebuilder:validation:XValidation:rule="has(self.targetRef) ? (self.targetRef.group == 'gateway.networking.k8s.io' && self.targetRef.kind in ['Gateway', 'HTTPRoute', 'GRPCRoute', 'UDPRoute', 'TCPRoute', 'TLSRoute']) || (self.targetRef.group == '' && self.targetRef.kind == 'Service') || (self.targetRef.group == 'multicluster.x-k8s.io' && self.targetRef.kind == 'ServiceImport') || (self.targetRef.group == 'gateway.envoyproxy.io' && self.targetRef.kind == 'Backend') : true", message="invalid targetRef group/kind combination"
// +kubebuilder:validation:XValidation:rule="has(self.targetRefs) ? self.targetRefs.all(ref, (ref.group == 'gateway.networking.k8s.io' && ref.kind in ['Gateway', 'HTTPRoute', 'GRPCRoute', 'UDPRoute', 'TCPRoute', 'TLSRoute']) || (ref.group == '' && ref.kind == 'Service') || (ref.group == 'multicluster.x-k8s.io' && ref.kind == 'ServiceImport') || (ref.group == 'gateway.envoyproxy.io' && ref.kind == 'Backend')) : true", message="invalid targetRefs group/kind combination"

@zhaohuabing zhaohuabing Apr 30, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Non-blocking nit: It's nice to have CEL validations for unsupported features for Backend targets. Previously, some fields were silently ignored for TCPRoute/UDPRoute, so we may want to make the behavior consistent by also applying CEL validation for them.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

does somebody have context on which fields are ignored for TCPRoute/UDPRoute and can be validated on here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Filed #8897 to track this. Agree it would be good to add CEL validation for TCPRoute/UDPRoute unsupported fields for consistency, but keeping it out of this PR to avoid scope creep.

@zhaohuabing

zhaohuabing commented Apr 30, 2026 •

Copy link
Copy Markdown
Member

Would it make sense to group the backend-related fields together?

That might make it easier to reason about which fields are applicable to which target types.

type BackendTrafficSettings struct {
	LoadBalancer  *LoadBalancer `json:"loadBalancer,omitempty"`
	ProxyProtocol *ProxyProtocol `json:"proxyProtocol,omitempty"`
	TCPKeepalive *TCPKeepalive `json:"tcpKeepalive,omitempty"`
	HealthCheck *HealthCheck `json:"healthCheck,omitempty"`
	CircuitBreaker *CircuitBreaker `json:"circuitBreaker,omitempty"`
	Timeout *Timeout `json:"timeout,omitempty"`
	Connection *BackendConnection `json:"connection,omitempty"`
	DNS *DNS `json:"dns,omitempty"`
	HTTP2 *HTTP2Settings `json:"http2,omitempty"`
}

type ClusterSettings struct {
	BackendConnectionSettings `json:",inline"`

	// Retry is applicable for traffic to non-route upstream services like jwt providers or oidc providers.
	Retry *Retry `json:"retry,omitempty"`
}

We might also want to rename ClusterSettings to other names like UpstreamServiceSettings, since ClusterSettings has become a bit ambiguous now.

@muwaqar-cflt

Copy link
Copy Markdown
Contributor Author

Filed #8898 to track the BackendClusterSettings struct split. This will make the Backend-target vs Route/Gateway field boundary a struct-level guarantee. Keeping it as a follow-up to avoid making this PR harder to follow.

@zhaohuabing

zhaohuabing commented May 21, 2026 •

Copy link
Copy Markdown
Member

Hi @muwaqar-cflt does this PR also address the cluster duplication issue, or will that come in a follow-up PR?

If I recall correctly, @arkodg proposed that we should only allow targeting backends when clusters are created per backend(MergeBackends=true), and we agreed on that.

@zhaohuabing zhaohuabing added this to the v1.9.0-rc.1 Release milestone May 22, 2026
@muwaqar-cflt

Copy link
Copy Markdown
Contributor Author

Hi @zhaohuabing — yes, the last commit (168813f) already moved the feature flag to MergeBackends on EnvoyProxy.spec, per the agreement with @arkodg that Backend-targeted BTP should only be enabled when cluster deduplication is in effect.

Cluster deduplication itself (N:1 shared clusters) will come in a follow-up PR. This PR is already fairly large with the API changes, CEL validation, translator phase, conflict detection, and status reporting — adding the topology change on top would make it hard to review.

@zhaohuabing

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6d7cc412f7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Required fixes

  • internal/gatewayapi/backendtrafficpolicy.go:1568-1571: The status message for the disabled feature flag still references enableBackendTargetsInBackendTrafficPolicy, but this PR introduces mergeBackends/MergeBackends as the actual flag. This is user-facing and will mislead users enabling the feature.

Optional follow-ups

  • This PR combines API/CEL validation updates, translator behavior changes, generated CRDs, docs, and extensive golden testdata updates. If review/merge risk becomes an issue, consider splitting API/CRD/docs from translator behavior changes in a follow-up PR.

This PR adds support for backend-targeted BackendTrafficPolicy (Service/ServiceImport/Backend) gated behind a new EnvoyProxy.spec.mergeBackends feature flag, and updates CEL validations, translator behavior, status reporting, docs, release notes, and golden testdata to support the new target level and merge hierarchy.

Changes:

  • Add mergeBackends to EnvoyProxySpec and wire it through the runner/translator.
  • Extend BackendTrafficPolicy CEL validation to allow backend targets and to restrict backend-targeted policies to CDS-only fields (rejecting RDS fields and sectionName).
  • Add translator golden tests and testdata covering gateway/backend/route merge behavior and multi-backend rule rejection status.

Reviewed changes

Copilot reviewed 51 out of 56 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
test/helm/gateway-crds-helm/envoy-gateway-crds.out.yaml Update generated CRD output (CEL + mergeBackends).
test/helm/gateway-crds-helm/e2e.out.yaml Update generated CRD output (CEL + mergeBackends).
test/helm/gateway-crds-helm/all.out.yaml Update generated CRD output (CEL + mergeBackends).
test/cel-validation/backendtrafficpolicy_test.go Update/add CEL validation coverage for backend targets and field restrictions.
site/content/en/latest/api/extension_types.md Document mergeBackends in EnvoyProxy API docs.
release-notes/current.yaml Add release note entry for backend-targeted BTP behind MergeBackends.
internal/gatewayapi/translator.go Add MergeBackends flag to Translator config.
internal/gatewayapi/translator_test.go Add translator golden test cases for backend-targeted BTP scenarios.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-with-route-no-merge.in.yaml New golden input for backend-targeted + route-targeted merge scenarios.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-with-route-no-merge.out.yaml New golden output for backend-targeted + route-targeted merge scenarios.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-with-route-merge-no-gateway.in.yaml New golden input for route merge without gateway policy.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-with-route-merge-no-gateway.out.yaml New golden output for route merge without gateway policy.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-with-route-merge-backend-no-merge.in.yaml New golden input for merge chain stopping at backend.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-with-route-merge-backend-no-merge.out.yaml New golden output for merge chain stopping at backend.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-with-route-merge-backend-merge.in.yaml New golden input for gateway→backend→route strategic merge.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-with-route-merge-backend-merge.out.yaml New golden output for gateway→backend→route strategic merge.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-with-gateway-no-merge.in.yaml New golden input for backend policy without inheriting gateway defaults.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-with-gateway-no-merge.out.yaml New golden output for backend policy without inheriting gateway defaults.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-with-gateway-merge.in.yaml New golden input for backend policy inheriting gateway defaults.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-with-gateway-merge.out.yaml New golden output for backend policy inheriting gateway defaults.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-udp-basic.in.yaml New UDP golden input for backend-targeted BTP.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-udp-basic.out.yaml New UDP golden output for backend-targeted BTP.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-udp-with-route-merge-backend-merge.in.yaml New UDP golden input for route+backend+gateway merge.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-udp-with-route-merge-backend-merge.out.yaml New UDP golden output for route+backend+gateway merge.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-udp-multi-backend-partial-coverage.in.yaml New UDP golden input for multi-backend rule rejection.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-udp-multi-backend-partial-coverage.out.yaml New UDP golden output for multi-backend rule rejection.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-tcp-basic.in.yaml New TCP golden input for backend-targeted BTP.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-tcp-basic.out.yaml New TCP golden output for backend-targeted BTP.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-tcp-with-route-merge-backend-merge.in.yaml New TCP golden input for route+backend+gateway merge.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-tcp-with-route-merge-backend-merge.out.yaml New TCP golden output for route+backend+gateway merge.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-tcp-multi-backend-partial-coverage.in.yaml New TCP golden input for multi-backend rule rejection.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-tcp-multi-backend-partial-coverage.out.yaml New TCP golden output for multi-backend rule rejection.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-multi-rule-route.in.yaml New golden input for per-rule sectionName BTP + multi-backend rule rejection.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-multi-rule-route.out.yaml New golden output for per-rule sectionName BTP + multi-backend rule rejection.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-multi-backend-same-btp.in.yaml New golden input for multi-backend rule with shared backend policy (still rejected per limitation).
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-multi-backend-same-btp.out.yaml New golden output for multi-backend rule with shared backend policy (still rejected per limitation).
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-multi-backend-partial-coverage.in.yaml New golden input for partial backend policy coverage case.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-multi-backend-partial-coverage.out.yaml New golden output for partial backend policy coverage case.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-multi-backend-different-btps.in.yaml New golden input for multi-backend rule with different backend policies (rejected per limitation).
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-multi-backend-different-btps.out.yaml New golden output for multi-backend rule with different backend policies (rejected per limitation).
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-feature-disabled.in.yaml New golden input for feature-flag-disabled behavior.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-feature-disabled.out.yaml New golden output for feature-flag-disabled behavior.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-basic.in.yaml New golden input for basic backend-targeted BTP behavior.
internal/gatewayapi/testdata/backendtrafficpolicy-backend-target-basic.out.yaml New golden output for basic backend-targeted BTP behavior.
internal/gatewayapi/status/error.go Add route condition reason for unsupported backend traffic policy scenarios.
internal/gatewayapi/runner/runner.go Wire MergeBackends into translator initialization.
internal/gatewayapi/helpers.go Add IsMergeBackendsEnabled helper and new internal key/context types.
internal/gatewayapi/backendtrafficpolicy_test.go Add unit coverage for backend-target kind detection helper.
charts/gateway-helm/charts/crds/crds/generated/gateway.envoyproxy.io_envoyproxies.yaml Update generated EnvoyProxy CRD with mergeBackends.
charts/gateway-helm/charts/crds/crds/generated/gateway.envoyproxy.io_backendtrafficpolicies.yaml Update generated BTP CRD with new CEL validation rules.
charts/gateway-crds-helm/templates/generated/gateway.envoyproxy.io_envoyproxies.yaml Update templated EnvoyProxy CRD with mergeBackends.
charts/gateway-crds-helm/templates/generated/gateway.envoyproxy.io_backendtrafficpolicies.yaml Update templated BTP CRD with new CEL validation rules.
api/v1alpha1/zz_generated.deepcopy.go Add DeepCopy support for EnvoyProxySpec.MergeBackends.
api/v1alpha1/envoyproxy_types.go Add MergeBackends API field to EnvoyProxySpec.
api/v1alpha1/backendtrafficpolicy_types.go Update CEL validations to allow backend targets and restrict backend-targeted fields.
Files not reviewed (1)
  • api/v1alpha1/zz_generated.deepcopy.go: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@muwaqar-cflt
muwaqar-cflt force-pushed the backend-level-btp branch 3 times, most recently from 59cd03c to 2cfe400 Compare June 12, 2026 16:41
@codecov

codecov Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 74.77679% with 113 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.09%. Comparing base (9271654) to head (d87ae16).
⚠️ Report is 124 commits behind head on main.

Files with missing lines Patch % Lines
internal/gatewayapi/backendtrafficpolicy.go 75.70% 67 Missing and 37 partials ⚠️
internal/gatewayapi/helpers.go 0.00% 8 Missing ⚠️
internal/gatewayapi/runner/runner.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #8890      +/-   ##
==========================================
- Coverage   75.12%   75.09%   -0.04%     
==========================================
  Files         252      252              
  Lines       40882    41278     +396     
==========================================
+ Hits        30712    30996     +284     
- Misses       8079     8155      +76     
- Partials     2091     2127      +36     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@zhaohuabing

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2cfe40098b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@zhaohuabing

zhaohuabing commented Jun 16, 2026 •

Copy link
Copy Markdown
Member

Hi @zhaohuabing — yes, the last commit (168813f) already moved the feature flag to MergeBackends on EnvoyProxy.spec, per the agreement with @arkodg that Backend-targeted BTP should only be enabled when cluster deduplication is in effect.

Cluster deduplication itself (N:1 shared clusters) will come in a follow-up PR. This PR is already fairly large with the API changes, CEL validation, translator phase, conflict detection, and status reporting — adding the topology change on top would make it hard to review.

Hi @muwaqar-cflt thanks for clarifying. I’m a bit concerned that this PR enables more behavior than we agreed during the last meeting.

My understanding from the discussion is that backend-targeted BTP should only be enabled when backend cluster deduplication is actually in effect. In this PR, mergeBackends=true enables backend-targeted BTP attachment and translation, but the N:1 shared cluster topology is deferred to a follow-up. That creates an intermediate state where users can enable mergeBackends and rely on backend-targeted BTP behavior before cluster deduplication exists.

Could we reverse the order here: land the backend cluster deduplication PR first, then add backend-targeted BTP on top of that foundation? That would keep the feature flag semantics clear and avoid exposing a temporary behavior that is not the intended final contract.

I realize this PR already contains a lot of useful groundwork, especially the API/CEL/status pieces. We could reuse them after the deduplication PR lands.

@muwaqar-cflt

Copy link
Copy Markdown
Contributor Author

Hi @zhaohuabing — that's a fair concern. How about this: I'll remove the mergeBackends field from EnvoyProxySpec in this PR entirely, so there's no user-facing knob to enable backend-targeted BTP. All the internal plumbing (CEL validation, translator phase, conflict detection, status reporting, golden tests) stays but is unreachable since translator.MergeBackends defaults to false with no way to set it.

When the cluster dedup PR lands, it adds the mergeBackends API field and wires it through the runner — at that point both the topology and the policy attachment ship together, and the flag semantics are exactly what we agreed on.

I'd prefer to land this groundwork now rather than defer it behind the dedup PR. Cluster deduplication involves a significant refactor across the repo and may not land soon. In the meantime, this PR would remain open accumulating merge conflicts, and other contributors will keep changing BTP logic in the same files — piling onto the rebase burden for me as the PR author. Landing the foundational code incrementally avoids that while giving us the same end-state guarantee: no backend-targeted BTP without dedup.

@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been automatically marked as stale because it has not had activity in the last 30 days. Please feel free to give a status update now, ping for review, when it's ready. Thank you for your contributions!

@muwaqar-cflt

muwaqar-cflt commented Aug 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Closing this in favor of a fresh design rather than rebasing this branch.

A lot has landed on main since this was opened - the MergeBackends cluster-deduplication foundation this PR was gated on (#9477), the Selector restricting its scope (#9624), and per-listener/per-ListenerSet ClusterSettings divergence correctness fixes (#9695, #9692) - plus a generalized Gateway/ListenerSet policy-attachment framework (policyScopeGraph, listenerSetPolicyMap) that didn't exist when this branch was written. Rebasing this PR's mechanism (route-level Traffic mutation, per-route-rule routeRuleBackendPolicyMap matching) onto that framework would mean re-porting it wholesale rather than a normal rebase.

Also revisiting two things from the design doc/discussion here: Backend-targeted BTP should override Route-level BTP rather than the other way around, and mergeType should be required (not optional) on backend targets, since an unset mergeType would otherwise wholesale-replace rather than merge.

Thanks for all the review and discussion on this one @zhaohuabing @arkodg @kkk777-7.

muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Aug 13, 2026
…status parity from envoyproxy#8890

Replace independent group and kind allow-lists with a combined group/kind
pairing rule for targetRef and targetRefs, matching the fix from the
abandoned envoyproxy#8890 (invalid combinations like group: gateway.networking.k8s.io
with kind: Service previously passed admission since group and kind were
validated independently). Port envoyproxy#8890's comprehensive per-kind CEL test
matrix (valid CDS-only fields, reject-all-RDS-fields, sectionName rejection,
each across Service/ServiceImport/Backend and targetRef/targetRefs),
adapted to also require mergeType per this branch's own rule.

Rename isBackendTrafficPolicyTarget to isBackendTargetKind (also envoyproxy#8890's
name) - the old name read as checking whether a target is a
BackendTrafficPolicy, not whether its kind is a backend kind. Call
deprecatedFieldsUsedInBackendTrafficPolicy/
SetDeprecatedFieldsWarningForPolicyAncestors for backend-targeted policies
too, matching the other three scopes in this file (and envoyproxy#8890) - the helper
already exists and is already used uniformly elsewhere. Add a
non-generic MergedConditionMessage naming the actual gateway policy in the
Merged condition, replacing the static placeholder string; envoyproxy#8890's version
was generic over multiple merged-with policies (a shape this branch's
one-backend-to-one-gateway merge never has), so this only keeps the single
fallback case it actually needs.

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Aug 13, 2026
…d vs envoyproxy#8890

Three scenarios from envoyproxy#8890's fixture set were phase-1-relevant but not
exercised by any existing fixture here:

- partial-coverage: a rule with two backendRefs where only one has a
  backend-targeted policy - proves the untargeted backend's cluster is
  left untouched rather than treated as a conflict.
- multi-targetrefs-one-policy: a single BackendTrafficPolicy resource with
  plural targetRefs naming two backends, rather than one policy per
  backend - exercises processBackendTrafficPolicyForBackend being called
  twice for the same policy object, and confirms the resulting ancestor
  status is a single deduplicated entry, not doubled.
- tcp-basic: a merged cluster reached via TCPRoute rather than HTTPRoute -
  confirms the mechanism is protocol-agnostic (it only walks
  BackendClusters, never branches on route kind).

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Aug 13, 2026
… is off

Backend-targeted BackendTrafficPolicy previously had no code-level check
gating it on MergeBackends at all - when the flag was off, the policy
simply had nothing to attach to and silently did nothing, with no status
signal explaining why. This matches neither the original design doc
(which already described this as an explicit gate) nor envoyproxy#8890's own
prior-art behavior, and was flagged as an upstream-maintainer requirement
during that PR's review (feature should only be reachable once cluster
deduplication exists to make it meaningful).

Add an explicit per-gateway check in processBackendTrafficPolicyForBackend:
a gateway with mergeBackends disabled now gets an Accepted:False/Disabled
resolve error (reusing the existing egv1a1.PolicyReasonDisabled reason),
rather than silently doing nothing. Other reasons a backend might not
resolve to a merged cluster (dynamic resolver, per-listener divergence,
simply not referenced by any route) remain silent no-ops, since
mergeBackends being on is the one precondition this code can verify
directly - the rest depend on route.go's own eligibility decisions.

Split the mergebackends-btp-backend-target-unmerged-no-op fixture in two:
-mergebackends-disabled (the scenario this fix changes, now showing the
explicit Disabled status) and -unreferenced-no-op (a new fixture proving
the genuine silent no-op still holds when mergeBackends is on but the
backend is simply never referenced by a route).

Also corrects two inconsistencies between the design doc and the
code: the doc's Non-goals section previously lumped "mergeBackends
disabled" into the same silent-no-op bucket as other non-resolution
reasons, contradicting its own Resolution-and-merge section; and its
Status reporting section said ancestors are "the target backend" when
the code correctly uses each matched Gateway (matching BackendTLSPolicy's
own precedent).

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Aug 21, 2026
…status parity from envoyproxy#8890

Replace independent group and kind allow-lists with a combined group/kind
pairing rule for targetRef and targetRefs, matching the fix from the
abandoned envoyproxy#8890 (invalid combinations like group: gateway.networking.k8s.io
with kind: Service previously passed admission since group and kind were
validated independently). Port envoyproxy#8890's comprehensive per-kind CEL test
matrix (valid CDS-only fields, reject-all-RDS-fields, sectionName rejection,
each across Service/ServiceImport/Backend and targetRef/targetRefs),
adapted to also require mergeType per this branch's own rule.

Rename isBackendTrafficPolicyTarget to isBackendTargetKind (also envoyproxy#8890's
name) - the old name read as checking whether a target is a
BackendTrafficPolicy, not whether its kind is a backend kind. Call
deprecatedFieldsUsedInBackendTrafficPolicy/
SetDeprecatedFieldsWarningForPolicyAncestors for backend-targeted policies
too, matching the other three scopes in this file (and envoyproxy#8890) - the helper
already exists and is already used uniformly elsewhere. Add a
non-generic MergedConditionMessage naming the actual gateway policy in the
Merged condition, replacing the static placeholder string; envoyproxy#8890's version
was generic over multiple merged-with policies (a shape this branch's
one-backend-to-one-gateway merge never has), so this only keeps the single
fallback case it actually needs.

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Aug 21, 2026
…d vs envoyproxy#8890

Three scenarios from envoyproxy#8890's fixture set were phase-1-relevant but not
exercised by any existing fixture here:

- partial-coverage: a rule with two backendRefs where only one has a
  backend-targeted policy - proves the untargeted backend's cluster is
  left untouched rather than treated as a conflict.
- multi-targetrefs-one-policy: a single BackendTrafficPolicy resource with
  plural targetRefs naming two backends, rather than one policy per
  backend - exercises processBackendTrafficPolicyForBackend being called
  twice for the same policy object, and confirms the resulting ancestor
  status is a single deduplicated entry, not doubled.
- tcp-basic: a merged cluster reached via TCPRoute rather than HTTPRoute -
  confirms the mechanism is protocol-agnostic (it only walks
  BackendClusters, never branches on route kind).

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Aug 21, 2026
… is off

Backend-targeted BackendTrafficPolicy previously had no code-level check
gating it on MergeBackends at all - when the flag was off, the policy
simply had nothing to attach to and silently did nothing, with no status
signal explaining why. This matches neither the original design doc
(which already described this as an explicit gate) nor envoyproxy#8890's own
prior-art behavior, and was flagged as an upstream-maintainer requirement
during that PR's review (feature should only be reachable once cluster
deduplication exists to make it meaningful).

Add an explicit per-gateway check in processBackendTrafficPolicyForBackend:
a gateway with mergeBackends disabled now gets an Accepted:False/Disabled
resolve error (reusing the existing egv1a1.PolicyReasonDisabled reason),
rather than silently doing nothing. Other reasons a backend might not
resolve to a merged cluster (dynamic resolver, per-listener divergence,
simply not referenced by any route) remain silent no-ops, since
mergeBackends being on is the one precondition this code can verify
directly - the rest depend on route.go's own eligibility decisions.

Split the mergebackends-btp-backend-target-unmerged-no-op fixture in two:
-mergebackends-disabled (the scenario this fix changes, now showing the
explicit Disabled status) and -unreferenced-no-op (a new fixture proving
the genuine silent no-op still holds when mergeBackends is on but the
backend is simply never referenced by a route).

Also corrects two inconsistencies between the design doc and the
code: the doc's Non-goals section previously lumped "mergeBackends
disabled" into the same silent-no-op bucket as other non-resolution
reasons, contradicting its own Resolution-and-merge section; and its
Status reporting section said ancestors are "the target backend" when
the code correctly uses each matched Gateway (matching BackendTLSPolicy's
own precedent).

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Sep 9, 2026
…status parity from envoyproxy#8890

Replace independent group and kind allow-lists with a combined group/kind
pairing rule for targetRef and targetRefs, matching the fix from the
abandoned envoyproxy#8890 (invalid combinations like group: gateway.networking.k8s.io
with kind: Service previously passed admission since group and kind were
validated independently). Port envoyproxy#8890's comprehensive per-kind CEL test
matrix (valid CDS-only fields, reject-all-RDS-fields, sectionName rejection,
each across Service/ServiceImport/Backend and targetRef/targetRefs),
adapted to also require mergeType per this branch's own rule.

Rename isBackendTrafficPolicyTarget to isBackendTargetKind (also envoyproxy#8890's
name) - the old name read as checking whether a target is a
BackendTrafficPolicy, not whether its kind is a backend kind. Call
deprecatedFieldsUsedInBackendTrafficPolicy/
SetDeprecatedFieldsWarningForPolicyAncestors for backend-targeted policies
too, matching the other three scopes in this file (and envoyproxy#8890) - the helper
already exists and is already used uniformly elsewhere. Add a
non-generic MergedConditionMessage naming the actual gateway policy in the
Merged condition, replacing the static placeholder string; envoyproxy#8890's version
was generic over multiple merged-with policies (a shape this branch's
one-backend-to-one-gateway merge never has), so this only keeps the single
fallback case it actually needs.

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Sep 9, 2026
…d vs envoyproxy#8890

Three scenarios from envoyproxy#8890's fixture set were phase-1-relevant but not
exercised by any existing fixture here:

- partial-coverage: a rule with two backendRefs where only one has a
  backend-targeted policy - proves the untargeted backend's cluster is
  left untouched rather than treated as a conflict.
- multi-targetrefs-one-policy: a single BackendTrafficPolicy resource with
  plural targetRefs naming two backends, rather than one policy per
  backend - exercises processBackendTrafficPolicyForBackend being called
  twice for the same policy object, and confirms the resulting ancestor
  status is a single deduplicated entry, not doubled.
- tcp-basic: a merged cluster reached via TCPRoute rather than HTTPRoute -
  confirms the mechanism is protocol-agnostic (it only walks
  BackendClusters, never branches on route kind).

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Sep 9, 2026
… is off

Backend-targeted BackendTrafficPolicy previously had no code-level check
gating it on MergeBackends at all - when the flag was off, the policy
simply had nothing to attach to and silently did nothing, with no status
signal explaining why. This matches neither the original design doc
(which already described this as an explicit gate) nor envoyproxy#8890's own
prior-art behavior, and was flagged as an upstream-maintainer requirement
during that PR's review (feature should only be reachable once cluster
deduplication exists to make it meaningful).

Add an explicit per-gateway check in processBackendTrafficPolicyForBackend:
a gateway with mergeBackends disabled now gets an Accepted:False/Disabled
resolve error (reusing the existing egv1a1.PolicyReasonDisabled reason),
rather than silently doing nothing. Other reasons a backend might not
resolve to a merged cluster (dynamic resolver, per-listener divergence,
simply not referenced by any route) remain silent no-ops, since
mergeBackends being on is the one precondition this code can verify
directly - the rest depend on route.go's own eligibility decisions.

Split the mergebackends-btp-backend-target-unmerged-no-op fixture in two:
-mergebackends-disabled (the scenario this fix changes, now showing the
explicit Disabled status) and -unreferenced-no-op (a new fixture proving
the genuine silent no-op still holds when mergeBackends is on but the
backend is simply never referenced by a route).

Also corrects two inconsistencies between the design doc and the
code: the doc's Non-goals section previously lumped "mergeBackends
disabled" into the same silent-no-op bucket as other non-resolution
reasons, contradicting its own Resolution-and-merge section; and its
Status reporting section said ancestors are "the target backend" when
the code correctly uses each matched Gateway (matching BackendTLSPolicy's
own precedent).

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Sep 23, 2026
…status parity from envoyproxy#8890

Replace independent group and kind allow-lists with a combined group/kind
pairing rule for targetRef and targetRefs, matching the fix from the
abandoned envoyproxy#8890 (invalid combinations like group: gateway.networking.k8s.io
with kind: Service previously passed admission since group and kind were
validated independently). Port envoyproxy#8890's comprehensive per-kind CEL test
matrix (valid CDS-only fields, reject-all-RDS-fields, sectionName rejection,
each across Service/ServiceImport/Backend and targetRef/targetRefs),
adapted to also require mergeType per this branch's own rule.

Rename isBackendTrafficPolicyTarget to isBackendTargetKind (also envoyproxy#8890's
name) - the old name read as checking whether a target is a
BackendTrafficPolicy, not whether its kind is a backend kind. Call
deprecatedFieldsUsedInBackendTrafficPolicy/
SetDeprecatedFieldsWarningForPolicyAncestors for backend-targeted policies
too, matching the other three scopes in this file (and envoyproxy#8890) - the helper
already exists and is already used uniformly elsewhere. Add a
non-generic MergedConditionMessage naming the actual gateway policy in the
Merged condition, replacing the static placeholder string; envoyproxy#8890's version
was generic over multiple merged-with policies (a shape this branch's
one-backend-to-one-gateway merge never has), so this only keeps the single
fallback case it actually needs.

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Sep 23, 2026
…d vs envoyproxy#8890

Three scenarios from envoyproxy#8890's fixture set were phase-1-relevant but not
exercised by any existing fixture here:

- partial-coverage: a rule with two backendRefs where only one has a
  backend-targeted policy - proves the untargeted backend's cluster is
  left untouched rather than treated as a conflict.
- multi-targetrefs-one-policy: a single BackendTrafficPolicy resource with
  plural targetRefs naming two backends, rather than one policy per
  backend - exercises processBackendTrafficPolicyForBackend being called
  twice for the same policy object, and confirms the resulting ancestor
  status is a single deduplicated entry, not doubled.
- tcp-basic: a merged cluster reached via TCPRoute rather than HTTPRoute -
  confirms the mechanism is protocol-agnostic (it only walks
  BackendClusters, never branches on route kind).

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Sep 23, 2026
… is off

Backend-targeted BackendTrafficPolicy previously had no code-level check
gating it on MergeBackends at all - when the flag was off, the policy
simply had nothing to attach to and silently did nothing, with no status
signal explaining why. This matches neither the original design doc
(which already described this as an explicit gate) nor envoyproxy#8890's own
prior-art behavior, and was flagged as an upstream-maintainer requirement
during that PR's review (feature should only be reachable once cluster
deduplication exists to make it meaningful).

Add an explicit per-gateway check in processBackendTrafficPolicyForBackend:
a gateway with mergeBackends disabled now gets an Accepted:False/Disabled
resolve error (reusing the existing egv1a1.PolicyReasonDisabled reason),
rather than silently doing nothing. Other reasons a backend might not
resolve to a merged cluster (dynamic resolver, per-listener divergence,
simply not referenced by any route) remain silent no-ops, since
mergeBackends being on is the one precondition this code can verify
directly - the rest depend on route.go's own eligibility decisions.

Split the mergebackends-btp-backend-target-unmerged-no-op fixture in two:
-mergebackends-disabled (the scenario this fix changes, now showing the
explicit Disabled status) and -unreferenced-no-op (a new fixture proving
the genuine silent no-op still holds when mergeBackends is on but the
backend is simply never referenced by a route).

Also corrects two inconsistencies between the design doc and the
code: the doc's Non-goals section previously lumped "mergeBackends
disabled" into the same silent-no-op bucket as other non-resolution
reasons, contradicting its own Resolution-and-merge section; and its
Status reporting section said ancestors are "the target backend" when
the code correctly uses each matched Gateway (matching BackendTLSPolicy's
own precedent).

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Oct 6, 2026
…status parity from envoyproxy#8890

Replace independent group and kind allow-lists with a combined group/kind
pairing rule for targetRef and targetRefs, matching the fix from the
abandoned envoyproxy#8890 (invalid combinations like group: gateway.networking.k8s.io
with kind: Service previously passed admission since group and kind were
validated independently). Port envoyproxy#8890's comprehensive per-kind CEL test
matrix (valid CDS-only fields, reject-all-RDS-fields, sectionName rejection,
each across Service/ServiceImport/Backend and targetRef/targetRefs),
adapted to also require mergeType per this branch's own rule.

Rename isBackendTrafficPolicyTarget to isBackendTargetKind (also envoyproxy#8890's
name) - the old name read as checking whether a target is a
BackendTrafficPolicy, not whether its kind is a backend kind. Call
deprecatedFieldsUsedInBackendTrafficPolicy/
SetDeprecatedFieldsWarningForPolicyAncestors for backend-targeted policies
too, matching the other three scopes in this file (and envoyproxy#8890) - the helper
already exists and is already used uniformly elsewhere. Add a
non-generic MergedConditionMessage naming the actual gateway policy in the
Merged condition, replacing the static placeholder string; envoyproxy#8890's version
was generic over multiple merged-with policies (a shape this branch's
one-backend-to-one-gateway merge never has), so this only keeps the single
fallback case it actually needs.

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Oct 6, 2026
…d vs envoyproxy#8890

Three scenarios from envoyproxy#8890's fixture set were phase-1-relevant but not
exercised by any existing fixture here:

- partial-coverage: a rule with two backendRefs where only one has a
  backend-targeted policy - proves the untargeted backend's cluster is
  left untouched rather than treated as a conflict.
- multi-targetrefs-one-policy: a single BackendTrafficPolicy resource with
  plural targetRefs naming two backends, rather than one policy per
  backend - exercises processBackendTrafficPolicyForBackend being called
  twice for the same policy object, and confirms the resulting ancestor
  status is a single deduplicated entry, not doubled.
- tcp-basic: a merged cluster reached via TCPRoute rather than HTTPRoute -
  confirms the mechanism is protocol-agnostic (it only walks
  BackendClusters, never branches on route kind).

Signed-off-by: Muhammad Waqar <[email protected]>
muwaqar-cflt added a commit to muwaqar/gateway that referenced this pull request Oct 6, 2026
… is off

Backend-targeted BackendTrafficPolicy previously had no code-level check
gating it on MergeBackends at all - when the flag was off, the policy
simply had nothing to attach to and silently did nothing, with no status
signal explaining why. This matches neither the original design doc
(which already described this as an explicit gate) nor envoyproxy#8890's own
prior-art behavior, and was flagged as an upstream-maintainer requirement
during that PR's review (feature should only be reachable once cluster
deduplication exists to make it meaningful).

Add an explicit per-gateway check in processBackendTrafficPolicyForBackend:
a gateway with mergeBackends disabled now gets an Accepted:False/Disabled
resolve error (reusing the existing egv1a1.PolicyReasonDisabled reason),
rather than silently doing nothing. Other reasons a backend might not
resolve to a merged cluster (dynamic resolver, per-listener divergence,
simply not referenced by any route) remain silent no-ops, since
mergeBackends being on is the one precondition this code can verify
directly - the rest depend on route.go's own eligibility decisions.

Split the mergebackends-btp-backend-target-unmerged-no-op fixture in two:
-mergebackends-disabled (the scenario this fix changes, now showing the
explicit Disabled status) and -unreferenced-no-op (a new fixture proving
the genuine silent no-op still holds when mergeBackends is on but the
backend is simply never referenced by a route).

Also corrects two inconsistencies between the design doc and the
code: the doc's Non-goals section previously lumped "mergeBackends
disabled" into the same silent-no-op bucket as other non-resolution
reasons, contradicting its own Resolution-and-merge section; and its
Status reporting section said ancestors are "the target backend" when
the code correctly uses each matched Gateway (matching BackendTLSPolicy's
own precedent).

Signed-off-by: Muhammad Waqar <[email protected]>
zhaohuabing pushed a commit that referenced this pull request Oct 9, 2026
… or Backend directly (merged clusters only) (#9816)

* api: add backend-targeted BackendTrafficPolicy CEL validation layer

Adds CEL validation rules for backend-targeted (Service/ServiceImport/Backend)
BackendTrafficPolicy support:

- Extends targetRef/targetRefs group validation to accept multicluster.x-k8s.io
  and gateway.envoyproxy.io groups for Service, ServiceImport, and Backend kinds
- Adds validation requiring mergeType when targeting a backend
- Adds validation rejecting route-only fields (rateLimit, faultInjection,
  useClientProtocol, compression, compressor, responseOverride, httpUpgrade,
  requestBuffer, telemetry, routingType, retry, bandwidthLimit) when targeting
  a backend
- Adds validation rejecting sectionName on backend targets
- Updates mergeType doc comment to reflect support for backend targets
- Includes four new test cases covering valid/invalid backend targeting scenarios

These changes establish the CEL contract that downstream tasks depend on.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: resolve backend-targeted BackendTrafficPolicy into merged clusters

Adds processBackendTrafficPolicyForBackend, wired into
ProcessBackendTrafficPolicies, to resolve BackendTrafficPolicies
targeting a Service/ServiceImport/Backend: detects conflicting
attachments to the same backend, merges with any whole-gateway policy,
and writes the resulting traffic features into every already-merged
BackendCluster's Traffic field across all gateways. Backends that
never resolve to a merged cluster are silently skipped, per Phase 1
scope.

Adds the isBackendTrafficPolicyTarget predicate and the
backendPolicyKey/backendPolicyKeyFromTarget/backendPolicyKeyFromMetadata
helpers used for matching policy targets to BackendCluster metadata.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: add golden fixtures for backend-targeted BackendTrafficPolicy

Exercises the full translator pipeline for Service-targeted
BackendTrafficPolicy under MergeBackends: standalone, merged with a
whole-gateway policy, independent multi-backendRef weighted rules, the
silent no-op when a backendRef never merges, and conflict detection
between two policies targeting the same backend.

Signed-off-by: Muhammad Waqar <[email protected]>

* test: regenerate Helm CRD golden fixtures for backend-target CEL rules

make gen-check wasn't run after Task 1's CEL validation changes to
BackendTrafficPolicySpec, leaving these golden fixtures stale relative to
the new kubebuilder markers. Regenerated via make generate.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: fix status scoping and error handling in backend-targeted BTP

Scope the Accepted/Merged ancestor status to the gateways where the
policy's target actually matched a BackendCluster, instead of every
configured gateway - a policy whose target never resolves anywhere now
gets no ancestor status at all. Gate the Merged condition further on
whether a real gateway-level BackendTrafficPolicy existed to merge
with, since mergeType alone doesn't imply an actual merge happened.
Surface buildTrafficFeatures errors via
SetTranslationErrorForPolicyAncestors instead of silently skipping the
cluster, and trim tf.Timeout's route-scoped members before assigning
to bc.Traffic, matching the gateway-level path's precedent. Add a
release note for the backend-targeted BackendTrafficPolicy feature.

Signed-off-by: Muhammad Waqar <[email protected]>

* api,gatewayapi: tighten CEL group/kind pairing and naming, port test/status parity from #8890

Replace independent group and kind allow-lists with a combined group/kind
pairing rule for targetRef and targetRefs, matching the fix from the
abandoned #8890 (invalid combinations like group: gateway.networking.k8s.io
with kind: Service previously passed admission since group and kind were
validated independently). Port #8890's comprehensive per-kind CEL test
matrix (valid CDS-only fields, reject-all-RDS-fields, sectionName rejection,
each across Service/ServiceImport/Backend and targetRef/targetRefs),
adapted to also require mergeType per this branch's own rule.

Rename isBackendTrafficPolicyTarget to isBackendTargetKind (also #8890's
name) - the old name read as checking whether a target is a
BackendTrafficPolicy, not whether its kind is a backend kind. Call
deprecatedFieldsUsedInBackendTrafficPolicy/
SetDeprecatedFieldsWarningForPolicyAncestors for backend-targeted policies
too, matching the other three scopes in this file (and #8890) - the helper
already exists and is already used uniformly elsewhere. Add a
non-generic MergedConditionMessage naming the actual gateway policy in the
Merged condition, replacing the static placeholder string; #8890's version
was generic over multiple merged-with policies (a shape this branch's
one-backend-to-one-gateway merge never has), so this only keeps the single
fallback case it actually needs.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: simplify matchedGWs tracking in processBackendTrafficPolicyForBackend

gwPolicy is looked up once per gateway, before the inner BackendClusters
loop, and never changes within that loop - so every write to
matchedGWs[gwNN] for a given gateway assigns the same value regardless of
which matching cluster triggered it. The nil-guard branch was dead
complexity protecting against an overwrite that could never happen;
collapsing it to an unconditional assignment is behavior-preserving
(verified via a full golden-fixture regeneration producing zero diff).

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: add golden fixtures for backend-target coverage gaps found vs #8890

Three scenarios from #8890's fixture set were phase-1-relevant but not
exercised by any existing fixture here:

- partial-coverage: a rule with two backendRefs where only one has a
  backend-targeted policy - proves the untargeted backend's cluster is
  left untouched rather than treated as a conflict.
- multi-targetrefs-one-policy: a single BackendTrafficPolicy resource with
  plural targetRefs naming two backends, rather than one policy per
  backend - exercises processBackendTrafficPolicyForBackend being called
  twice for the same policy object, and confirms the resulting ancestor
  status is a single deduplicated entry, not doubled.
- tcp-basic: a merged cluster reached via TCPRoute rather than HTTPRoute -
  confirms the mechanism is protocol-agnostic (it only walks
  BackendClusters, never branches on route kind).

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: reject backend-targeted BTP explicitly when mergeBackends is off

Backend-targeted BackendTrafficPolicy previously had no code-level check
gating it on MergeBackends at all - when the flag was off, the policy
simply had nothing to attach to and silently did nothing, with no status
signal explaining why. This matches neither the original design doc
(which already described this as an explicit gate) nor #8890's own
prior-art behavior, and was flagged as an upstream-maintainer requirement
during that PR's review (feature should only be reachable once cluster
deduplication exists to make it meaningful).

Add an explicit per-gateway check in processBackendTrafficPolicyForBackend:
a gateway with mergeBackends disabled now gets an Accepted:False/Disabled
resolve error (reusing the existing egv1a1.PolicyReasonDisabled reason),
rather than silently doing nothing. Other reasons a backend might not
resolve to a merged cluster (dynamic resolver, per-listener divergence,
simply not referenced by any route) remain silent no-ops, since
mergeBackends being on is the one precondition this code can verify
directly - the rest depend on route.go's own eligibility decisions.

Split the mergebackends-btp-backend-target-unmerged-no-op fixture in two:
-mergebackends-disabled (the scenario this fix changes, now showing the
explicit Disabled status) and -unreferenced-no-op (a new fixture proving
the genuine silent no-op still holds when mergeBackends is on but the
backend is simply never referenced by a route).

Also corrects two inconsistencies between the design doc and the
code: the doc's Non-goals section previously lumped "mergeBackends
disabled" into the same silent-no-op bucket as other non-resolution
reasons, contradicting its own Resolution-and-merge section; and its
Status reporting section said ancestors are "the target backend" when
the code correctly uses each matched Gateway (matching BackendTLSPolicy's
own precedent).

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: fix stale golden fixture left behind by previous commit

mergebackends-btp-backend-target-mergebackends-disabled.out.yaml was
committed with its pre-fix content (ancestors: null) instead of the
regenerated Disabled-status content the rename was supposed to carry -
a staging mistake in the previous commit, not a code issue. Verified via
a fresh --override-testdata run that this is the only fixture affected.

Signed-off-by: Muhammad Waqar <[email protected]>

* ir: add Traffic field to DestinationSetting for inline backend-targeted BTP

Signed-off-by: Muhammad Waqar <[email protected]>

* ir: force per-setting cluster splitting when a Setting has its own Traffic

Signed-off-by: Muhammad Waqar <[email protected]>

* xds/translator: prefer a single setting's own Traffic over the route's

Signed-off-by: Muhammad Waqar <[email protected]>

* api: add PolicyReasonUnsupportedBackendTrafficPolicy

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: add overrideIfSet helper, the inverse of setIfNil

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: resolve backend-targeted BTP into inline HTTPRoute/GRPCRoute destinations

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: resolve backend-targeted BTP into single-backendRef TCP/UDP destinations

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: carry BackendConnection/DNS through TCP/UDP inline BTP resolution

TCPRoute has BackendConnection/DNS fields and UDPRoute has a DNS field
that the resolved ClusterTrafficFeatures literals omitted, so a
backend-targeted BackendTrafficPolicy setting these fields for a TCP/UDP
destination was silently dropped (applyTraffic overwrites rather than
merges).

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: don't block multi-backendRef HTTP/GRPC rules from taking a Traffic override

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: fix stale comment after HTTP/GRPC no longer blocks on multi-backendRef

The comment above the combined-Warning emission still said "HTTP/GRPC,
TCP, and UDP walks" after the previous commit removed HTTP/GRPC's own
contribution to blockedRoutes entirely - only TCP/UDP populate it now.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: add golden fixtures for inline HTTP/GRPC backend-targeted BTP

Covers the single-backendRef, multi-backendRef-different-policies,
partial-coverage, and multi-targetRefs-same-policy scenarios for the
inline (non-merged) resolution path added in this branch.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: add golden fixtures for Route-vs-Backend precedence

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: rename multi-rule-warning fixture, it doesn't produce a Warning

The Warning/UnsupportedBackendTrafficPolicy condition only ever fires for
TCP/UDP/TLS routes (the only route kinds with no per-setting cluster
splitting mechanism) - this fixture's name predates the Task 6 fix that
correctly stopped HTTP/GRPC's inline walk from blocking on multi-backendRef
rules at all, since HasSettingWithTraffic()/NeedsClusterPerSetting()
already lets HTTP/GRPC split into per-setting clusters instead. The
fixture's actual content is still valid, non-redundant coverage (multi-rule
+ intra-rule partial coverage + whole-route policy layering, combined) -
only the "warning" framing in its name and premise was stale.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: add golden fixtures for TCP/UDP inline backend-targeted BTP

Signed-off-by: Muhammad Waqar <[email protected]>

* ir: fix gofmt alignment in TestRouteDestinationHasSettingWithTraffic

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: fix UDP inline walk dropping backend-policy cluster fields

The UDP walk in processBackendTrafficPolicyForBackend only applied
LoadBalancer and DNS from a backend-targeted BackendTrafficPolicy,
silently dropping CircuitBreaker, HealthCheck, Timeout, TCPKeepalive,
BackendConnection, and HTTP2 - asymmetric with the merged-UDP path and
the HTTP/TCP inline walks. Add the missing overrideIfSet calls and the
Timeout normalization, matching HTTP/TCP.

Add a golden fixture proving the UDP circuit-breaker field now applies,
and a fixture proving a single BackendTrafficPolicy's ancestor entry for
one gateway can carry both Accepted (from a TCPRoute occurrence that
succeeds) and Warning (from a sibling occurrence blocked by a shared
Envoy cluster) simultaneously.

Also fix a stale doc comment on DestinationSetting.Traffic (predated the
removal of the HTTP/GRPC walk's len(rd.Settings) > 1 guard), broaden
processBackendTrafficPolicyForBackend's doc comment to cover the inline
walks, update the release note to cover both phases, and trim several
comments that narrated implementation history instead of stating why.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: rename HasTrafficInSettings, extract determineSettingTraffic helper

Align RouteDestination.HasSettingWithTraffic's name with the existing
HasFiltersInSettings. Extract the repeated len(settings) == 1 &&
settings[0].Traffic != nil check in asClusterArgs into a named helper next
to determineIPFamily, its closest existing analog.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: drop redundant determineSettingTraffic call-site comments

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: drop code-identifier cross-refs, dedupe tests, tidy TCP/UDP asClusterArgs

Remove comment references naming NeedsClusterPerSetting directly. Merge
TestRouteDestinationNeedsClusterPerSettingWithTraffic into the existing
NeedsClusterPerSetting table test and drop the one-off DeepCopy test, which
had no equivalent for any other IR type. Move dns/backendConnection into
the else-branch of TCP/UDP's asClusterArgs so both branches set every
cluster-scoped field explicitly, instead of one being pre-set and silently
overwritten.

Signed-off-by: Muhammad Waqar <[email protected]>

* release-notes: mention TLSRoute, drop mergeType from the requirement note

TLSRoute translates into the same ir.TCPRoute IR type as TCPRoute, so the
backend-targeted TCP walk already covers it. mergeType is a CEL-enforced
precondition regardless of feature state, not specific to this feature.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: rename blockedRoutes, drop unneeded DeepCopy in HTTP walk

blockedRoutes -> unsupportedRoutes, matching PolicyReasonUnsupportedBackendTrafficPolicy
instead of colliding conceptually with the unrelated PolicyReasonDisabled case earlier in
the same function.

route.Traffic.ClusterFeatures() aliases the route's own shared Traffic, so some copy is
needed before overriding fields on it. But nothing in this path ever mutates a nested
sub-struct in place - every write replaces a top-level pointer wholesale - so a shallow
copy is exactly as safe as the recursive DeepCopy and matches the TCP/UDP walks' own
field-copy pattern below it.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi,xds/translator: add golden coverage for merged-UDP, RDS-only route precedence, and translator-level split

gatewayapi:
- udp-basic: merged-cluster case via a UDPRoute, mirroring tcp-basic - no
  merged UDP fixture existed at all.
- multi-backendref-with-gateway: two independently-targeted merged clusters
  plus a whole-gateway policy layered over both, proving neither backend's
  fields leak into the other's cluster while the gateway's fields still land
  on both.
- merge-with-rds-only-route: a route-level policy that sets only an RDS
  field (faultInjection) with mergeType explicit, so it doesn't disqualify
  its destination from merging. Proves the backend's CDS fields land on the
  merged BackendCluster while the route's RDS field survives untouched -
  this specific combination (route policy present, but RDS-only) was
  untested; route-vs-backend CDS precedence itself is inline-only by
  construction (hasClusterSettingsBelowGateway forces inline the moment a
  route/rule sets any cluster-scoped field).

xds/translator: no fixture previously drove a DestinationSetting.Traffic
override through the actual translator to real Envoy Cluster resources -
only unit tests calling asClusterArgs directly, or IR-level gatewayapi
fixtures that stop short of xDS output.
- http-route-sole-setting-traffic: single setting carrying Traffic wins
  over the route's own, serialized correctly into the Cluster proto.
- http-route-weighted-backend-traffic-split(-three-settings): multiple
  settings, one carries Traffic - each setting gets its own Cluster
  resource, not just the targeted one paired against a shared "everyone
  else" cluster. The three-setting variant is the minimal case that
  actually distinguishes full per-setting isolation from that alternative.
- tcp/udp-route-sole-setting-traffic: same sole-setting proof for TCP/UDP,
  including UDP's backend-policy-only fields (e.g. circuitBreaker) that
  ir.UDPRoute itself has no field to carry at the route level.

Signed-off-by: Muhammad Waqar <[email protected]>

* release-notes: rename fragment to match PR #9816

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: don't report Disabled on gateways that don't reference the target backend

processBackendTrafficPolicyForBackend iterated every gateway and reported a
Disabled ancestor for any of them with mergeBackends off, regardless of
whether that gateway's IR referenced the policy's target backend at all. In
a cluster with many gateways this could displace real ancestor entries once
the 16-ancestor cap kicks in. Add gatewayReferencesBackend and only check it
inside the mergeBackends-disabled branch, so the common (enabled) path
doesn't pay for a second walk over the same IR the walks below it already
traverse.

Found by Codex review on #9816.

Signed-off-by: Muhammad Waqar <[email protected]>

* api: permit admissionControl on Service/ServiceImport/Backend targets

admissionControl is a cluster-scoped field (already classified as such by
btpSpecHasClusterScopedFields, and implemented as an upstream HTTP filter
attached to the cluster itself), and the backend-targeted resolution path
in processBackendTrafficPolicyForBackend already applies it - but the CEL
rule still only allowed Gateway/ListenerSet/HTTPRoute/GRPCRoute targets, so
a backend-targeted policy could never actually set it. Extend the rule to
match, and regenerate the CRDs and helm-template golden outputs.

Found by Codex review on #9816.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: raise patch coverage on processBackendTrafficPolicyForBackend

Codecov flagged 71.98% patch coverage on processBackendTrafficPolicyForBackend.
Add TestProcessBackendTrafficPolicyForBackendEdgeCases, a single table-driven
test calling it directly with hand-built IR to cover: a gateway missing from
xdsIR entirely, nil Destination/Route on each of the HTTP/TCP/UDP walks, a
multi-setting match with no RouteDestination Metadata (silently skipped,
no Warning - matches the existing documented behavior), and the deprecated
singular targetRef warning path.

Also close a real gap found while investigating: UDP's own multi-backendRef
Warning path had no coverage anywhere, unlike TCP's equivalent
(tcp-multi-backendref-warning, added back in Task 10) - add the missing
udp-multi-backendref-warning golden fixture.

Raises the function from 71.98% to 87.9%. The remaining gap is four
identically-shaped branches (one per walk) handling mergeBackendTrafficPolicy/
buildTrafficFeatures returning an error - not reachable by any BackendTrafficPolicy
that passes CEL validation for a backend target, mirroring the same
already-uncovered pattern in this file's pre-existing merged-cluster path.

Signed-off-by: Muhammad Waqar <[email protected]>

* api,gatewayapi: fix real CI lint failures (gci false-corruption, unparam)

CI's lint job failed for two reasons:

- gci reported api/v1alpha1/backendtrafficpolicy_types.go:42 as not
  properly formatted. This is the same '' -> U+201D corruption bug seen
  earlier working locally, except go1.26.6 in CI hits it too, not just this
  machine's toolchain - a real blocker, not a local artifact. Rewrite the
  two empty-string CEL checks (self.targetRef.group == '') as
  self.targetRef.group.size() == 0, which never produces the adjacent-quote
  sequence gofmt/gci mishandles. Verified semantically identical by running
  the full CEL validation suite against real API servers on all 4 tested
  k8s versions.
- unparam flagged newBackendTargetPolicy's name parameter, which every call
  site passed as the same literal "btp-1". Drop the parameter.

Confirmed both fixed by re-running golangci-lint locally with the same
config CI uses (0 issues, previously 2 errors).

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: fix inline backend resolution clobbering route's own override

The HTTP/TCP/UDP walks merged the backend policy with gwPolicy before
overriding onto the route's already-resolved traffic. When the backend
policy left a field unset, the merge filled it in from gwPolicy anyway,
and that gateway-inherited value then unconditionally overwrote whatever
the route had already correctly resolved for that field - discarding a
route-level override the backend policy never touched.

Use the backend policy's own fields only (buildTrafficFeatures(policy, nil))
as the override source; the gateway's contribution is already reflected in
route.Traffic by the time backend processing runs. The merged BackendCluster
walk needed no change - it has no competing route-level traffic to preserve.

Found by @zhaohuabing on #9816.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: scope backend-BTP ancestor status to referencing gateways, fix false Merged

Conflicted, and the walks' own resolve/translation errors, were reported
against every gateway passed into processBackendTrafficPolicyForBackend
instead of just the ones that actually reference the target backend.
Narrow ancestorRefs itself via a pre-pass filtered by
gatewayReferencesBackend, and defer the walks' translation-error status
to a per-gateway flag so it's still reported with the right ancestor.

Also split matchedGWs (identity, feeds Accepted) from a new mergedGWs
map (feeds Merged) populated only when walk 1 performs a literal
merge with a gateway-level policy - walks 2-4 never merge, so a policy
that only ever matched inline was incorrectly tagged Merged.

Signed-off-by: Muhammad Waqar <[email protected]>

* xds/translator: fix gen-check drift in Phase 2 RDS golden fixtures

initialFetchTimeout: 0s no longer appears in ConfigSource output after
the dependency bump picked up in this rebase, same as the unrelated
drift main itself fixed in 4de02ef (#9825). These three fixtures were
added on this branch after that fix landed on main, so they never picked
it up.

Signed-off-by: Muhammad Waqar <[email protected]>

* ir,gatewayapi: add RouteDestination.RequiresSingleCluster (unwired)

Add RequiresSingleCluster field to ir.RouteDestination to mark destinations
that require all backends to resolve to a single Envoy cluster (e.g. rules
with fallback backends, session persistence, or consistent-hash load
balancing). Deliberately not serialized (json:"-" yaml:"-"): it is a
same-process signal produced by route.go and consumed by
backendtrafficpolicy.go within a single Translate call.

Wire the field through routeDestinationForListener as a new parameter,
passing false placeholders at all 4 existing call sites for now -
subsequent commits compute and wire the real per-route-kind values.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: thread RequiresSingleCluster through HTTP/GRPC route processing

Capture the existing mergeUnsafeForRule (HTTP) / mergeIncompatible (GRPC)
value - already computed per rule, before weight-0 filtering - onto
httpRouteWithBackendDestinations.requiresSingleCluster, and pass it into
routeDestinationForListener's new parameter at the shared HTTP/GRPC call
site in processHTTPRouteParentRefListener, replacing the false placeholder.

Also fix TestTranslate/TestTranslateWithExtensionKinds: they cmp.Diff
generated IR against a YAML-unmarshalled expected struct, and since
RequiresSingleCluster is json/yaml:"-", the unmarshalled side is always
false while generated IR now correctly carries true on the
mergebackends-http-demerge-* fixtures. Ignore the field in both
comparisons rather than serialize it.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: thread RequiresSingleCluster through TLS/TCP/UDP route processing

Replace the false placeholder at the 3 remaining routeDestinationForListener
call sites with the already-computed mergeIncompatible value
(mergeIncompatibleForSingleClusterRule's result). TCP and UDP already had
this in scope at the call site; TLS's mergeIncompatible was computed inside
the per-rule loop, out of scope at the later per-listener call site, so hoist
its computation to route scope - allRuleBackendRefs is rule-invariant, so
this is a relocation, not a behavior change.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: block backend-targeted BTP on must-stay-single-cluster rules

Guard all three inline-Settings walks in processBackendTrafficPolicyForBackend
(HTTP, TCP, UDP) on rd.RequiresSingleCluster before writing a backend-targeted
policy's Traffic override onto a DestinationSetting: HTTP previously had no
guard at all, and TCP/UDP's ad hoc len(rd.Settings) > 1 checks are replaced
with the same precise field. Reuses the existing unsupportedRoutes/Warning
machinery unchanged - only what triggers it changes.

Adds 6 fixture pairs: fallback-backend, session-persistence, and
consistent-hash cases (HTTP + one GRPC) proving the block now fires and no
Traffic override leaks through; a plain weighted multi-backendRef regression
fixture proving ordinary rules still get the override; and a weight-zero-
sibling fixture proving the block stays stable across a live traffic-weight
change, since RequiresSingleCluster is captured pre-filter.

Also updates two backendtrafficpolicy_test.go subtests whose synthetic
RouteDestination literals relied on len(Settings) > 1 to reach the block
path - same intent, same assertions, updated to set RequiresSingleCluster
directly.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi,ir,xds: remove backend-targeted BTP support for demerged destinations

Scope backend-targeted BackendTrafficPolicy to merged clusters only. A
merged ir.BackendCluster is safe by construction - merge-eligibility
already excludes every hazard (fallback backend, session persistence,
route-scoped CDS divergence, consistent hash) as a precondition for
merging - so this sidesteps the whole class of gap the inline path kept
surfacing, most recently a route-scoped ConsistentHash BackendTrafficPolicy
demerging via hasClusterSettingsBelowGateway, a mechanism the
RequiresSingleCluster guard added earlier today never saw.

Removes: DestinationSetting.Traffic and RouteDestination.HasTrafficInSettings
(internal/ir/xds.go); the RequiresSingleCluster field and its threading
through routeDestinationForListener (internal/gatewayapi/route.go); the
HTTP/TCP/UDP inline walks in processBackendTrafficPolicyForBackend
(internal/gatewayapi/backendtrafficpolicy.go); the per-setting Traffic
branches in *RouteTranslator.asClusterArgs and determineSettingTraffic
(internal/xds/translator); the now-unused
PolicyReasonUnsupportedBackendTrafficPolicy status reason (api/v1alpha1);
and 5 internal/xds/translator/testdata fixture pairs that hand-authored a
per-setting Traffic override to test exactly this removed behavior at the
translator level.

mergeUnsafeForRule/mergeIncompatibleForWeightedRule/
weightedRuleBackendsMustBeInOneCluster/mergeIncompatibleForSingleClusterRule
and the Phase 1 merged-cluster mechanism (bc.Traffic, the x.BackendClusters
loop) are untouched - this removal is scoped only to backend-targeted-BTP-
applies-to-inline-settings, not to mergeBackends merge-eligibility itself.

A backend-targeted BackendTrafficPolicy targeting a backend that never
merges now silently does not apply - no Warning, matching Phase 1's
original behavior before inline support existed.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: remove test fixtures for demerged-destination backend-BTP

Delete every mergebackends-btp-backend-target-* fixture that existed
specifically to test inline/demerged backend-targeted BackendTrafficPolicy
application, precedence, or the now-removed Warning-on-unsupported path.
The remaining, merged-cluster-only fixtures regenerate byte-identical -
confirming they never depended on the removed code path.

Also narrows the 9816 release note to describe only the merged-cluster
scope that survived, dropping the inline-application and Route-vs-Backend
precedence language that no longer describes shipped behavior.

Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: update doc comment, drop orphaned overrideIfSet helper

Update processBackendTrafficPolicyForBackend's doc comment to accurately
reflect the current merged-only behavior following the removal of
inline-walk support for backend-targeted BackendTrafficPolicy.

Delete the orphaned overrideIfSet[T any] generic helper and its test
from helpers.go/helpers_test.go - it was only used by the three deleted
inline walks and now has zero production call-sites, unlike this file's
other generic helpers (setIfNil, policyOwnerOr, ownerOf,
getFirstMatchOrFirstFromData), which all remain in active use.

Signed-off-by: Muhammad Waqar <[email protected]>

* api: reject ConsistentHash load balancing for backend-targeted BackendTrafficPolicy

Envoy's hash policy for weighted-cluster selection is route-scoped and
singular - it doesn't make sense for different backends in the same
weighted route to each request a different hash input via their own
backend-targeted policy. Add a CEL rule rejecting loadBalancer.type:
ConsistentHash when targeting a Service/ServiceImport/Backend, matching
the existing pattern of rejecting rateLimit/faultInjection/etc. for
backend targets.

Also fixes a pre-existing compile break in test/cel-validation: three
unrelated table entries still referenced ClusterSettings.Retry, which
moved to BackendSettings.Retry when #8899 split ClusterSettings on main;
nobody had run `make go.test.cel` on this branch since that rebase.

Signed-off-by: Muhammad Waqar <[email protected]>

* api: document ConsistentHash rejection and merged-only scope for backend-targeted BTP

Signed-off-by: Muhammad Waqar <[email protected]>

* api: reject timeout.http.requestTimeout/streamIdleTimeout for backend-targeted BTP

Signed-off-by: Muhammad Waqar <[email protected]>

* api: stop permitting admissionControl via targetSelectors on backend targets

Narrow the admissionControl CEL rule's targetSelectors clause back to
Gateway/ListenerSet/HTTPRoute/GRPCRoute, removing Service/ServiceImport/
Backend. Those three kinds were added to this clause alongside targetRef/
targetRefs when admissionControl was extended to backend targets, but
targetSelectors is never actually resolved for backend-kind targets at
the controller level (ProcessBackendTrafficPolicies calls
resolvePolicyTargetsFromReferences, not the selector-aware
resolvePolicyTargets, for backend targeting) - so the schema silently
accepted a shape that never did anything.

Update the one existing test exercising this combination to expect
rejection instead of acceptance.

Signed-off-by: Muhammad Waqar <[email protected]>

* test(e2e): verify merged Cluster carries backend-targeted BackendTrafficPolicy settings

Signed-off-by: Muhammad Waqar <[email protected]>

* test(e2e): use 512 instead of 777 for the backend-targeted BTP's maxConnections

No functional reason for 777 specifically - 512 reads as an intentional,
deliberately-configured value rather than an arbitrary one, while still
being distinct from Envoy's own max_connections default (1024), which is
what route C's existing policy happens to coincide with.

Signed-off-by: Muhammad Waqar <[email protected]>

* test(e2e): use 2048 instead of 1024 for route C's maxConnections

1024 is Envoy's own default max_connections, so route C's policy applying
could not be distinguished from nothing being configured at all. 2048 is
unambiguous, same reasoning as picking 512 (not 777) for the
backend-targeted policy.

Signed-off-by: Muhammad Waqar <[email protected]>

* api,test: address final-review polish items

- Clarify the admissionControl rejection message to accurately describe
  that Service/ServiceImport/Backend targets are supported via
  targetRef/targetRefs but not targetSelectors, instead of listing them
  as unconditionally allowed.
- Fold the ConsistentHash rejection's rationale into its own CEL message
  instead of a separate comment, which controller-gen was otherwise
  pulling into the generated API reference doc with no lead-in.
- Harden the new e2e subtest against a convergence race: wait for
  merge-backends-service-btp to be Accepted before reading live Envoy
  cluster stats, matching the pattern BackendTrafficPolicyMustBeAccepted
  already provides and other e2e tests already use.

Signed-off-by: Muhammad Waqar <[email protected]>

* xds/translator: fold leftover post-literal assignments back into struct literals

UDP/TCPRouteTranslator.asClusterArgs split loadBalancer/dns (and TCP's other
cluster-scoped fields) out of the xdsClusterArgs literal into an else-branch
when a since-removed conditional (per-setting Traffic override for inline
backend-targeted BTP) needed to pick between two field sets. That conditional
is gone, so these were just unconditional statements sitting outside the
literal with no behavioral reason to stay there.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>

* api: allow useClientProtocol on backend-targeted BackendTrafficPolicy

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: apply useClientProtocol to merged clusters for backend-targeted BTP

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: add golden tests for backend-targeted BTP useClientProtocol

Proves end-to-end that an HTTP merged cluster picks up useClientProtocol
from a backend-targeted BackendTrafficPolicy, and a TCP merged cluster
does not, even though the policy sets it (same gating as the existing
whole-gateway BTP path). No new xds/translator fixture is needed: the
translator reads ir.BackendCluster.UseClientProtocol the same way
regardless of which policy populated it, and that mechanism is already
covered by merge-backends-gateway-traffic.yaml.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: style fixups for useClientProtocol gating and its test

Blank lines around the protocol-gated block so it doesn't blend into the
surrounding lines. Reformat the new table test's cases to one field per
line per this repo's table-test convention.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: scope backend-targeted BTP's merged cluster settings by protocol

processBackendTrafficPolicyForBackend copied the full ClusterTrafficFeatures
onto every matching merged cluster regardless of its protocol, so HTTP-only
fields (healthCheck, http2, admissionControl, ...) could leak onto a
udp_proxy/tcp_proxy cluster. Reuse applyGatewayPolicyToMergedCluster, which
already subsets correctly per protocol for the whole-gateway BTP path (added
in #10016 for the same bug class).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: aggregate backend-targeted BTP status across all of a policy's targets

A multi-targetRefs backend-targeted BackendTrafficPolicy had each target
write Accepted/Conflicted/Disabled status directly and independently to the
same policy.Status, with no coordination between targets sharing an
ancestor. SetResolveErrorForPolicyAncestors (used for Conflicted/Disabled/
Invalid) has no guard against overwriting an already-set Accepted
condition, unlike SetAcceptedForPolicyAncestor - so whichever target was
processed last for a shared ancestor won, and in the worst order a
genuinely Accepted result could be silently clobbered by an unrelated
target's Conflicted/Disabled/error outcome for the same ancestor.

Split processBackendTrafficPolicyForBackend into a pure per-target resolver
(now returns a backendTargetOutcome instead of writing status) and a new
processBackendTargetedPolicies wrapper that owns the per-policy loop over
targets, aggregates accepted/merged/failed outcomes across all of a
policy's targets, then commits one status entry per ancestor - walking
gateways in their given order for a deterministic result, and never
regressing an ancestor another target already got accepted for.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>

* xds/translator: return UDP/TCP cluster args directly, no local var needed

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: reject targetSelectors naming a backend kind, with a status message

Per #9816 (comment):
backend targeting only resolves targetRef/targetRefs
(resolvePolicyTargetsFromReferences), so a BackendTrafficPolicy using
targetSelectors with kind Service/ServiceImport/Backend was previously
accepted by the API and then silently had no effect, with no status
feedback.

Rejects it in Go instead of CEL, avoiding the CEL cost-budget problem a
dedicated rejection rule would hit (api/v1alpha1/backendtrafficpolicy_types.go
already has two rules traversing the shared TargetSelectors field, and a
third pushes the CRD over budget). Resolves the selector against live
Service/ServiceImport/Backend objects purely to find which ancestor
Gateways to report a resolve error to - the same resolvePolicyTargetsFromSelectors
function already used for Gateway/ListenerSet selector targeting elsewhere,
not a new mechanism - the match is never applied.

Real selector support is tracked as a follow-up:
#10212

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: revert backend-target status aggregation, match existing pattern

The multi-targetRefs status aggregation added in 892a4fd was not one of
zirain's three blocking comments (protocol subsetting, MergeGateways,
targetSelectors) - it was a secondary comment this session chose to fix
proactively. On reflection, it introduced bespoke behavior found nowhere
else in this file: all six other BackendTrafficPolicy target-kind sections
(RouteRule, Route, ListenerSet Listener, ListenerSet, Gateway Listener,
Gateway) write status directly per-target with no aggregation across a
policy's multiple targets, accepting the same "last processed wins"
ordering this aggregation tried to fix only for backend targeting.

Reverts processBackendTrafficPolicyForBackend to writing status directly
(keeping the unrelated protocol-subsetting fix from 557e4d7), removes
processBackendTargetedPolicies/backendTargetOutcome/backendTargetFailure,
and restores the plain per-target loop in ProcessBackendTrafficPolicies -
matching the other six sections' exact shape. rejectBackendTargetSelectors
now writes status directly too, for the same reason.

Tracked as a cross-cutting follow-up covering all seven sections, not a
backend-targeting-specific fix: #10214

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>

* gatewayapi: preallocate rejectBackendTargetSelectors' matched slice

Fixes a prealloc lint failure in CI.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Signed-off-by: Muhammad Waqar <[email protected]>

---------

Signed-off-by: Muhammad Waqar <[email protected]>
Co-authored-by: Claude Sonnet 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants