Repository navigation
fix: ServerSideApply defects in certificate-shim and issuing controller - #9268
Conversation
|
/cc @wallrj |
There was a problem hiding this comment.
Warning
Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.
Pull request overview
Fixes ServerSideApply-related edge cases in the certificate-shim and issuing controller, and hardens associated tests to prevent regressions.
Changes:
- Updated status apply integration test helper to use the production
internalcertificates.ApplyStatusimplementation and added coverage for Update-owned managedFields behavior. - Fixed issuing controller failure path to avoid mutating the shared informer cache; added a regression unit test.
- Adjusted shim SSA behavior (Create vs Apply, annotation handling) and updated tests to validate full SSA payloads.
Reviewed changes
Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| test/integration/certificates/status_scalar_apply_test.go | Switches test helper to production ApplyStatus and adds a managedFields ownership regression subtest. |
| pkg/controller/certificates/issuing/issuing_controller_test.go | Makes ApplyStatus assertions exact-bytes and adds a regression test for informer-cache mutation on failure. |
| pkg/controller/certificates/issuing/issuing_controller.go | Deep-copies lister object before mutating in failIssueCertificate to avoid cache corruption/double-count. |
| pkg/controller/certificate-shim/sync_test.go | Consolidates SSA tests and tightens expectations for create/update behavior and annotation propagation. |
| pkg/controller/certificate-shim/sync.go | Restores Create on SSA create path; fixes SSA update annotation source; clones shared annotation map per built Certificate. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| func TestIssuingController_FailIssuanceDoesNotMutateInformerCache(t *testing.T) { | ||
| nextPrivateKeySecretName := "next-private-key" | ||
| baseCert := gen.Certificate("test", | ||
| gen.SetCertificateIssuer(cmmeta.IssuerReference{Name: "ca-issuer", Kind: "Issuer", Group: "foo.io"}), | ||
| gen.SetCertificateGeneration(3), | ||
| gen.SetCertificateSecretName("output"), |
There was a problem hiding this comment.
Agreed. Please fix this in this PR. With the gate on, the status write is a patch, so this "update" reactor never fires. The write succeeds, and the assertions fail for the wrong reason or pass by luck if the informer is slow. The test only works today because ServerSideApply defaults to false (internal/controller/feature/features.go:228).
Suggested change:
- Pin the gate off with
featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, feature.ServerSideApply, false)at the top. - Add a second case with the gate on and a
"patch"reactor. That is the path the fix: ServerSideApply field loss in certificate-shim and issuing controller #8793 review body was about, because the SSA payload is what carries the inflated counter to the API server.
Evidence
With the gate on, updateOrApplyStatus (issuing_controller.go:512) calls ApplyStatus, which is a patch on the status subresource. The fake client's reactor matches the exact verb (fixture.go#L979-L985).
[Claude Fable 5.1]
| // stopping the shim from adopting a Certificate a user created by | ||
| // hand that has not reached our informer cache yet. The ownership | ||
| // guards in buildCertificates only run once the object is cached. | ||
| _, err = cmClient.CertmanagerV1().Certificates(crt.Namespace).Create(ctx, crt, metav1.CreateOptions{FieldManager: fieldManager}) |
There was a problem hiding this comment.
Reverting to Create brings back a convergence bug when the ServerSideApply gate is on. A label or annotation that the shim sets at create time, and that you later remove from the Ingress, is never removed from the Certificate. The shim then re-applies on every sync and emits Successfully updated Certificate each time. The deleted Apply-on-create branch existed to avoid this (master L148-L160).
I still want the AlreadyExists guard from r3906257948. Two ways to keep both:
- Keep
Createas here, then force-Apply the same object once. The Apply entry then owns every field from birth. One extra call, create path only. - Use a non-forced Apply on create and treat a 409 the same way as
Create's AlreadyExists today: return the error and requeue. On the retry the object is in the cache and the ownership guards run.
Why the field survives
Create with FieldManager records the shim's fields under a {manager, operation: Update} entry. The forced Apply in the update loop writes under {manager, operation: Apply}. The apiserver treats these as two different managers because BuildManagerIdentifier keeps Operation in the key (managedfields.go#L134-L158).
Apply prunes only fields that the Apply entry itself set last time (update.go#L252-L256). Force only transfers ownership of fields present in the patch with a different value (update.go#L131). A key that is absent from the patch is neither pruned nor transferred.
Concrete sequence:
- The Ingress has label
a=1. The shim creates the Certificate withCreate. - You remove the label from the Ingress.
certNeedsUpdatefires on theLabelsdiff (L627) and the shim sends a forced Apply withouta.- The Update entry still owns
metadata.labels.a, so the label stays. - Every later sync repeats steps 3 and 4.
The same applies to --extra-certificate-annotations values and the edit-in-place override annotations. Your new integration subtest pins exactly this mechanism for status scalars ("an Update-owned scalar must survive an omitting Apply").
Why the description and tests do not cover it
The description says "operation:Apply-from-birth is reclaimed by the first forced update Apply regardless". That holds only for fields the first Apply sets with a changed value. It does not hold for the removed field that triggered the update.
None of the SSA unit tests at this commit start from a Certificate carrying a shim-set field that the new payload omits.
Correction (2026-09-04): I originally wrote here that the fake client does not model managedFields. That was wrong. cmfake.NewClientset uses client-go's NewFieldManagedObjectTracker, which runs the real field manager, so a unit test can cover this.
[Claude Fable 5.1]
There was a problem hiding this comment.
Measured against a real apiserver, Option (a) does not converge though:
control Create + forced Apply omitting label a -> present=true (the bug)
option a Create + identical forced Apply, then omit -> present=true
option b non-forced Apply on create, then omit -> present=false
The identical Apply in (a) co-owns rather than transfers, so the Update entry still blocks the prune. A forced Apply reclaims only a field it sets with a changed value, never the removed one, which is the field that matters here.
So the create path is option (b), ApplyNonForced. A Certificate the shim does not own conflicts instead of being adopted, the error requeues so the buildCertificates guards run once it is cached, and the shim's own pre-gate Certificate still applies cleanly.
One correction: cmfake.NewClientset builds on testing.NewFieldManagedObjectTracker:
managedFields, pruning and non-forced conflicts. The guard is a case in TestSync_ServerSideApply rather than a new integration package; put the create path back to a forced Apply and it fails on the conflict, the event and the patch bytes.
There was a problem hiding this comment.
Agreed, and thank you for measuring it. The non-forced Apply on create is the right fix, and the conflict case in TestSync_ServerSideApply pins it. I had the fake wrong: cmfake.NewClientset uses NewFieldManagedObjectTracker, and that runs the real field manager for Apply patches, so it models managedFields, pruning and non-forced conflicts. I have corrected my comment above.
One nit in the description: it says the non-forced Apply was "the first of the two options offered". It was the second. The first, Create followed by a forced Apply, is the one your measurement rules out.
Evidence
The fake tracker builds a real managedfields.FieldManager per kind and passes opts.Force straight through (fixture.go#L893-L897, fixture.go#L916-L925).
I ran the three touched packages locally at e6f05f4 and all pass:
ok github.com/cert-manager/cert-manager/pkg/controller/certificate-shim
ok github.com/cert-manager/cert-manager/pkg/controller/certificates/issuing
ok github.com/cert-manager/cert-manager/internal/controller/certificates
[Claude Fable 5.1]
| // cannot override, so a stale informer cache would 409. | ||
| // Enumerate the metadata the shim owns instead; | ||
| // buildCertificates narrows the annotations for this path. | ||
| err = internalcertificates.Apply(ctx, cmClient, fieldManager, &cmapi.Certificate{ |
There was a problem hiding this comment.
You can replace this literal with internalcertificates.Apply(ctx, cmClient, fieldManager, crt). The crt built at L411-L431 already has exactly these fields: Name, Namespace, Labels, Annotations, OwnerReferences and Spec, with no resourceVersion. setIssuerSpecificConfig and translateAnnotations only write Annotations and Spec.
Under the gate, buildCertificates can append crt itself to updateCrts. That removes the existingCrt.DeepCopy() at L472, the per-gate annotation branch at L482-L486, this literal and both explanatory comments. The non-SSA Update branch keeps its DeepCopy, as it must.
The one difference, and an alternative
crt carries only the shim's controller ref, not existingCrt's full ownerReferences list. That is the right SSA payload. ownerReferences is listType=map with listMapKey=uid (types.go#L268-L271), so refs owned by other managers are left alone. The expected bytes in "ingress update applies the full spec" are identical either way.
If you would rather keep the projection, the better home for the resourceVersion concern is serializeApply (internal/controller/certificates/apply.go:80). It already clears ManagedFields and could clear ResourceVersion, UID, Generation and CreationTimestamp for every caller.
[Claude Fable 5.1]
| // object straight to failIssueCertificate, so a failure recorded on it would | ||
| // be counted a second time on the next sync, and would also be read by the | ||
| // trigger controller from that same cache. | ||
| func TestIssuingController_FailIssuanceDoesNotMutateInformerCache(t *testing.T) { |
There was a problem hiding this comment.
This fixture duplicates the one in TestIssuingController_ServerSideApplyFailedIssuanceAttempts (L1657-L1720, L1794-L1800) almost verbatim. A package-level failedIssuanceFixture(t) used by both tests would remove about 45 lines and stop the two scenarios drifting. They have already drifted once: this copy drops RenewBefore.
What is duplicated
baseCertwith the same options (minusRenewBefore)exampleBundleandissuingCert- the failed CertificateRequest with revision annotation
"2"and the same condition - the next-private-key Secret
- the
controllerWrapper,RegisterandlocalTemporarySignerwiring
Folding this test into the existing table works less well. That runner pins the gate on, hardcodes one expected patch and calls require.NoError on ProcessItem.
[Claude Fable 5.1]
| )), | ||
| }, | ||
| }, | ||
| "ingress update applies the full spec": { |
There was a problem hiding this comment.
You can keep exact-byte matching and make these payloads readable. Build the expected Certificate as a typed *cmapi.Certificate literal with TypeMeta set, then json.Marshal it. That produces the same bytes as the controller, because serializeApply and serializeApplyStatus are plain json.Marshal of the same type. This applies here, at L4870, and to the two literals in issuing_controller_test.go with the %[1]q splice.
Why the bytes match, and precedent
Struct field order is fixed and map keys are sorted, so two json.Marshal calls on equal values give identical bytes. NewAction compares the patch bytes with go-cmp (pkg/controller/test/actions.go:80-89), so the assertion stays exact. The typed form diffs field by field when the API type changes. In the issuing tests the metav1.Time fields can take the fixed clock directly, which removes the format splice.
Precedent: test/integration/certificates/trigger_controller_test.go:441.
[Claude Fable 5.1]
| // update append extra annotations | ||
| if len(updateCrt.GetAnnotations()) > 0 && len(annotations) > 0 { | ||
| updateCrt.SetAnnotations(mergeAnnotations(updateCrt.GetAnnotations(), annotations)) | ||
| // The two write paths need different annotation sets: Update |
There was a problem hiding this comment.
certNeedsUpdate (called at L467, defined at L618-L718) never compares annotations. An annotation-only change on the Ingress or Gateway therefore never reaches the update loop. The corrected annotation payload is only sent when a spec or label change happens at the same time. This is pre-existing, but it limits what this fix delivers.
Two options:
- Compare the shim's own annotation set in
certNeedsUpdate. Both write paths already carry it. - Soften "annotations are present on create and update" in the description to "on updates triggered by a spec or label change".
I am happy for the first option to be a follow-up if you would rather keep this PR to the #8793 review scope.
Examples and test coverage
Annotation-only changes that are missed: a new or changed --extra-certificate-annotations value, or edit-in-place toggled on the Ingress.
Every update case in the new tests relies on a spec or label diff: stale-label and revisionHistoryLimit at sync_test.go:4785, and stale.example.com at sync_test.go:4854.
[Claude Fable 5.1]
There was a problem hiding this comment.
Taking the second option, and widening the trigger is a follow-up. Because a wider trigger hands more hand-edited state to the non-SSA Update writer, which replaces spec and labels wholesale. That is the same root as the label follow-up, the shim declares its owned field set in two places that disagree, and both want fixing together.
There was a problem hiding this comment.
Agreed. The two owned-field lists want fixing together in the follow-up. The description already says the annotation-only case does not trigger an update, which is all this PR needs.
[Claude Fable 5.1]
e36ab48 to
38738bf
Compare
…end the shim's annotations With the ServerSideApply gate on, a Certificate created with Create records the shim's fields under an operation:Update managedFields entry that the update path's Apply can never prune from, so a label or annotation the shim set at create time and the user later removed survived forever; a non-forced Apply leaves the object owned by the Apply entry and still conflicts rather than adopting a Certificate the shim does not own. Separately, extractExtraAnnotations returns nil rather than an empty map, so the annotations the shim derives from the ingress-like object were dropped from the write unless an extra annotation happened to be configured. The shim tests now assert exact patch bytes built from typed values, because matchRootCertificateApply ignored its expected argument, and a new case covers the create-path conflict propagating out of sync with no success event. Signed-off-by: Yuedong Wu <[email protected]>
…iled issuance failIssueCertificate mutated the Certificate before copying it, and ProcessItem passes the lister object straight through, so the failure counters were written onto the shared informer cache and a retried status write could count one failure twice. Copy at the top of the function, as issueCertificate does. The apply-status expectations are tightened to exact patch bytes built from typed values, the two failed-issuance tests now share one fixture, and the cache test runs with the ServerSideApply gate pinned both ways because the status write is an update or a patch depending on it. Signed-off-by: Yuedong Wu <[email protected]>
…te->Apply migration Test_StatusScalarApply re-implemented the status apply, so it could not catch a change in the production serialization it exists to characterize. Add a subtest for the state Certificates are in when the ServerSideApply gate is enabled on an existing install: scalars written earlier by UpdateStatus survive an ApplyStatus that omits them, until one ApplyStatus includes them and takes ownership. Signed-off-by: Yuedong Wu <[email protected]>
38738bf to
e6f05f4
Compare
|
The three new commits address every point from the earlier review. I have nothing further on the code. CI is green after the retest, and the earlier e2e failure was the pre-existing ACME double-finalize flake, not this PR. For anyone trying to see the combined effect of #8793 and this PR, I have written a walkthrough: rendered (gist source). It covers the two issues, the Apply ownership rules, what each PR changed, how each symptom in #7438 and #8785 is resolved, and the consolidated diff. Two small points on the description, neither blocking:
Why the first failure after enabling the gate still uses the old countYour point that a stale old [Claude Fable 5.1] |
|
/lgtm Thank you for the thorough follow-up and for measuring the create-path options against a real API server. Every point from the #8793 review is addressed, the touched packages pass locally, and CI is green. The two description nits above are not blocking. [Claude Fable 5.1] |
|
[APPROVALNOTIFIER] This PR is APPROVED This pull-request has been approved by: wallrj The full list of commands accepted by this bot can be found here. The pull request process is described here DetailsNeeds approval from an approver in each of these files:
Approvers can indicate their approval by writing |
|
We will not backport this PR to release-1.21. The fix for #7438 and #8785 ships in v1.22 only. Reasons:
[Claude Fable 5.1] |
Pull Request Motivation
Resolves the post-merge review of #8793.
Each of the nine review comments is answered below:
r3906257985, apply-patch matcher asserts nothing. Both matchers replaced with exact-bytes
testpkg.NewActionbuilt from typed values; the two SSA test functions collapse into the existing table.r3906257992, integration test re-implements ApplyStatus.
applyCertificateStatusnow delegates tointernalcertificates.ApplyStatus.Review body,
failIssueCertificatemutates the informer cache.DeepCopymoved above the mutations. Worth adding:trigger_controller.goreads those fields from the same cache, so a failed status write already skewed backoff on its own.r3906257957, full-spec force ownership. Release note added, no code change.
issuerRef.groupis a further fieldcertNeedsUpdateskips.r3906257931, annotations dropped from the apply payload. Fixed with
Apply(..., crt)as suggested.crtcarries noresourceVersion, sobuildCertificatesappends it directly under the gate, dropping theObjectMetaliteral, theDeepCopyand the per-gate annotation branch. Two nearby defects: extras were merged rather thancrt.Annotations, so the non-SSA update path dropped them too, and the secondsetIssuerSpecificConfigcall was dead.r3906257948, forced Apply on create removes the AlreadyExists guard. The create path is a non-forced Apply that handles the conflict: a Certificate the shim does not own conflicts rather than being adopted, and the error requeues so the
buildCertificatesguards run once it is cached.Createis not an option, it records the shim's fields under anoperation:Updateentry the update path can never prune from, so a label removed from the Ingress would survive forever. This also satisfies inteon's request for Apply on create.ApplyhardcodedForce: true, hence theApplyNonForcedsibling.r3906257968, stale status after enabling the gate. Release-noted, no migration code. The mechanism is as described. A frozen old
lastFailureTimedoes not extend backoff,shouldBackoffReissuingOnFailurereturnsfalse, 0oncedurationSinceFailure >= delay, but the stale count survives one more failure:failIssueCertificateincrements what it read, so the first failure after the flip writes stale + 1 and backs off from that. The next success clears it. A one-time clear would need permanentmanagedFieldsintrospection inProcessItemand cannot separate stale state from state written just before a restart.r3906257979, hand-maintained apply whitelists drift. Migrating four controllers to the generated apply configurations is not cherry-pickable alongside #8793. Issue to follow, with the three known drift instances.
Review body, applyset label deleted from the cached map.
delete(labels, applysetLabel)is untouched. Issue to follow, covering both the process-wide label stripping and the data race.E2E Verification
Field ownership on the create path, measured against a real API server:
Createplus a forced Apply omitting a shim-set label leaves the label present, because the Update entry still owns itA forced Apply reclaims ownership only for a field it sets with a changed value, never for a removed field.
Without the fix, on released v1.21.1:
revisionHistoryLimitstays stuck at 7 where this branch gives 31,2,3,4,5,6,7after a single failure, against1hereWith the fix:
certNeedsUpdatecompares no annotations, so an annotation-only edit still does not trigger oneparentRefs, and the solver HTTPRoute is parented purely from the annotationsfailedIssuanceAttemptsincrements once per failure and clears on successrevisionHistoryLimitstill propagates on updateKind
/kind bug
Release Note
Note: The release note covers only what a released version exhibits. Both regressions were introduced by #8793 and never shipped, so they are deliberately absent from it.