Skip to content

[misc] refactor component cleanup#145

Merged
slin1237 merged 1 commit into
mainfrom
slin/resource-cleanup
Jul 7, 2025
Merged

[misc] refactor component cleanup#145
slin1237 merged 1 commit into
mainfrom
slin/resource-cleanup

Conversation

@slin1237
Copy link
Copy Markdown
Collaborator

@slin1237 slin1237 commented Jul 7, 2025

What type of PR is this?

/kind cleanup
/kind bug

What this PR does / why we need it:

This PR refactors the InferenceService controller to fix a Kubernetes reconciliation anti-pattern where "deletion reconcilers" were being created
with nil specs when components (router, decoder, engine) were removed from the InferenceService spec.

Previous behavior (problematic):

  • When a component was removed from the spec, the controller created a reconciler with a nil spec to handle deletion
  • Used status-based existence checking (unreliable)
  • Manually deleted resources instead of leveraging Kubernetes garbage collection
  • Created unnecessary reconciler instances for deletion

New behavior (fixed):

  • Resources are immediately cleaned up when components are removed from the spec
  • Uses label-based selection with owner reference verification
  • Dynamically handles all resource types without hard-coding
  • Gracefully handles optional CRDs that may not be installed
  • Maintains backwards compatibility while fixing the core issue

Key improvements:

  1. Removed the anti-pattern of creating deletion reconcilers with nil specs
  2. Simplified the component interface by removing Delete() and ShouldExist() methods
  3. Added a flexible cleanup system that uses unstructured objects
  4. Added CRD availability checking to prevent failures with optional resources
  5. Comprehensive unit test coverage for the cleanup logic

Which issue(s) this PR fixes:

Special notes for your reviewer:

  1. The cleanup implementation in cleanup.go uses unstructured objects to avoid hard-coding resource types, making it maintainable as new resources
    are added
  2. The implementation checks CRD availability before attempting cleanup to handle optional resources (Ray, Knative, KEDA, etc.)
  3. All existing tests pass, and new comprehensive unit tests have been added
  4. The refactoring maintains full backwards compatibility - no changes to CRDs or user-facing APIs

Does this PR introduce a user-facing change?

Fixed InferenceService controller reconciliation to properly clean up orphaned resources when components (engine, decoder, router) are removed from
the spec. Resources are now immediately deleted when their corresponding component is removed, instead of remaining orphaned until the
InferenceService itself is deleted.

@github-actions github-actions Bot added bug Something isn't working cleanup labels Jul 7, 2025
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @slin1237, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly refactors the InferenceService controller's resource management to improve the cleanup of orphaned Kubernetes resources. By centralizing and generalizing the deletion process, I've eliminated a problematic reconciliation anti-pattern, simplified component interfaces, and enhanced the controller's overall reliability and maintainability. The changes ensure that when components are removed from an InferenceService spec, their associated resources are immediately and correctly garbage collected.

Highlights

  • Refactored Component Cleanup: I've introduced a new, centralized cleanup mechanism for InferenceService components (engine, decoder, router). This addresses a Kubernetes reconciliation anti-pattern where 'deletion reconcilers' were previously created with nil specs when components were removed from the InferenceService specification. The new approach leverages Kubernetes owner references and label-based selection for more robust and immediate resource deletion.
  • Simplified Component Interface: The Component interface has been simplified by removing the Delete() and ShouldExist() methods. The responsibility for cleaning up orphaned resources is now handled globally by the InferenceService controller, rather than individually by each component reconciler. This reduces complexity and potential for errors within component-specific logic.
  • Dynamic Resource Discovery and Deletion: The new cleanup logic in cleanup.go dynamically discovers and deletes resources using unstructured objects, avoiding hard-coding specific resource types. It also includes checks for CRD availability, gracefully handling optional resources like Ray, Knative, KEDA, and Istio, ensuring compatibility across different cluster configurations.
  • Improved Reconciliation Flow: The main InferenceService reconciliation loop in controller.go has been streamlined. The previous conditional logic for creating deletion reconcilers and calling component-specific Delete methods has been removed. Cleanup is now a distinct, early step in the reconciliation process, ensuring orphaned resources are addressed promptly.
  • Comprehensive Unit Testing: New, comprehensive unit tests have been added in cleanup_test.go to validate the correctness and robustness of the new cleanup logic, covering various scenarios including the deletion of orphaned resources and the preservation of active ones.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@slin1237 slin1237 force-pushed the slin/resource-cleanup branch from a900b88 to 1c23218 Compare July 7, 2025 21:42
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request refactors the component cleanup logic, moving away from an anti-pattern to a cleaner, more robust implementation using owner references and dynamic resource discovery. The changes are well-structured and the addition of comprehensive unit tests is excellent. I have a few suggestions to further improve the new cleanup logic, mainly around error handling and removing a piece of unused code.

Comment on lines +95 to +97
if err := r.Delete(ctx, &obj); err != nil && !apierrors.IsNotFound(err) {
return fmt.Errorf("delete %s/%s: %w", gvk.Kind, obj.GetName(), err)
}
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.

medium

The current implementation returns on the first error encountered during resource deletion. This means if deleting one orphaned resource fails, the cleanup for other orphaned resources of the same type (GVK) is aborted for the current reconciliation cycle. It would be more robust to attempt to delete all orphaned resources of the current type, logging any errors but not returning immediately.

Suggested change
if err := r.Delete(ctx, &obj); err != nil && !apierrors.IsNotFound(err) {
return fmt.Errorf("delete %s/%s: %w", gvk.Kind, obj.GetName(), err)
}
if err := r.Delete(ctx, &obj); err != nil && !apierrors.IsNotFound(err) {
log.Error(err, "Failed to delete orphaned resource", "gvk", gvk, "name", obj.GetName())
}

Comment on lines +115 to +146
// cleanupRemovedComponentsDynamic uses discovery to dynamically clean up unknown resource types.
func (r *InferenceServiceReconciler) cleanupRemovedComponentsDynamic(
ctx context.Context,
isvc *v1beta1.InferenceService,
activeComponents map[v1beta1.ComponentType]bool,
) error {
log := log.FromContext(ctx)
selector := labels.Set{constants.InferenceServicePodLabelKey: isvc.Name}.AsSelector()

apiLists, err := r.Clientset.Discovery().ServerPreferredResources()
if err != nil {
log.Info("Partial resource discovery failure", "error", err)
}

for _, list := range apiLists {
gv, err := schema.ParseGroupVersion(list.GroupVersion)
if err != nil {
continue
}

for _, res := range list.APIResources {
if !contains(res.Verbs, "list") || !contains(res.Verbs, "delete") || strings.Contains(res.Name, "/") {
continue
}
gvk := schema.GroupVersionKind{Group: gv.Group, Version: gv.Version, Kind: res.Kind}
if err := r.cleanupResourcesOfType(ctx, gvk, isvc, selector, activeComponents); err != nil {
log.V(1).Info("Failed to cleanup dynamically discovered resource", "gvk", gvk, "error", err)
}
}
}
return nil
}
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.

medium

The function cleanupRemovedComponentsDynamic appears to be unused. To improve code clarity and maintainability, it's best to remove dead code. If this is intended for future use, please add a comment explaining its purpose.

}
ok, err := utils.IsCrdAvailable(r.ClientConfig, res.gvk.GroupVersion().String(), res.gvk.Kind)
if err != nil {
log.Log.V(1).Info("Failed to check CRD", "gvk", res.gvk, "error", err)
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.

medium

It's a best practice to use an instance-specific logger (r.Log) instead of the global log.Log. This improves consistency and allows for better contextual logging.

Suggested change
log.Log.V(1).Info("Failed to check CRD", "gvk", res.gvk, "error", err)
r.Log.V(1).Info("Failed to check CRD", "gvk", res.gvk, "error", err)

@slin1237 slin1237 merged commit 56997d0 into main Jul 7, 2025
23 checks passed
@slin1237 slin1237 deleted the slin/resource-cleanup branch July 7, 2025 21:51
slin1237 added a commit that referenced this pull request Dec 22, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working cleanup

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants