Skip to content

Conversation

@Tharsanan1
Copy link
Contributor

@Tharsanan1 Tharsanan1 commented Jan 27, 2026

Purpose

Fixes: #817

Summary by CodeRabbit

  • New Features

    • Provider-to-template mappings are now tracked as synchronizable lazy resources for consistent propagation.
    • Routing now includes provider name metadata to support provider-aware routing decisions.
    • Lazy resources are exposed in system configuration dumps for improved observability.
  • Tests

    • Added end-to-end tests verifying lazy resource synchronization, provider-template mapping lifecycle, and route metadata propagation.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 27, 2026

Walkthrough

Adds provider-to-template lazy-resource handling across the gateway: publishes/removes provider→template mappings in the gateway controller, threads provider metadata through XDS routes, exposes lazy resources in policy-engine config dumps, and adds integration tests exercising lazy-resource xDS synchronization and provider-template mapping behavior.

Changes

Cohort / File(s) Summary
Gateway Controller - Provider Mapping Logic
gateway/gateway-controller/pkg/utils/llm_deployment.go
New constant lazyResourceTypeProviderTemplateMapping plus methods publishProviderTemplateMappingAsLazyResource and removeProviderTemplateMappingLazyResource; hooks to publish on deploy and remove on delete with nil-safety and warning logs.
Gateway Controller - Lazy Resource Manager / Snapshot / Store
gateway/gateway-controller/pkg/lazyresourcexds/lazy_resource_manager.go, gateway/gateway-controller/pkg/lazyresourcexds/lazy_resource_snapshot.go, gateway/gateway-controller/pkg/storage/lazy_resource_store.go
Make lazy-resource APIs type-aware: add/Get/Remove methods that include resourceType (*ByIDAndType variants), change internal storage to resourcesByType, and update snapshot/manager removal signatures and logs to include resource_type.
Gateway Controller - XDS Routing (provider metadata)
gateway/gateway-controller/pkg/xds/translator.go
Extracts providerName during translation and threads it into route creation; route metadata now includes provider_name alongside template handle.
Policy Engine - Config Dump & Types
gateway/policy-engine/internal/admin/dumper.go, gateway/policy-engine/internal/admin/types.go
Add LazyResources to ConfigDumpResponse and new types LazyResourcesDump and LazyResourceInfo; config dump now aggregates lazy resources by type and total count.
Policy Engine - Route Metadata & Context
gateway/policy-engine/internal/kernel/extproc.go, gateway/policy-engine/internal/kernel/execution_context.go
Add ProviderName to RouteMetadata, populate it from route metadata, and include provider_name in shared execution context metadata.
Analytics Constants
gateway/policy-engine/internal/analytics/analytics.go, gateway/system-policies/analytics/v0.1.0/analytics.go
Add lazyResourceTypeProviderTemplateMapping constant to identify new lazy resource type.
SDK / Storage API
sdk/gateway/policy/v1alpha/lazy_resource.go
Add compositeKey helper and type-aware store APIs: GetResourceByIDAndType, RemoveResourceByIDAndType, and supporting mapping helpers.
Integration Tests / BDD
gateway/it/features/lazy-resources-xds.feature, gateway/it/steps_llm.go, gateway/it/suite_test.go
Add comprehensive feature file and step implementations to validate lazy-resources xDS sync, provider/template CRUD, provider-template mapping propagation and cleanup; register new feature in test suite.

Sequence Diagram

sequenceDiagram
    actor User
    participant GWCtrl as Gateway Controller
    participant LRS as Lazy Resource Store
    participant XDS as XDS Translator
    participant PE as Policy Engine
    participant ConfigDump as Config Dump

    User->>GWCtrl: Deploy LLM Provider (providerName, templateHandle)
    GWCtrl->>LRS: publishProviderTemplateMappingAsLazyResource(providerName, templateHandle, correlationID)
    LRS-->>GWCtrl: ACK (mapping stored)

    User->>XDS: Create route for API
    XDS->>XDS: extractProviderName() / extractTemplateHandle()
    XDS->>XDS: createRoute(..., provider_name metadata)
    XDS-->>PE: Envoy route with provider_name & template_handle metadata

    PE->>ConfigDump: Dump configuration
    ConfigDump->>LRS: dumpLazyResources()
    LRS-->>ConfigDump: ResourcesByType (incl. ProviderTemplateMapping)
    ConfigDump-->>PE: ConfigDumpResponse{..., LazyResources}

    User->>GWCtrl: Delete LLM Provider (providerName)
    GWCtrl->>LRS: removeProviderTemplateMappingLazyResource(providerName, correlationID)
    LRS-->>GWCtrl: ACK (mapping removed)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I hopped through routes and lazy stores tonight,
Publishing mappings tidy and bright.
Provider and template now softly align,
Policy engine sees their matching sign.
Hooray — the gateway hums just right! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description only includes 'Fixes: #817' and is missing critical sections from the template including Goals, Approach, User Stories, Documentation, Automation Tests, and Security Checks. Complete the PR description by adding all required template sections: Goals, Approach, User Stories, Documentation, Automation Tests, and Security Checks to provide comprehensive context for the changes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Send provider-template map to policy engine' directly addresses the main objective stated in issue #817: sending provider-to-template relation data to the policy engine.
Linked Issues check ✅ Passed The PR successfully implements provider-template mapping: adds lazy resource publishing/removal during provider lifecycle in the gateway-controller, propagates provider_name metadata through xDS routes, includes policy-engine side handling for lazy resources, and adds comprehensive integration tests validating the synchronization.
Out of Scope Changes check ✅ Passed All changes align with the issue objective: provider-template mapping implementation includes refactoring lazy resource management APIs to support type-aware operations, which is a necessary internal improvement enabling the core functionality without introducing unrelated scope creep.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings

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

❤️ Share

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@gateway/gateway-controller/pkg/utils/llm_deployment.go`:
- Around line 732-742: The removal routine
removeProviderTemplateMappingLazyResource currently calls
lazyResourceManager.RemoveResource(providerName, correlationID) which only
removes by ID and risks colliding with other resource types (via
store.RemoveByID); update the call so the removal filters by ResourceType (use
the same ResourceType constant used when publishing, e.g.,
ResourceTypeProviderTemplateMapping) or add/use a RemoveResourceByType(id,
resourceType, correlationID) method so only provider-template mapping resources
are deleted, and change the empty providerName handling to mirror
publishProviderTemplateMappingAsLazyResource by returning an error for empty
providerName instead of silently returning nil.
🧹 Nitpick comments (3)
gateway/gateway-controller/pkg/xds/translator.go (2)

437-445: Consider consolidating LLM metadata extraction.
extractTemplateHandle and extractProviderName both traverse SourceConfiguration (with JSON marshal/unmarshal). A single helper that parses once and returns both values would reduce repeated work per config.


1005-1112: LGTM: provider_name propagated into route metadata.
Reminder: since gateway components changed, rebuild local images with cd gateway && make build-local.

gateway/it/features/lazy-resources-xds.feature (1)

64-66: Consider using polling with timeout instead of fixed sleep for xDS propagation.

The 3-second fixed wait may cause flakiness in slow CI environments or be unnecessarily slow in fast environments. A polling mechanism with exponential backoff and timeout would be more robust.

However, if fixed delays are the established pattern in this test suite and have proven reliable, this can be addressed in a follow-up.

@Tharsanan1 Tharsanan1 changed the title Send provider to template map to policy engine Send provider-template map to policy engine Jan 27, 2026
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@gateway/it/steps_llm.go`:
- Around line 350-367: The assertion function assertLazyResourceNotExists should
fail if the config dump is missing the lazy_resources section instead of
silently passing; after unmarshalling in assertLazyResourceNotExists check that
response.LazyResources is non-nil and that
response.LazyResources.ResourcesByType is present (e.g., len==0 or nil) and, if
missing, return a descriptive error like "config dump missing lazy_resources" so
the test surfaces shape regressions; apply the same guard to the analogous "not
exists" assertion at the other spot (the function around lines 552-572) to
ensure both functions validate presence of LazyResources before iterating.
🧹 Nitpick comments (1)
gateway/it/features/lazy-resources-xds.feature (1)

64-66: Prefer polling over fixed sleeps to reduce flakiness.
Given xDS propagation variability, consider an “eventually” step that polls config_dump until the expected condition is met (and reuse it for other waits in this feature).

Comment on lines +350 to +367
// assertLazyResourceNotExists checks that a lazy resource with the given ID does not exist
func assertLazyResourceNotExists(body []byte, templateID string) error {
var response ConfigDumpResponse
if err := json.Unmarshal(body, &response); err != nil {
return fmt.Errorf("failed to parse config dump JSON: %w", err)
}

for resourceType, resources := range response.LazyResources.ResourcesByType {
for _, resource := range resources {
if resource.ID == templateID {
return fmt.Errorf("template %q should not exist but was found in lazy resources of type %q",
templateID, resourceType)
}
}
}

return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Guard against missing lazy_resources in “not exists” assertions.
If the field is absent, these checks currently pass, which can hide regressions in config-dump shape.

✅ Suggested hardening
func assertLazyResourceNotExists(body []byte, templateID string) error {
    var response ConfigDumpResponse
    if err := json.Unmarshal(body, &response); err != nil {
        return fmt.Errorf("failed to parse config dump JSON: %w", err)
    }
+   if response.LazyResources.ResourcesByType == nil {
+       return fmt.Errorf("lazy_resources missing from config dump")
+   }

    for resourceType, resources := range response.LazyResources.ResourcesByType {
        for _, resource := range resources {
            if resource.ID == templateID {
                return fmt.Errorf("template %q should not exist but was found in lazy resources of type %q",
                    templateID, resourceType)
            }
        }
    }

    return nil
}
func assertLazyResourceNotExistsWithType(body []byte, resourceID, resourceType string) error {
    var response ConfigDumpResponse
    if err := json.Unmarshal(body, &response); err != nil {
        return fmt.Errorf("failed to parse config dump JSON: %w", err)
    }
+   if response.LazyResources.ResourcesByType == nil {
+       return fmt.Errorf("lazy_resources missing from config dump")
+   }

    resources, exists := response.LazyResources.ResourcesByType[resourceType]
    if !exists {
        // Type doesn't exist, so resource definitely doesn't exist
        return nil
    }

Also applies to: 552-572

🤖 Prompt for AI Agents
In `@gateway/it/steps_llm.go` around lines 350 - 367, The assertion function
assertLazyResourceNotExists should fail if the config dump is missing the
lazy_resources section instead of silently passing; after unmarshalling in
assertLazyResourceNotExists check that response.LazyResources is non-nil and
that response.LazyResources.ResourcesByType is present (e.g., len==0 or nil)
and, if missing, return a descriptive error like "config dump missing
lazy_resources" so the test surfaces shape regressions; apply the same guard to
the analogous "not exists" assertion at the other spot (the function around
lines 552-572) to ensure both functions validate presence of LazyResources
before iterating.

@renuka-fernando renuka-fernando merged commit 9fc3229 into wso2:main Jan 27, 2026
4 checks passed
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.

Send provider and provider template relation data to policy engine

3 participants