kubeblocks icon indicating copy to clipboard operation
kubeblocks copied to clipboard

fix(controller): patch CR metadata without owning spec

Open weicao opened this issue 6 months ago • 5 comments

Summary

  • replace whole-object finalizer updates with merge patches that only change metadata
  • update ComponentVersion compatible ComponentDefinition labels and annotations through merge patch instead of whole-object update
  • keep chart-rendered spec fields owned by the chart manager during controller metadata reconciliation

Context

Helm server-side apply upgrades can conflict when controller metadata updates are submitted as full-object updates. The apiserver may then record the controller manager as owning spec fields that were rendered by the chart, such as ComponentVersion.spec.releases or OpsDefinition.spec.actions.

This change keeps the controller write path scoped to metadata for those reconciliation steps. HandleCRDeletion is used by multiple CR reconcilers, including ComponentVersion, OpsDefinition, OpsRequest, Addon, Restore, BackupRepo, ActionSet, BackupSchedule, BackupPolicy, and legacy parameter config rendering paths, so the fix prevents the same managedFields ownership drift across those metadata-only finalizer paths.

Validation

  • go test ./pkg/controllerutil -run TestHandleCRDeletionPatchesFinalizerMetadata -count=1 -v
  • go test ./controllers/apps -run TestComponentVersionSupportedCompDefLabelsUsesMetadataPatch -count=1 -v
  • go test -c ./controllers/apps
  • go test -c ./controllers/operations
  • go test -c ./pkg/controllerutil
  • git diff --check

Boundary

Local tests assert the generated patch payload contains metadata changes and does not contain spec. Live managedFields and Helm in-place upgrade validation should be run with a patch image against the addon upgrade scenario.

weicao avatar May 19 '26 11:05 weicao

Auto Cherry-pick Instructions

Usage:
  - /nopick: Not auto cherry-pick when PR merged.
  - /pick: release-x.x [release-x.x]: Auto cherry-pick to the specified branch when PR merged.

Example:
  - /nopick
  - /pick release-1.1

apecloud-bot avatar May 19 '26 11:05 apecloud-bot

LGTM (peer review, 不能 formal approve 因为共享 GitHub identity).

Code-level second review verified:

  • HandleCRDeletion two Update → Patch with MergeFrom(cr.DeepCopyObject()) — patch payload only contains finalizer metadata
  • updateSupportedCompDefLabels: client.Client → client.Writer (least-privilege) + MergeFrom(compVersion.DeepCopy()) patch — payload only contains labels + compatibleDefinitionsKey annotation
  • TestComponentVersionSupportedCompDefLabelsUsesMetadataPatch directly asserts !strings.Contains(patchData, "spec") + strings.Contains(patchData, "metadata") at byte level

Scope verification (high-leverage fix):

  • HandleCRDeletion is called by 10+ reconcilers (CMPV, OpsDefinition, OpsRequest, Addon, Restore, BackupRepo, ActionSet, BackupSchedule, BackupPolicy, LegacyParamConfigRenderer) — all chart-rendered CRs benefit
  • Verified OpsDefinition controller has no other spec write path; HandleCRDeletion fix is sufficient for OpsDef .spec.actions SSA conflict

Non-blocker observations (future follow-up):

  • Production code does not set explicit client.FieldOwner("kubeblocks"); relies on default UserAgent → fieldManager which matches existing manager=kubeblocks in managedFields. Adding explicit FieldOwner later would make the contract code-visible.

Test boundary: plain Go tests assert patch-data contract at byte level (envtest BeforeSuite unavailable due to missing /usr/local/kubebuilder/bin/etcd locally — same constraint for me and PR author). Live managedFields + helm in-place upgrade validation provided by sideload patch image test against the addon upgrade scenario.

mergeStateStatus=BLOCKED expected (only formal review gate); CI just queued.

weicao avatar May 19 '26 11:05 weicao

Codecov Report

:x: Patch coverage is 83.33333% with 1 line in your changes missing coverage. Please review. :white_check_mark: Project coverage is 53.08%. Comparing base (c1eb0c6) to head (b7e357f). :warning: Report is 10 commits behind head on main.

Files with missing lines Patch % Lines
pkg/controllerutil/controller_common.go 75.00% 0 Missing and 1 partial :warning:
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10264      +/-   ##
==========================================
+ Coverage   52.73%   53.08%   +0.35%     
==========================================
  Files         534      535       +1     
  Lines       61231    62110     +879     
==========================================
+ Hits        32288    32974     +686     
- Misses      25691    25825     +134     
- Partials     3252     3311      +59     
Flag Coverage Δ
unittests 53.08% <83.33%> (+0.35%) :arrow_up:

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

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

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

codecov[bot] avatar May 19 '26 12:05 codecov[bot]

Live verification cross-reference (release-1.0 backport PR #10265) — release-1.0 backport with identical production diff was patch-imaged, sideloaded to idc2, and validated against the SQL Server addon's mix-A-1 v18 in-place helm upgrade scenario.

  • helm install (chart 1.0.4-with-fix1268) → REVISION=1 deployed
  • helm upgrade in-place to chart 1.0.5 → STATUS=deployed, REVISION=2, rc=0, 5s, NO SSA conflict (previously failed with 4 .spec.releases / .spec.actions[*] Apply conflicts)
  • managedFields after-state: manager=kubeblocks no longer claims any f:spec.* for any of the 4 target objects (cmpv/mssql + 3 mssql-dynamic-* OpsDefinition); helm retains f:spec ownership as expected
  • Details + evidence pack: see https://github.com/apecloud/kubeblocks/pull/10265#issuecomment-4488130490

Since this PR (main) and #10265 (release-1.0) carry identical production diff (verified via git diff origin/release-1.0..PR-10265-head -- pkg/controllerutil/controller_common.go controllers/apps/componentversion_controller.go equivalence with this PR), the mechanism validation on release-1.0 extends to main behavior.

weicao avatar May 19 '26 13:05 weicao

/pick release-1.1 release-1.0

weicao avatar May 19 '26 14:05 weicao

The finalizer patch should keep the optimistic-locking behavior of the previous Update path. client.MergeFrom does not include metadata.resourceVersion, so a concurrent finalizer change from another controller can be overwritten by this patch, potentially dropping another finalizer or re-adding one that was already removed. Please use client.MergeFromWithOptions(base, client.MergeFromWithOptimisticLock{}) for the finalizer add/remove patches, and add a test covering a concurrent finalizer update.

leon-ape avatar May 29 '26 03:05 leon-ape

Addressed the finalizer optimistic-locking review comment in head 4eb96caf7.

Changes:

  • HandleCRDeletion finalizer add/remove patches now use client.MergeFromWithOptions(base, client.MergeFromWithOptimisticLock{}).
  • Existing metadata-only patch tests now assert the patch carries metadata.resourceVersion, so the old Update optimistic-locking behavior is preserved while still avoiding spec ownership.
  • Added a concurrent finalizer update test: when the local object has stale resourceVersion=1 and the server-side object has moved to resourceVersion=2, the mocked patch path returns a conflict instead of silently accepting a patch that could overwrite another finalizer change.

Validation:

  • make test-go-generate: PASS
  • go test ./pkg/controllerutil -run TestHandleCRDeletionPatchesFinalizerMetadata -count=1: PASS
  • go test ./controllers/apps -run TestComponentVersionSupportedCompDefLabelsUsesMetadataPatch -count=1: PASS

Boundary: go test ./pkg/controllerutil -count=1 still cannot run fully on this machine because envtest cannot find /usr/local/kubebuilder/bin/etcd; the focused non-envtest regression test above passes.

weicao avatar Jun 01 '26 02:06 weicao

The ComponentVersion metadata patch should keep the same optimistic-locking behavior as the previous whole-object Update path as well.

updateSupportedCompDefLabels now uses client.MergeFrom(compVersion.DeepCopy()). If the reconciler reads the ComponentVersion and Helm or another controller updates its metadata before this patch is submitted, this stale patch can still succeed and write labels/annotations computed from the old object state. The goal here is to avoid taking ownership of chart-rendered spec fields, not to relax concurrent update semantics.

Please use client.MergeFromWithOptions(compVersion.DeepCopy(), client.MergeFromWithOptimisticLock{}) here too, and extend TestComponentVersionSupportedCompDefLabelsUsesMetadataPatch to assert that the patch payload includes metadata.resourceVersion.

leon-ape avatar Jun 01 '26 02:06 leon-ape

Addressed the ComponentVersion optimistic-locking review comment in head b7e357fc5.

Changes:

  • updateSupportedCompDefLabels now uses client.MergeFromWithOptions(compVersion.DeepCopy(), client.MergeFromWithOptimisticLock{}).
  • TestComponentVersionSupportedCompDefLabelsUsesMetadataPatch now sets metadata.resourceVersion on the fixture and asserts the generated metadata-only patch includes that resourceVersion.
  • This keeps the old whole-object Update optimistic-locking behavior while still avoiding ownership of chart-rendered spec fields.

Validation:

  • go test ./controllers/apps -run TestComponentVersionSupportedCompDefLabelsUsesMetadataPatch -count=1: PASS
  • go test ./pkg/controllerutil -run TestHandleCRDeletionPatchesFinalizerMetadata -count=1: PASS
  • git diff --check: PASS

Boundary: full envtest suites still depend on the local /usr/local/kubebuilder/bin/etcd binary, so I kept local validation focused on the non-envtest regression tests for this patch.

weicao avatar Jun 01 '26 03:06 weicao

This branch name is not following the standards: feature/|bugfix/|release/|hotfix/|support/|releasing/|dependabot/

apecloud-bot avatar Jun 01 '26 04:06 apecloud-bot

/cherry-pick release-1.1

apecloud-bot avatar Jun 01 '26 04:06 apecloud-bot

/cherry-pick release-1.0

apecloud-bot avatar Jun 01 '26 04:06 apecloud-bot

🤖 says: cherry pick action finished successfully 🎉!
See: https://github.com/apecloud/kubeblocks/actions/runs/26735898172

apecloud-bot avatar Jun 01 '26 04:06 apecloud-bot

🤖 says: cherry pick action finished successfully 🎉!
See: https://github.com/apecloud/kubeblocks/actions/runs/26735897796

apecloud-bot avatar Jun 01 '26 04:06 apecloud-bot