Skip to content

OCPBUGS-98601: Add --force-cleanup-on-timeout flag to destroy command#9013

Open
hypershift-jira-solve-ci[bot] wants to merge 3 commits into
openshift:mainfrom
hypershift-community:fix-OCPBUGS-98601
Open

OCPBUGS-98601: Add --force-cleanup-on-timeout flag to destroy command#9013
hypershift-jira-solve-ci[bot] wants to merge 3 commits into
openshift:mainfrom
hypershift-community:fix-OCPBUGS-98601

Conversation

@hypershift-jira-solve-ci

@hypershift-jira-solve-ci hypershift-jira-solve-ci Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

What this PR does / why we need it:

When the grace period expires during hypershift destroy cluster, the CLI currently aborts with an error, leaving stale HostedClusters with unremoved finalizers. On CI management clusters this creates a vicious cycle: accumulated stale control-plane pods consume resources, causing API timeouts that prevent the deprovisioner from cleaning them up.

This PR adds a --force-cleanup-on-timeout flag that, when enabled, force-removes finalizers from the HostedCluster and its child resources (HCP, CAPI Cluster, MachineDeployments, MachineSets, Machines, NodePools) in the control plane namespace after the grace period expires, then continues with platform-specific cleanup instead of aborting.

Key behaviors:

  • The flag defaults to false to preserve existing interactive behavior
  • Preserves the CLI's destroyFinalizer on the HostedCluster during force cleanup to prevent premature garbage collection before destroyPlatformSpecifics completes
  • Includes NodePool cleanup (NodePools live in the management namespace, not the CP namespace)
  • Uses retry.RetryOnConflict with optimistic locking, matching the existing removeFinalizer pattern
  • Returns aggregated errors so the caller can detect and log partial failures
  • Only triggers force cleanup on context.DeadlineExceeded, not on user cancellation (Ctrl+C)
  • Uses table-driven pattern for CP namespace resource cleanup

Which issue(s) this PR fixes:

Fixes https://redhat.atlassian.net/browse/OCPBUGS-98601

Special notes for your reviewer:

The second commit hardens the initial implementation based on review findings: preserved destroyFinalizer logic, NodePool cleanup, retry-on-conflict, improved logging (GVK kind over Go %T), and comprehensive tests.

Checklist:

  • Subject and description added to both, commit and PR.
  • Relevant issues have been referenced.
  • This change includes docs.
  • This change includes unit tests.

Always review AI generated responses prior to use.
Generated with Claude Code via openshift-developer plugin


Note: This PR was auto-generated by the jira-agent periodic CI job in response to OCPBUGS-98601. See the full report for token usage, cost breakdown, and detailed phase output.

Summary by CodeRabbit

  • New Features

    • Added a --force-cleanup-on-timeout option for cluster deletion.
    • When enabled, if deletion times out, blocking finalizers are removed from the target cluster and associated control-plane resources to allow cleanup to proceed.
    • The command warns that forced cleanup may leave cloud resources requiring manual removal.
  • Tests

    • Added coverage for finalizer removal/preservation behavior and for timeout vs cancellation handling during deletion.

OpenShift CI Bot and others added 2 commits July 15, 2026 11:42
When the grace period expires during `hypershift destroy cluster`, the
CLI currently aborts with an error, leaving stale HostedClusters with
unremoved finalizers. On CI management clusters this creates a vicious
cycle: accumulated stale control-plane pods consume resources, causing
API timeouts that prevent the deprovisioner from cleaning them up.

Add a --force-cleanup-on-timeout flag that, when enabled, force-removes
finalizers from the HostedCluster and its child resources (HCP, CAPI
Cluster, MachineDeployments, MachineSets, Machines) in the control
plane namespace after the grace period expires, then continues with
platform-specific cleanup instead of aborting.

The flag defaults to false to preserve existing interactive behavior.

Signed-off-by: OpenShift CI Bot <ci-bot@redhat.com>
…eness

Address review findings for the --force-cleanup-on-timeout feature:

- Preserve the CLI's destroyFinalizer on the HostedCluster during force
  cleanup to prevent premature garbage collection before
  destroyPlatformSpecifics completes
- Add NodePool cleanup to forceCleanupFinalizers — NodePools live in the
  management namespace (not the CP namespace) and were previously missed
- Add retry.RetryOnConflict with optimistic locking to
  removeFinalizersFromObject, matching the existing removeFinalizer pattern
- Return aggregated errors from forceCleanupFinalizers so the caller can
  detect and log partial failures
- Only trigger force cleanup on context.DeadlineExceeded, not on user
  cancellation (Ctrl+C)
- Use table-driven pattern for CP namespace resource cleanup to reduce
  duplication
- Improve logging: prefer GVK kind over Go %T pointer types, log
  preserved finalizers
- Strengthen --force-cleanup-on-timeout flag description with orphaned
  cloud resource warning
- Add tests for: preserved destroyFinalizer, NodePool filtering by
  cluster name, preserve parameter, no-op when only preserved finalizers
  remain

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@openshift-merge-bot

Copy link
Copy Markdown
Contributor

Pipeline controller notification
This repo is configured to use the pipeline controller. Second-stage tests will be triggered either automatically or after lgtm label is added, depending on the repository configuration. The pipeline controller will automatically detect which contexts are required and will utilize /test Prow commands to trigger the second stage.

For optional jobs, comment /test ? to see a list of all defined jobs. To trigger manually all jobs from second stage use /pipeline required command.

This repository is configured in: LGTM mode

@openshift-ci-robot openshift-ci-robot added jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. jira/invalid-bug Indicates that a referenced Jira bug is invalid for the branch this PR is targeting. labels Jul 15, 2026
@openshift-ci-robot

Copy link
Copy Markdown

@hypershift-jira-solve-ci[bot]: This pull request references Jira Issue OCPBUGS-98601, which is invalid:

  • expected the bug to target the "5.0.0" version, but no target version was set

Comment /jira refresh to re-evaluate validity if changes to the Jira bug are made, or edit the title of this pull request to link to a different bug.

The bug has been updated to refer to the pull request using the external bug tracker.

Details

In response to this:

What this PR does / why we need it:

When the grace period expires during hypershift destroy cluster, the CLI currently aborts with an error, leaving stale HostedClusters with unremoved finalizers. On CI management clusters this creates a vicious cycle: accumulated stale control-plane pods consume resources, causing API timeouts that prevent the deprovisioner from cleaning them up.

This PR adds a --force-cleanup-on-timeout flag that, when enabled, force-removes finalizers from the HostedCluster and its child resources (HCP, CAPI Cluster, MachineDeployments, MachineSets, Machines, NodePools) in the control plane namespace after the grace period expires, then continues with platform-specific cleanup instead of aborting.

Key behaviors:

  • The flag defaults to false to preserve existing interactive behavior
  • Preserves the CLI's destroyFinalizer on the HostedCluster during force cleanup to prevent premature garbage collection before destroyPlatformSpecifics completes
  • Includes NodePool cleanup (NodePools live in the management namespace, not the CP namespace)
  • Uses retry.RetryOnConflict with optimistic locking, matching the existing removeFinalizer pattern
  • Returns aggregated errors so the caller can detect and log partial failures
  • Only triggers force cleanup on context.DeadlineExceeded, not on user cancellation (Ctrl+C)
  • Uses table-driven pattern for CP namespace resource cleanup

Which issue(s) this PR fixes:

Fixes https://redhat.atlassian.net/browse/OCPBUGS-98601

Special notes for your reviewer:

The second commit hardens the initial implementation based on review findings: preserved destroyFinalizer logic, NodePool cleanup, retry-on-conflict, improved logging (GVK kind over Go %T), and comprehensive tests.

Checklist:

  • Subject and description added to both, commit and PR.
  • Relevant issues have been referenced.
  • This change includes docs.
  • This change includes unit tests.

Always review AI generated responses prior to use.
Generated with Claude Code via openshift-developer plugin

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: 91714021-8fe7-41e9-82d8-dcde7a10b9c5

📥 Commits

Reviewing files that changed from the base of the PR and between 4a5fdb1 and 73e47fc.

📒 Files selected for processing (2)
  • cmd/cluster/core/destroy.go
  • cmd/cluster/core/destroy_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/cluster/core/destroy.go

📝 Walkthrough

Walkthrough

The destroy command adds --force-cleanup-on-timeout. When HostedCluster deletion exceeds its grace period, the enabled path removes finalizers from the HostedCluster and related NodePool, HostedControlPlane, and Cluster API resources while preserving the CLI destroy finalizer. Cleanup handles update conflicts, missing objects, and aggregated errors. Tests cover finalizer behavior and timeout control flow.

Sequence Diagram(s)

sequenceDiagram
  participant ClusterCLI
  participant destroyCluster
  participant KubernetesAPI
  ClusterCLI->>destroyCluster: enable force cleanup
  destroyCluster->>KubernetesAPI: wait for HostedCluster deletion
  KubernetesAPI-->>destroyCluster: deadline exceeded
  destroyCluster->>KubernetesAPI: list related resources
  destroyCluster->>KubernetesAPI: remove selected finalizers
Loading

Suggested reviewers: devguyio

🚥 Pre-merge checks | ✅ 11
✅ Passed checks (11 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: adding a new --force-cleanup-on-timeout flag to the destroy command.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Stable And Deterministic Test Names ✅ Passed All new subtest titles in destroy_test.go are static, descriptive strings; none use generated or time-varying values.
Test Structure And Quality ✅ Passed The added tests are focused unit tests with fake clients, no indefinite waits or cleanup gaps, and their structure matches existing package patterns.
Topology-Aware Scheduling Compatibility ✅ Passed Changes are limited to destroy CLI and cleanup tests; no deployment manifests, operator scheduling, affinity, or topology-aware constraints were added.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed Only standard unit tests were added; no new Ginkgo e2e tests, IPv4 assumptions, or external connectivity were found.
No-Weak-Crypto ✅ Passed Touched files only add CLI flags and finalizer cleanup; no MD5/SHA1/DES/RC4/3DES/Blowfish/ECB, custom crypto, or secret/token comparisons found.
Container-Privileges ✅ Passed PASS: The diff only touches CLI destroy logic/tests; no K8s manifests or securityContext settings like privileged, hostNetwork, hostIPC, SYS_ADMIN, or allowPrivilegeEscalation=true were added.
No-Sensitive-Data-In-Logs ✅ Passed No new logs print secrets/tokens/PII; added logs only include cluster/namespace/object names, infraID, and finalizer metadata.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@openshift-ci openshift-ci Bot added area/cli Indicates the PR includes changes for CLI and removed do-not-merge/needs-area labels Jul 15, 2026
@openshift-ci

openshift-ci Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: hypershift-jira-solve-ci[bot]
Once this PR has been reviewed and has the lgtm label, please assign muraee for approval. For more information see the Code Review Process.

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

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

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

@openshift-ci
openshift-ci Bot requested review from devguyio and jparrill July 15, 2026 12:29
@jparrill

Copy link
Copy Markdown
Contributor

/jira refresh

@openshift-ci-robot openshift-ci-robot added jira/valid-bug Indicates that a referenced Jira bug is valid for the branch this PR is targeting. and removed jira/invalid-bug Indicates that a referenced Jira bug is invalid for the branch this PR is targeting. labels Jul 15, 2026
@openshift-ci-robot

Copy link
Copy Markdown

@jparrill: This pull request references Jira Issue OCPBUGS-98601, which is valid. The bug has been moved to the POST state.

3 validation(s) were run on this bug
  • bug is open, matching expected state (open)
  • bug target version (5.0.0) matches configured target version for branch (5.0.0)
  • bug is in the state ASSIGNED, which is one of the valid states (NEW, ASSIGNED, POST)
Details

In response to this:

/jira refresh

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cmd/cluster/core/destroy_test.go`:
- Line 96: Rename each added t.Run description in the destroy tests, including
the subtests near the referenced cases, to follow the required “When ..., it
should ...” format. Preserve each test’s existing behavior and intent while
making every description begin with “When” and state the expected outcome with
“it should”.
- Line 95: Add unit tests around DestroyCluster covering the timeout branch,
including flag-disabled behavior, deadline versus cancellation handling,
continuation after platform cleanup, and propagation of cleanup errors. Extend
the existing TestForceCleanupFinalizers test area or related DestroyCluster
tests, using focused cases that verify each outcome.

In `@cmd/cluster/core/destroy.go`:
- Around line 156-160: Update the timeout branch in the destroy flow around
forceCleanupFinalizers so a non-nil cleanupErr is retained instead of only
logged. Continue platform cleanup, then return the retained error before the
success logging/return path, while preserving normal success behavior when
forced cleanup succeeds.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Enterprise

Run ID: 8cd33f27-93c8-4960-82ed-e14050b76b98

📥 Commits

Reviewing files that changed from the base of the PR and between 7eb0da0 and 4a5fdb1.

📒 Files selected for processing (3)
  • cmd/cluster/cluster.go
  • cmd/cluster/core/destroy.go
  • cmd/cluster/core/destroy_test.go

Comment thread cmd/cluster/core/destroy_test.go
Comment thread cmd/cluster/core/destroy_test.go Outdated
Comment thread cmd/cluster/core/destroy.go
@codecov

codecov Bot commented Jul 15, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 62.10526% with 36 lines in your changes missing coverage. Please review.
✅ Project coverage is 44.13%. Comparing base (7eb0da0) to head (4a5fdb1).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
cmd/cluster/core/destroy.go 62.76% 27 Missing and 8 partials ⚠️
cmd/cluster/cluster.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #9013      +/-   ##
==========================================
+ Coverage   44.11%   44.13%   +0.01%     
==========================================
  Files         772      772              
  Lines       96226    96319      +93     
==========================================
+ Hits        42448    42507      +59     
- Misses      50832    50858      +26     
- Partials     2946     2954       +8     
Files with missing lines Coverage Δ
cmd/cluster/cluster.go 0.00% <0.00%> (ø)
cmd/cluster/core/destroy.go 31.32% <62.76%> (+19.22%) ⬆️
Flag Coverage Δ
cmd-support 38.31% <62.10%> (+0.07%) ⬆️
cpo-hostedcontrolplane 46.16% <ø> (ø)
cpo-other 45.13% <ø> (ø)
hypershift-operator 54.09% <ø> (ø)
other 32.12% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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

Dropped some comments. Thanks!

}
} else {
return 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.

question: If force cleanup partially fails (say, the HC's own finalizer wasn't removed because the API server was flaky), destroyPlatformSpecifics still runs and then removeFinalizer tries to remove destroyFinalizer. The HC could end up with stale non-destroy finalizers and no controller to process them. Should partial failure at least be reflected in the exit code?

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.

Done. forceCleanupErr is now retained and returned after platform-specific cleanup completes, so partial failure is reflected in the exit code.


AI-assisted response via Claude Code

g.Expect(err).To(HaveOccurred())
})
}

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.

nit: Test names should follow the project's Gherkin convention ("When... it should...") and the TestRemoveFinalizersFromObject subtests share identical structure — good candidate for a table-driven test. Examples:

  • "should remove finalizers from child resources...""When child resources have finalizers, it should remove them and preserve destroyFinalizer on HostedCluster"
  • "should be a no-op when object has no finalizers""When object has no finalizers, it should be a no-op"

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.

Done. Renamed all 8 test descriptions to use the "When... it should..." convention.


AI-assisted response via Claude Code

g.Expect(c.Get(ctx, client.ObjectKeyFromObject(obj), &updated)).To(Succeed())
g.Expect(updated.Finalizers).To(ConsistOf(destroyFinalizer))
})
}

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.

suggestion: The integration point in DestroyCluster (the ForceCleanupOnTimeout && errors.Is(err, context.DeadlineExceeded) branch) has no test coverage. Three scenarios worth adding:

  1. ForceCleanupOnTimeout=true + DeadlineExceeded → force cleanup runs
  2. ForceCleanupOnTimeout=true + context.Canceled (Ctrl+C) → error returned, no force cleanup
  3. ForceCleanupOnTimeout=false + DeadlineExceeded → error returned, no force cleanup

The existing TestDestroyCluster uses FAKE_CLIENT env var which could be extended for this.

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.

Done. Added TestDestroyClusterForceCleanup covering all 3 requested scenarios. Extracted an internal destroyCluster function accepting client.Client to enable testing with a pre-populated fake client.


AI-assisted response via Claude Code

@jparrill

Copy link
Copy Markdown
Contributor

/test address-review-comments

@hypershift-jira-solve-ci

Copy link
Copy Markdown
Contributor Author

Review agent triggered. View job

Address review feedback:

- Propagate forceCleanupFinalizers errors to the caller instead of
  silently logging success. The error is retained and returned after
  platform-specific cleanup completes.
- Extract destroyCluster internal function accepting a client.Client
  parameter to enable integration testing without FAKE_CLIENT.
- Rename all test descriptions to "When... it should..." Gherkin
  convention.
- Add TestDestroyClusterForceCleanup with three scenarios:
  ForceCleanupOnTimeout+DeadlineExceeded, context.Canceled bypass,
  and flag-disabled behavior.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@openshift-ci-robot

Copy link
Copy Markdown

@hypershift-jira-solve-ci[bot]: This pull request references Jira Issue OCPBUGS-98601, which is valid.

3 validation(s) were run on this bug
  • bug is open, matching expected state (open)
  • bug target version (5.0.0) matches configured target version for branch (5.0.0)
  • bug is in the state POST, which is one of the valid states (NEW, ASSIGNED, POST)
Details

In response to this:

What this PR does / why we need it:

When the grace period expires during hypershift destroy cluster, the CLI currently aborts with an error, leaving stale HostedClusters with unremoved finalizers. On CI management clusters this creates a vicious cycle: accumulated stale control-plane pods consume resources, causing API timeouts that prevent the deprovisioner from cleaning them up.

This PR adds a --force-cleanup-on-timeout flag that, when enabled, force-removes finalizers from the HostedCluster and its child resources (HCP, CAPI Cluster, MachineDeployments, MachineSets, Machines, NodePools) in the control plane namespace after the grace period expires, then continues with platform-specific cleanup instead of aborting.

Key behaviors:

  • The flag defaults to false to preserve existing interactive behavior
  • Preserves the CLI's destroyFinalizer on the HostedCluster during force cleanup to prevent premature garbage collection before destroyPlatformSpecifics completes
  • Includes NodePool cleanup (NodePools live in the management namespace, not the CP namespace)
  • Uses retry.RetryOnConflict with optimistic locking, matching the existing removeFinalizer pattern
  • Returns aggregated errors so the caller can detect and log partial failures
  • Only triggers force cleanup on context.DeadlineExceeded, not on user cancellation (Ctrl+C)
  • Uses table-driven pattern for CP namespace resource cleanup

Which issue(s) this PR fixes:

Fixes https://redhat.atlassian.net/browse/OCPBUGS-98601

Special notes for your reviewer:

The second commit hardens the initial implementation based on review findings: preserved destroyFinalizer logic, NodePool cleanup, retry-on-conflict, improved logging (GVK kind over Go %T), and comprehensive tests.

Checklist:

  • Subject and description added to both, commit and PR.
  • Relevant issues have been referenced.
  • This change includes docs.
  • This change includes unit tests.

Always review AI generated responses prior to use.
Generated with Claude Code via openshift-developer plugin


Note: This PR was auto-generated by the jira-agent periodic CI job in response to OCPBUGS-98601. See the full report for token usage, cost breakdown, and detailed phase output.

Summary by CodeRabbit

  • New Features

  • Added a --force-cleanup-on-timeout option for cluster deletion.

  • When enabled, if deletion times out, blocking finalizers are removed from the target cluster and associated control-plane resources to allow cleanup to proceed.

  • The command warns that forced cleanup may leave cloud resources requiring manual removal.

  • Tests

  • Added coverage for finalizer removal/preservation behavior and for timeout vs cancellation handling during deletion.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@openshift-ci

openshift-ci Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

@hypershift-jira-solve-ci[bot]: all tests passed!

Full PR test history. Your PR dashboard.

Details

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/cli Indicates the PR includes changes for CLI jira/valid-bug Indicates that a referenced Jira bug is valid for the branch this PR is targeting. jira/valid-reference Indicates that this PR references a valid Jira ticket of any type.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants