From 44de08af665107f24167bd0186d2de7e4f6f1e31 Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Tue, 17 Nov 2026 23:31:55 -0500 Subject: [PATCH 01/11] feat(health): classify a live object's health from its conditions Add a leaf package that maps a live object to a health tier: paused (the crossplane.io/paused annotation, overriding conditions), failing (Synced=False), notReady (Ready=False) or healthy, carrying the Synced and Ready conditions it was classified from. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/health/health.go | 104 ++++++++++++++++++++++ internal/health/health_test.go | 154 +++++++++++++++++++++++++++++++++ 2 files changed, 258 insertions(+) create mode 100644 internal/health/health.go create mode 100644 internal/health/health_test.go diff --git a/internal/health/health.go b/internal/health/health.go new file mode 100644 index 00000000..8ada72c4 --- /dev/null +++ b/internal/health/health.go @@ -0,0 +1,104 @@ +/* +Copyright 2026 The Crossplane Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Package health classifies the health of a live cluster object from its +// Synced and Ready conditions and its paused annotation. It is a leaf package +// so that both the diff engine and the simulate result model can use it. +package health + +import ( + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + xpmeta "github.com/crossplane/crossplane-runtime/v2/pkg/meta" + xpv2 "github.com/crossplane/crossplane/apis/v2/core/v2" + + "github.com/crossplane/cli/v2/pkg/resource" +) + +// State is the health tier of a live object. +type State string + +// The health tiers, in the order Of checks them. +const ( + // Paused means the object carries the crossplane.io/paused: "true" + // annotation, so its conditions are stale. It overrides the conditions. + Paused State = "paused" + // Failing means the object's Synced condition is False. + Failing State = "failing" + // NotReady means the object's Ready condition is False, and it is not + // failing. + NotReady State = "notReady" + // Healthy is anything else, including an object with no Synced or Ready + // condition, or with either Unknown. + Healthy State = "healthy" +) + +// Condition is one condition of a live object, as the cluster reports it. +type Condition struct { + Status corev1.ConditionStatus `json:"status"` + Reason string `json:"reason,omitempty"` + Message string `json:"message,omitempty"` +} + +// Health is the health of one live object: its tier, and the Synced and Ready +// conditions it was classified from, each absent when the object has none. +type Health struct { + State State `json:"state"` + Synced *Condition `json:"synced,omitempty"` + Ready *Condition `json:"ready,omitempty"` +} + +// Of classifies the live object u. It returns nil when there is no live +// object: a resource the plan creates has no health. +func Of(u *unstructured.Unstructured) *Health { + if u == nil { + return nil + } + + r := &resource.Resource{Unstructured: *u} + h := &Health{ + State: Healthy, + Synced: condition(r.GetCondition(xpv2.TypeSynced)), + Ready: condition(r.GetCondition(xpv2.TypeReady)), + } + + switch { + case xpmeta.IsPaused(u): + h.State = Paused + case h.Synced != nil && h.Synced.Status == corev1.ConditionFalse: + h.State = Failing + case h.Ready != nil && h.Ready.Status == corev1.ConditionFalse: + h.State = NotReady + } + + return h +} + +// Unhealthy reports whether h is a live object in any tier but healthy. No +// live object (nil) is not unhealthy. +func (h *Health) Unhealthy() bool { + return h != nil && h.State != Healthy +} + +// condition returns c, or nil when the object has no such condition. +func condition(c xpv2.Condition) *Condition { + if c.Type == "" { + return nil + } + + return &Condition{Status: c.Status, Reason: string(c.Reason), Message: c.Message} +} diff --git a/internal/health/health_test.go b/internal/health/health_test.go new file mode 100644 index 00000000..f4db7064 --- /dev/null +++ b/internal/health/health_test.go @@ -0,0 +1,154 @@ +/* +Copyright 2026 The Crossplane Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package health + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" +) + +func TestOf(t *testing.T) { + cond := func(typ, status, reason, msg string) any { + return map[string]any{"type": typ, "status": status, "reason": reason, "message": msg, "lastTransitionTime": "2026-01-01T00:00:00Z"} + } + obj := func(paused string, conds ...any) *unstructured.Unstructured { + u := &unstructured.Unstructured{Object: map[string]any{"apiVersion": "example.org/v1", "kind": "Bucket", "metadata": map[string]any{"name": "b"}}} + if paused != "" { + u.SetAnnotations(map[string]string{"crossplane.io/paused": paused}) + } + if conds != nil { + u.Object["status"] = map[string]any{"conditions": conds} + } + return u + } + syncedFalse := cond("Synced", "False", "ReconcileError", "cannot update: denied") + syncedTrue := cond("Synced", "True", "ReconcileSuccess", "") + readyFalse := cond("Ready", "False", "Creating", "") + readyTrue := cond("Ready", "True", "Available", "") + + cases := map[string]struct { + reason string + in *unstructured.Unstructured + want *Health + }{ + "NilObject": { + reason: "No live object has no health.", + want: nil, + }, + "NoConditions": { + reason: "An object with no Synced or Ready condition, such as a ConfigMap, is healthy.", + in: obj(""), + want: &Health{State: Healthy}, + }, + "SyncedAndReady": { + reason: "Synced=True and Ready=True is healthy, carrying both conditions.", + in: obj("", syncedTrue, readyTrue), + want: &Health{ + State: Healthy, + Synced: &Condition{Status: corev1.ConditionTrue, Reason: "ReconcileSuccess"}, + Ready: &Condition{Status: corev1.ConditionTrue, Reason: "Available"}, + }, + }, + "Unknown": { + reason: "Unknown conditions are healthy.", + in: obj("", cond("Synced", "Unknown", "", ""), cond("Ready", "Unknown", "", "")), + want: &Health{ + State: Healthy, + Synced: &Condition{Status: corev1.ConditionUnknown}, + Ready: &Condition{Status: corev1.ConditionUnknown}, + }, + }, + "SyncedFalse": { + reason: "Synced=False is failing, even when Ready=False too.", + in: obj("", syncedFalse, readyFalse), + want: &Health{ + State: Failing, + Synced: &Condition{Status: corev1.ConditionFalse, Reason: "ReconcileError", Message: "cannot update: denied"}, + Ready: &Condition{Status: corev1.ConditionFalse, Reason: "Creating"}, + }, + }, + "ReadyFalse": { + reason: "Ready=False with Synced not False is not ready.", + in: obj("", syncedTrue, readyFalse), + want: &Health{ + State: NotReady, + Synced: &Condition{Status: corev1.ConditionTrue, Reason: "ReconcileSuccess"}, + Ready: &Condition{Status: corev1.ConditionFalse, Reason: "Creating"}, + }, + }, + "ReadyFalseOnly": { + reason: "Ready=False with no Synced condition is not ready.", + in: obj("", readyFalse), + want: &Health{State: NotReady, Ready: &Condition{Status: corev1.ConditionFalse, Reason: "Creating"}}, + }, + "PausedOverridesFailing": { + reason: "The paused annotation overrides Synced=False; the stale conditions are still reported.", + in: obj("true", syncedFalse), + want: &Health{ + State: Paused, + Synced: &Condition{Status: corev1.ConditionFalse, Reason: "ReconcileError", Message: "cannot update: denied"}, + }, + }, + "PausedNotTrue": { + reason: "Only the value \"true\" pauses an object.", + in: obj("false", syncedFalse), + want: &Health{ + State: Failing, + Synced: &Condition{Status: corev1.ConditionFalse, Reason: "ReconcileError", Message: "cannot update: denied"}, + }, + }, + "MalformedStatus": { + reason: "A status whose conditions cannot be read is treated as having none.", + in: &unstructured.Unstructured{Object: map[string]any{"status": map[string]any{"conditions": "nope"}}}, + want: &Health{State: Healthy}, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + got := Of(tc.in) + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("%s\nOf(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} + +func TestUnhealthy(t *testing.T) { + cases := map[string]struct { + reason string + in *Health + want bool + }{ + "Nil": {reason: "No live object is not unhealthy.", in: nil, want: false}, + "Healthy": {reason: "Healthy is not unhealthy.", in: &Health{State: Healthy}, want: false}, + "Failing": {reason: "Failing is unhealthy.", in: &Health{State: Failing}, want: true}, + "NotReady": {reason: "Not ready is unhealthy.", in: &Health{State: NotReady}, want: true}, + "Paused": {reason: "Paused is unhealthy.", in: &Health{State: Paused}, want: true}, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + if got := tc.in.Unhealthy(); got != tc.want { + t.Errorf("%s\nUnhealthy(): want %t, got %t", tc.reason, tc.want, got) + } + }) + } +} From 09ffe089c603833161ab518b6cfa7cfe510eaa3c Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Wed, 18 Nov 2026 00:29:26 -0500 Subject: [PATCH 02/11] feat(diff): carry live health on XR diff groups and impacts Record the health of each XR's live object and of the composed resources the diff engine already fetched to render it, on XRDiffGroup and XRImpact. No new cluster reads: the XR comes from the resolved composite's cluster copy, and composed resources from the observed resources render consumes, before --eventual-state synthesizes any Ready condition. A nested XR's observed resources merge into its parent's once, keyed by identity. DiffSingleResource now returns the RenderedResources it built, so the composition path gets health along with the unchanged renderings. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/diff/diffprocessor/comp_processor.go | 17 ++- .../diff/diffprocessor/comp_processor_test.go | 138 ++++++++++++++---- internal/diff/diffprocessor/diff_processor.go | 24 ++- .../diff/diffprocessor/diff_processor_test.go | 33 ++++- internal/diff/result/comp.go | 3 + internal/diff/result/types.go | 23 +++ internal/diff/testutils/mocks.go | 6 +- internal/diff/types/types.go | 48 ++++++ internal/diff/types/types_test.go | 110 ++++++++++++++ internal/health/health.go | 1 + 10 files changed, 353 insertions(+), 50 deletions(-) create mode 100644 internal/diff/types/types_test.go diff --git a/internal/diff/diffprocessor/comp_processor.go b/internal/diff/diffprocessor/comp_processor.go index 55cc47e2..b14e1efa 100644 --- a/internal/diff/diffprocessor/comp_processor.go +++ b/internal/diff/diffprocessor/comp_processor.go @@ -53,8 +53,9 @@ type XRDiffResult struct { // Error contains any error that occurred while processing this XR. // nil means processing was successful. Error error - // unchanged holds the unchanged renderings Diffs leaves out, for the overlap check only. - unchanged map[string]*dt.ResourceDiff + // rendered is what the render produced: the unchanged renderings Diffs leaves out, for the overlap + // check, and the live objects the impact's health is read from. + rendered dtypes.RenderedResources } // HasChanges returns true if this XR has downstream resource changes. @@ -600,7 +601,7 @@ func (p *DefaultCompDiffProcessor) processSingleComposition(ctx context.Context, for _, xr := range keptXRs { if r := xrResults[dt.MakeDiffKeyFromResource(xr)]; r != nil && !r.HasError() { group := dt.XRDiffGroup{XR: objectRef(xr), Diffs: r.Diffs} - composites = append(composites, renderedComposite{xr: xr, group: withUnchanged([]dt.XRDiffGroup{group}, []map[string]*dt.ResourceDiff{r.unchanged})[0]}) + composites = append(composites, renderedComposite{xr: xr, group: withUnchanged([]dt.XRDiffGroup{group}, []map[string]*dt.ResourceDiff{r.rendered.Unchanged()})[0]}) } } @@ -815,7 +816,7 @@ func (p *DefaultCompDiffProcessor) collectXRDiffs(ctx context.Context, xrs []*un } xrCtx, cancel := p.config.xrContext(ctx) - diffs, unchanged, err := p.xrProc.DiffSingleResource(xrCtx, xr, compositionProvider) + diffs, rendered, err := p.xrProc.DiffSingleResource(xrCtx, xr, compositionProvider) err = p.config.afterXR(ctx, xrCtx, diffs, err) cancel() if err != nil { @@ -829,8 +830,8 @@ func (p *DefaultCompDiffProcessor) collectXRDiffs(ctx context.Context, xrs []*un } else { // Store successful result with diffs results[resourceID] = &XRDiffResult{ - Diffs: diffs, - unchanged: unchanged, + Diffs: diffs, + rendered: rendered, } } } @@ -1642,6 +1643,7 @@ func (p *DefaultCompDiffProcessor) buildImpactAnalysis(xrs []*un.Unstructured, r case result != nil && result.HasChanges(): impact.Status = dt.XRStatusChanged impact.Diffs = result.Diffs + impact.Health = result.rendered.Health() summary.WithChanges++ default: impact.Status = dt.XRStatusUnchanged @@ -1650,6 +1652,9 @@ func (p *DefaultCompDiffProcessor) buildImpactAnalysis(xrs []*un.Unstructured, r if result != nil && p.config.KeepEqualDiffs != nil { impact.Diffs = result.Diffs } + if result != nil { + impact.Health = result.rendered.Health() + } summary.Unchanged++ } diff --git a/internal/diff/diffprocessor/comp_processor_test.go b/internal/diff/diffprocessor/comp_processor_test.go index abb07075..24814f92 100644 --- a/internal/diff/diffprocessor/comp_processor_test.go +++ b/internal/diff/diffprocessor/comp_processor_test.go @@ -46,6 +46,7 @@ import ( dt "github.com/crossplane/cli/v2/internal/diff/result" tu "github.com/crossplane/cli/v2/internal/diff/testutils" "github.com/crossplane/cli/v2/internal/diff/types" + "github.com/crossplane/cli/v2/internal/health" "github.com/crossplane/cli/v2/pkg/render" ) @@ -1296,12 +1297,12 @@ func TestDefaultCompDiffProcessor_collectXRDiffs_RevisionName(t *testing.T) { processor := &DefaultCompDiffProcessor{ xrProc: &tu.MockDiffProcessor{ - DiffSingleResourceFn: func(ctx context.Context, _ *un.Unstructured, provider types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) { + DiffSingleResourceFn: func(ctx context.Context, _ *un.Unstructured, provider types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { var err error got, err = provider(ctx, rendered) - return map[string]*dt.ResourceDiff{}, nil, err + return map[string]*dt.ResourceDiff{}, types.RenderedResources{}, err }, }, config: ProcessorConfig{Logger: tu.TestLogger(t, false), IncludeManual: true}, @@ -1341,12 +1342,12 @@ func TestDefaultCompDiffProcessor_collectXRDiffs_PerXR(t *testing.T) { var hooked []string processor := &DefaultCompDiffProcessor{ xrProc: &tu.MockDiffProcessor{ - DiffSingleResourceFn: func(ctx context.Context, xr *un.Unstructured, _ types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) { + DiffSingleResourceFn: func(ctx context.Context, xr *un.Unstructured, _ types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { if xr.GetName() == "slow" { <-ctx.Done() - return nil, nil, ctx.Err() + return nil, types.RenderedResources{}, ctx.Err() } - return map[string]*dt.ResourceDiff{xr.GetName(): diff}, nil, nil + return map[string]*dt.ResourceDiff{xr.GetName(): diff}, types.RenderedResources{}, nil }, }, config: ProcessorConfig{ @@ -1637,11 +1638,11 @@ func TestDefaultCompDiffProcessor_collectXRDiffs_NestedXRCompositionLookup(t *te compositionRequests := make([]string, 0) mockXRProc := &tu.MockDiffProcessor{ - DiffSingleResourceFn: func(ctx context.Context, res *un.Unstructured, compositionProvider types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) { + DiffSingleResourceFn: func(ctx context.Context, res *un.Unstructured, compositionProvider types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { // For the root XR, test what composition is returned comp, err := compositionProvider(ctx, res) if err != nil { - return nil, nil, err + return nil, types.RenderedResources{}, err } compositionRequests = append(compositionRequests, fmt.Sprintf("%s/%s->%s", res.GetKind(), res.GetName(), comp.Composition.GetName())) @@ -1650,12 +1651,12 @@ func TestDefaultCompDiffProcessor_collectXRDiffs_NestedXRCompositionLookup(t *te // This is what ProcessNestedXRs does when it encounters nested XRs nestedComp, err := compositionProvider(ctx, nestedXR) if err != nil { - return nil, nil, err + return nil, types.RenderedResources{}, err } compositionRequests = append(compositionRequests, fmt.Sprintf("%s/%s->%s", nestedXR.GetKind(), nestedXR.GetName(), nestedComp.Composition.GetName())) - return make(map[string]*dt.ResourceDiff), nil, nil + return make(map[string]*dt.ResourceDiff), types.RenderedResources{}, nil }, } @@ -1855,10 +1856,10 @@ func TestDefaultCompDiffProcessor_collectXRDiffs_NestedXRRunComposition(t *testi }). Build(), xrProc: &tu.MockDiffProcessor{ - DiffSingleResourceFn: func(ctx context.Context, _ *un.Unstructured, provider types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) { + DiffSingleResourceFn: func(ctx context.Context, _ *un.Unstructured, provider types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { got, gotErr = provider(ctx, tc.args.nested) - return map[string]*dt.ResourceDiff{}, nil, gotErr + return map[string]*dt.ResourceDiff{}, types.RenderedResources{}, gotErr }, }, config: ProcessorConfig{Logger: tu.TestLogger(t, false)}, @@ -1928,12 +1929,12 @@ func TestDefaultCompDiffProcessor_DiffComposition_ReportErrorOutput(t *testing.T // Create mock XR processor that fails for one XR mockXRProc := &tu.MockDiffProcessor{ - DiffSingleResourceFn: func(_ context.Context, res *un.Unstructured, _ types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) { + DiffSingleResourceFn: func(_ context.Context, res *un.Unstructured, _ types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { if res.GetName() == "fail-xr" { - return nil, nil, fmt.Errorf("render pipeline failed: function timeout") + return nil, types.RenderedResources{}, fmt.Errorf("render pipeline failed: function timeout") } - return make(map[string]*dt.ResourceDiff), nil, nil + return make(map[string]*dt.ResourceDiff), types.RenderedResources{}, nil }, } @@ -2005,8 +2006,8 @@ func TestDefaultCompDiffProcessor_DiffComposition_LateWarningsReachStructuredOut advisories := NewAdvisoryCollector(&stderr) mockXRProc := &tu.MockDiffProcessor{ - DiffSingleResourceFn: func(context.Context, *un.Unstructured, types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) { - return map[string]*dt.ResourceDiff{}, nil, nil + DiffSingleResourceFn: func(context.Context, *un.Unstructured, types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { + return map[string]*dt.ResourceDiff{}, types.RenderedResources{}, nil }, // Stands in for the leftover-container advisory raised from the function provider's teardown, // which reaches comp through DefaultCompDiffProcessor.Cleanup -> xrProc.Cleanup. @@ -2062,8 +2063,8 @@ func newCompProcessorForTest(t *testing.T, compClient xp.CompositionClient, incl config.SetDefaultFactories() mockXR := &tu.MockDiffProcessor{ - DiffSingleResourceFn: func(context.Context, *un.Unstructured, types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) { - return map[string]*dt.ResourceDiff{}, nil, nil + DiffSingleResourceFn: func(context.Context, *un.Unstructured, types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { + return map[string]*dt.ResourceDiff{}, types.RenderedResources{}, nil }, } @@ -2657,15 +2658,15 @@ func TestDefaultCompDiffProcessor_processSingleComposition_PinnedXRWithChangedFu proc.xrProc = &tu.MockDiffProcessor{ ResolveCompositeFn: resolveComposite, // Like the real one, the provider is handed the effective composite. - DiffSingleResourceFn: func(ctx context.Context, xr *un.Unstructured, provider types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) { + DiffSingleResourceFn: func(ctx context.Context, xr *un.Unstructured, provider types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { composite, err := resolveComposite(ctx, xr) if err != nil { - return nil, nil, err + return nil, types.RenderedResources{}, err } resolved, err := provider(ctx, composite) if err != nil { - return nil, nil, err + return nil, types.RenderedResources{}, err } gotRevision = resolved.RevisionName @@ -2673,7 +2674,7 @@ func TestDefaultCompDiffProcessor_processSingleComposition_PinnedXRWithChangedFu gotPipeline = append(gotPipeline, step.FunctionRef.Name) } - return map[string]*dt.ResourceDiff{}, nil, nil + return map[string]*dt.ResourceDiff{}, types.RenderedResources{}, nil }, } @@ -2765,15 +2766,15 @@ func TestDefaultCompDiffProcessor_processSingleComposition_PinnedBackingXROfFilt return synced, nil }, - DiffSingleResourceFn: func(ctx context.Context, xr *un.Unstructured, provider types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) { + DiffSingleResourceFn: func(ctx context.Context, xr *un.Unstructured, provider types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { resolved, err := provider(ctx, xr) if err != nil { - return nil, nil, err + return nil, types.RenderedResources{}, err } rendered[xr.GetName()] = resolved.RevisionName - return map[string]*dt.ResourceDiff{}, nil, nil + return map[string]*dt.ResourceDiff{}, types.RenderedResources{}, nil }, } @@ -2964,18 +2965,15 @@ func TestDefaultCompDiffProcessor_DiffComposition_RenderOverlaps(t *testing.T) { var rendered []string proc := NewCompDiffProcessor(&tu.MockDiffProcessor{ - DiffSingleResourceFn: func(_ context.Context, res *un.Unstructured, _ types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) { + DiffSingleResourceFn: func(_ context.Context, res *un.Unstructured, _ types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { rendered = append(rendered, res.GetName()) out := map[string]*dt.ResourceDiff{} for _, d := range append([]*dt.ResourceDiff{self(res)}, tc.renders[res.GetName()]...) { out[d.GetDiffKey()] = d } - var unchanged map[string]*dt.ResourceDiff + var unchanged types.RenderedResources for _, d := range tc.unchanged[res.GetName()] { - if unchanged == nil { - unchanged = map[string]*dt.ResourceDiff{} - } - unchanged[d.GetDiffKey()] = d + unchanged.AddUnchanged(d.GetDiffKey(), d) } return out, unchanged, nil }, @@ -3016,3 +3014,81 @@ func TestDefaultCompDiffProcessor_DiffComposition_RenderOverlaps(t *testing.T) { }) } } + +func TestDefaultCompDiffProcessor_DiffComposition_Health(t *testing.T) { + xr := func(name string) *un.Unstructured { + return tu.NewResource("example.org/v1", "XResource", name).WithNamespace("default").Build() + } + bucket := tu.NewResource("example.org/v1", "Bucket", "bucket").WithCondition("Synced", "False", "ApplyFailed").Build() + failing := &health.Health{State: health.Failing, Synced: &health.Condition{Status: corev1.ConditionFalse, Reason: "ApplyFailed"}} + live := dt.CompositeHealth{ + XR: &health.Health{State: health.Healthy}, + Composed: []dt.ResourceHealth{{ObjectReference: corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "Bucket", Name: "bucket"}, Health: failing}}, + } + + type want struct { + status dt.XRStatus + health dt.CompositeHealth + } + cases := map[string]struct { + reason string + // changed makes the render produce a change; errs makes it fail. + changed, errs bool + want want + }{ + "Changed": { + reason: "A changed composite carries the health its render read.", + changed: true, + want: want{status: dt.XRStatusChanged, health: live}, + }, + "Unchanged": { + reason: "An unchanged composite carries its health too: being unchanged does not make it healthy.", + want: want{status: dt.XRStatusUnchanged, health: live}, + }, + "Errored": { + reason: "A composite whose render failed carries no health.", + errs: true, + want: want{status: dt.XRStatusError}, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + comp := tu.NewComposition("test-composition").WithCompositeTypeRef("example.org/v1", "XResource").WithPipelineMode().Build() + + proc := NewCompDiffProcessor(&tu.MockDiffProcessor{ + DiffSingleResourceFn: func(_ context.Context, res *un.Unstructured, _ types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { + if tc.errs { + return nil, types.RenderedResources{}, errors.New("render failed") + } + var rendered types.RenderedResources + rendered.SetLive(res) + rendered.AddObserved(bucket) + diffs := map[string]*dt.ResourceDiff{} + if tc.changed { + d := &dt.ResourceDiff{Gvk: bucket.GroupVersionKind(), ResourceName: "bucket", DiffType: dt.DiffTypeModified, Current: dt.ResourceViews{Raw: bucket}, Desired: dt.ResourceViews{Raw: bucket}} + diffs[d.GetDiffKey()] = d + } + return diffs, rendered, nil + }, + }, tu.NewMockCompositionClient(). + WithSuccessfulCompositionFetch(comp). + WithResourcesForComposition("test-composition", "default", []*un.Unstructured{xr("a")}). + Build(), WithLogger(tu.TestLogger(t, false))) + + // The input differs from the cluster's composition (the label), so impact analysis runs. + out, _ := proc.DiffComposition(t.Context(), []*un.Unstructured{ + tu.NewComposition("test-composition").WithCompositeTypeRef("example.org/v1", "XResource").WithPipelineMode(). + WithLabels(map[string]string{"version": "2"}).BuildAsUnstructured(), + }, "default", nil) + if out == nil || len(out.Compositions) != 1 || len(out.Compositions[0].ImpactAnalysis) != 1 { + t.Fatalf("%s\nDiffComposition(...): want one composition with one impact, got %+v", tc.reason, out) + } + + impact := out.Compositions[0].ImpactAnalysis[0] + if diff := gcmp.Diff(tc.want, want{status: impact.Status, health: impact.Health}, gcmp.AllowUnexported(want{})); diff != "" { + t.Errorf("%s\nImpactAnalysis[0]: -want, +got:\n%s", tc.reason, diff) + } + }) + } +} diff --git a/internal/diff/diffprocessor/diff_processor.go b/internal/diff/diffprocessor/diff_processor.go index f52482bc..4237b05d 100644 --- a/internal/diff/diffprocessor/diff_processor.go +++ b/internal/diff/diffprocessor/diff_processor.go @@ -51,10 +51,11 @@ type DiffProcessor interface { // error, so the successful inputs' results and the failures' errors can still be rendered. PerformDiff(ctx context.Context, resources []*un.Unstructured, compositionProvider types.CompositionProvider) (*dt.XRReport, error) - // DiffSingleResource processes a single resource and returns its diffs and, by diff key, the - // unchanged renderings its diffs leave out (see DefaultDiffCalculator.CalculateNonRemovalDiffs), - // which only the render-overlap check consumes. - DiffSingleResource(ctx context.Context, res *un.Unstructured, compositionProvider types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) + // DiffSingleResource processes a single resource and returns its diffs and what its render + // produced: the unchanged renderings its diffs leave out (see + // DefaultDiffCalculator.CalculateNonRemovalDiffs), which only the render-overlap check consumes, + // and the live objects health is read from. + DiffSingleResource(ctx context.Context, res *un.Unstructured, compositionProvider types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) // ResolveComposite returns the composite DiffSingleResource hands its composition provider for res: // the defaulted effective composite (see CompositeResolver), which for a claim is its backing XR. @@ -281,6 +282,7 @@ func (p *DefaultDiffProcessor) PerformDiff(ctx context.Context, resources []*un. // We don't emit partial results for a single XR: on success the // whole diff tree is attached, on failure none of it. group.Diffs = diffs + group.Health = rendered.Health() unchanged[i] = rendered.Unchanged() } } @@ -296,6 +298,7 @@ func (p *DefaultDiffProcessor) PerformDiff(ctx context.Context, resources []*un. } groups[i].Diffs = nil + groups[i].Health = dt.CompositeHealth{} res := toRender[i].Resource resourceID := fmt.Sprintf("%s/%s", groups[i].XR.Kind, groups[i].XR.Name) @@ -364,9 +367,8 @@ func (p *DefaultDiffProcessor) PerformDiff(ctx context.Context, resources []*un. // DiffSingleResource handles one resource at a time and returns its diffs. // The compositionProvider function is called to obtain the composition to use for rendering. // This is the public method for top-level XR diffing, which enables removal detection. -func (p *DefaultDiffProcessor) DiffSingleResource(ctx context.Context, res *un.Unstructured, compositionProvider types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) { - diffs, rendered, err := p.diffSingleResourceInternal(ctx, res, compositionProvider, nil, nil, true, 0) - return diffs, rendered.Unchanged(), err +func (p *DefaultDiffProcessor) DiffSingleResource(ctx context.Context, res *un.Unstructured, compositionProvider types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { + return p.diffSingleResourceInternal(ctx, res, compositionProvider, nil, nil, true, 0) } // ResolveComposite returns the defaulted effective composite of res; see DiffProcessor. @@ -526,6 +528,14 @@ func (p *DefaultDiffProcessor) diffSingleResourceInternal(ctx context.Context, r return nil, types.RenderedResources{}, errors.Wrap(err, "cannot calculate diffs for composed resources") } + // Record the live objects already fetched, for health. The observed resources are the cluster's, + // never the copies --eventual-state synthesizes Ready on (see RenderToStableState). + rendered.SetLive(composite.Cluster) + + for i := range observedResources { + rendered.AddObserved(&observedResources[i].Unstructured) + } + // Check for nested XRs in the composed resources and process them recursively p.config.Logger.Debug("Checking for nested XRs", "resource", resourceID, "composedCount", len(desired.ComposedResources)) diff --git a/internal/diff/diffprocessor/diff_processor_test.go b/internal/diff/diffprocessor/diff_processor_test.go index f046f18e..de257e3a 100644 --- a/internal/diff/diffprocessor/diff_processor_test.go +++ b/internal/diff/diffprocessor/diff_processor_test.go @@ -36,6 +36,7 @@ import ( dt "github.com/crossplane/cli/v2/internal/diff/result" tu "github.com/crossplane/cli/v2/internal/diff/testutils" "github.com/crossplane/cli/v2/internal/diff/types" + "github.com/crossplane/cli/v2/internal/health" "github.com/crossplane/cli/v2/pkg/render" "github.com/crossplane/cli/v2/pkg/resource" ) @@ -3111,8 +3112,10 @@ func TestDefaultDiffProcessor_ProcessNestedXRs(t *testing.T) { func TestDefaultDiffProcessor_DiffSingleResource_WithObservedResources(t *testing.T) { ctx := t.Context() - // Create test XR - xr := tu.NewResource("example.org/v1", "XR", "test-xr").Build() + // Create test XR. Its conditions, and the bucket's, are what the reported health is read from. + xr := tu.NewResource("example.org/v1", "XR", "test-xr"). + WithCondition("Synced", "False", "ReconcileError"). + Build() // Create test observed composed resources observedBucket := tu.NewResource("s3.aws.crossplane.io/v1", "Bucket", "observed-bucket"). @@ -3120,6 +3123,7 @@ func TestDefaultDiffProcessor_DiffSingleResource_WithObservedResources(t *testin "crossplane.io/composition-resource-name": "bucket", }). WithSpecField("bucketName", "my-bucket"). + WithCondition("Ready", "False", "Creating"). Build() observedUser := tu.NewResource("iam.aws.crossplane.io/v1", "User", "observed-user"). @@ -3152,6 +3156,7 @@ func TestDefaultDiffProcessor_DiffSingleResource_WithObservedResources(t *testin wantErr bool wantErrContain string verifyObservedPassed bool + wantHealth dt.CompositeHealth }{ "ObservedResourcesFetchedAndPassedToRender": { setupMocks: func() (k8.Clients, xp.Clients) { @@ -3250,6 +3255,21 @@ func TestDefaultDiffProcessor_DiffSingleResource_WithObservedResources(t *testin wantObservedCount: 2, verifyObservedPassed: true, wantErr: false, + // Health is read from the cluster XR and the observed resources the render already + // fetched, unchanged ones included. + wantHealth: dt.CompositeHealth{ + XR: &health.Health{State: health.Failing, Synced: &health.Condition{Status: corev1.ConditionFalse, Reason: "ReconcileError"}}, + Composed: []dt.ResourceHealth{ + { + ObjectReference: corev1.ObjectReference{APIVersion: "iam.aws.crossplane.io/v1", Kind: "User", Name: "observed-user"}, + Health: &health.Health{State: health.Healthy}, + }, + { + ObjectReference: corev1.ObjectReference{APIVersion: "s3.aws.crossplane.io/v1", Kind: "Bucket", Name: "observed-bucket"}, + Health: &health.Health{State: health.NotReady, Ready: &health.Condition{Status: corev1.ConditionFalse, Reason: "Creating"}}, + }, + }, + }, }, "EmptyObservedResourcesWhenTreeEmpty": { setupMocks: func() (k8.Clients, xp.Clients) { @@ -3324,6 +3344,9 @@ func TestDefaultDiffProcessor_DiffSingleResource_WithObservedResources(t *testin wantObservedCount: 0, verifyObservedPassed: true, wantErr: false, + wantHealth: dt.CompositeHealth{ + XR: &health.Health{State: health.Failing, Synced: &health.Condition{Status: corev1.ConditionFalse, Reason: "ReconcileError"}}, + }, }, "FailedObservedResourceFetchIsFatal": { setupMocks: func() (k8.Clients, xp.Clients) { @@ -3535,7 +3558,7 @@ func TestDefaultDiffProcessor_DiffSingleResource_WithObservedResources(t *testin return xpClients.Composition.FindMatchingComposition(ctx, res) } - diffs, _, err := processor.(*DefaultDiffProcessor).DiffSingleResource(ctx, xr, compositionProvider) + diffs, rendered, err := processor.(*DefaultDiffProcessor).DiffSingleResource(ctx, xr, compositionProvider) // Check error expectations if (err != nil) != tt.wantErr { @@ -3573,6 +3596,10 @@ func TestDefaultDiffProcessor_DiffSingleResource_WithObservedResources(t *testin if diffs == nil { t.Errorf("DiffSingleResource() returned nil diffs, expected non-nil map") } + + if diff := gcmp.Diff(tt.wantHealth, rendered.Health()); diff != "" { + t.Errorf("DiffSingleResource() health: -want, +got:\n%s", diff) + } }) } } diff --git a/internal/diff/result/comp.go b/internal/diff/result/comp.go index c6a1a6d4..bc89b03c 100644 --- a/internal/diff/result/comp.go +++ b/internal/diff/result/comp.go @@ -249,4 +249,7 @@ type XRImpact struct { // OutputError the command lists in its top-level errors. Error *OutputError Diffs map[string]*ResourceDiff // downstream diffs (nil if unchanged/error) + // Health is the live health of the composite and of what it composed, set for a changed or + // unchanged composite and zero for an errored or filtered one. + Health CompositeHealth } diff --git a/internal/diff/result/types.go b/internal/diff/result/types.go index f00022ea..62c86849 100644 --- a/internal/diff/result/types.go +++ b/internal/diff/result/types.go @@ -14,6 +14,8 @@ import ( corev1 "k8s.io/api/core/v1" un "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" + + "github.com/crossplane/cli/v2/internal/health" ) // XRDiffGroup pairs one input XR/claim with the diffs its render produced (or @@ -45,6 +47,27 @@ type XRDiffGroup struct { NameGenerated bool Diffs map[string]*ResourceDiff Err *OutputError + // Health is the live health of the XR and of what it composed, set alongside Diffs. + Health CompositeHealth +} + +// CompositeHealth is the live health of one input composite and of every resource the cluster +// observes it composing, nested composites and their resources included, taken from the objects the +// render already fetched. It describes the cluster, not the desired state: a resource the render +// would create has no entry, and one it would delete has one. +type CompositeHealth struct { + // XR is the health of the input's own cluster object (for a claim, the claim); nil when the + // cluster has none. + XR *health.Health + // Composed holds the health of each observed composed resource, once each, in diff key order. + Composed []ResourceHealth +} + +// ResourceHealth is the live health of one composed resource. +type ResourceHealth struct { + corev1.ObjectReference + + Health *health.Health } // XRReport is what one xr diff run produced: everything a DiffRenderer renders. diff --git a/internal/diff/testutils/mocks.go b/internal/diff/testutils/mocks.go index 6bcd364b..81127099 100644 --- a/internal/diff/testutils/mocks.go +++ b/internal/diff/testutils/mocks.go @@ -258,7 +258,7 @@ type MockDiffProcessor struct { // Function fields for mocking behavior InitializeFn func(ctx context.Context) error PerformDiffFn func(ctx context.Context, resources []*un.Unstructured, compositionProvider types.CompositionProvider) (*dt.XRReport, error) - DiffSingleResourceFn func(ctx context.Context, res *un.Unstructured, compositionProvider types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) + DiffSingleResourceFn func(ctx context.Context, res *un.Unstructured, compositionProvider types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) ResolveCompositeFn func(ctx context.Context, res *un.Unstructured) (*un.Unstructured, error) CleanupFn func(ctx context.Context) error } @@ -292,12 +292,12 @@ func (m *MockDiffProcessor) PerformDiff(ctx context.Context, resources []*un.Uns } // DiffSingleResource implements the DiffProcessor.DiffSingleResource method. -func (m *MockDiffProcessor) DiffSingleResource(ctx context.Context, res *un.Unstructured, compositionProvider types.CompositionProvider) (map[string]*dt.ResourceDiff, map[string]*dt.ResourceDiff, error) { +func (m *MockDiffProcessor) DiffSingleResource(ctx context.Context, res *un.Unstructured, compositionProvider types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { if m.DiffSingleResourceFn != nil { return m.DiffSingleResourceFn(ctx, res, compositionProvider) } - return make(map[string]*dt.ResourceDiff), nil, nil + return make(map[string]*dt.ResourceDiff), types.RenderedResources{}, nil } // Cleanup implements the DiffProcessor.Cleanup method. diff --git a/internal/diff/types/types.go b/internal/diff/types/types.go index b3daf84a..2644d745 100644 --- a/internal/diff/types/types.go +++ b/internal/diff/types/types.go @@ -19,6 +19,8 @@ package types import ( "context" + "maps" + "slices" corev1 "k8s.io/api/core/v1" un "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -27,6 +29,7 @@ import ( apiextensionsv1 "github.com/crossplane/crossplane/apis/v2/apiextensions/v1" dt "github.com/crossplane/cli/v2/internal/diff/result" + "github.com/crossplane/cli/v2/internal/health" ) // Verb is a Kubernetes API verb, as it appears in a SelfSubjectAccessReview's @@ -142,10 +145,51 @@ type CredentialFetchResult struct { // // It also holds, by diff key, the diff of each unchanged rendering the calculator did not keep among // the diffs it returns, so input validation sees every rendering whether or not equal diffs are kept. +// +// Finally it holds the live cluster objects the render already fetched, for health reporting: the +// composite's own cluster copy, and by diff key every composed resource observed beneath it. type RenderedResources struct { keys map[string]bool desired map[string]map[string]bool // composite identity -> composition resource names it desired unchanged map[string]*dt.ResourceDiff + live *un.Unstructured + observed map[string]*un.Unstructured +} + +// SetLive records the composite's own cluster copy (for a claim, the claim). Merge does not carry it: +// a nested composite's cluster copy is one of its parent's observed resources. +func (r *RenderedResources) SetLive(composite *un.Unstructured) { + r.live = composite +} + +// AddObserved records a composed resource's cluster copy. A resource observed twice, as a nested +// composite is (once beneath its parent, once as the composite it is), is recorded once. +func (r *RenderedResources) AddObserved(res *un.Unstructured) { + if r.observed == nil { + r.observed = make(map[string]*un.Unstructured) + } + + r.observed[dt.MakeDiffKeyFromResource(res)] = res +} + +// Health classifies the live objects SetLive and AddObserved recorded. +func (r *RenderedResources) Health() dt.CompositeHealth { + h := dt.CompositeHealth{XR: health.Of(r.live)} + + for _, key := range slices.Sorted(maps.Keys(r.observed)) { + res := r.observed[key] + h.Composed = append(h.Composed, dt.ResourceHealth{ + ObjectReference: corev1.ObjectReference{ + APIVersion: res.GetAPIVersion(), + Kind: res.GetKind(), + Name: res.GetName(), + Namespace: res.GetNamespace(), + }, + Health: health.Of(res), + }) + } + + return h } // AddUnchanged records the diff of an unchanged rendering that is not among the returned diffs. @@ -201,6 +245,10 @@ func (r *RenderedResources) Merge(other RenderedResources) { for key, d := range other.unchanged { r.AddUnchanged(key, d) } + + for _, res := range other.observed { + r.AddObserved(res) + } } // Keys returns the diff keys of every rendered composed resource. The caller must not modify it. diff --git a/internal/diff/types/types_test.go b/internal/diff/types/types_test.go new file mode 100644 index 00000000..851e22a2 --- /dev/null +++ b/internal/diff/types/types_test.go @@ -0,0 +1,110 @@ +/* +Copyright 2026 The Crossplane Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package types + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + corev1 "k8s.io/api/core/v1" + un "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + dt "github.com/crossplane/cli/v2/internal/diff/result" + "github.com/crossplane/cli/v2/internal/health" +) + +func TestRenderedResourcesHealth(t *testing.T) { + obj := func(apiVersion, kind, name, readyStatus string) *un.Unstructured { + u := &un.Unstructured{Object: map[string]any{}} + u.SetAPIVersion(apiVersion) + u.SetKind(kind) + u.SetName(name) + if readyStatus != "" { + _ = un.SetNestedSlice(u.Object, []any{map[string]any{"type": "Ready", "status": readyStatus}}, "status", "conditions") + } + return u + } + ref := func(apiVersion, kind, name string) corev1.ObjectReference { + return corev1.ObjectReference{APIVersion: apiVersion, Kind: kind, Name: name} + } + healthy := &health.Health{State: health.Healthy} + notReady := &health.Health{State: health.NotReady, Ready: &health.Condition{Status: corev1.ConditionFalse}} + + parent := obj("example.org/v1", "XParent", "parent", "") + child := obj("example.org/v1", "XChild", "child", "False") + grandchild := obj("v1", "ConfigMap", "grandchild", "") + + type args struct { + build func() RenderedResources + } + cases := map[string]struct { + reason string + args args + want dt.CompositeHealth + }{ + "Empty": { + reason: "Nothing recorded means no live composite and nothing composed.", + args: args{build: func() RenderedResources { return RenderedResources{} }}, + want: dt.CompositeHealth{}, + }, + "LiveAndObserved": { + reason: "The live composite gives XR, and each observed resource an entry, in diff key order.", + args: args{build: func() RenderedResources { + var r RenderedResources + r.SetLive(parent) + r.AddObserved(grandchild) + r.AddObserved(child) + return r + }}, + want: dt.CompositeHealth{ + XR: healthy, + Composed: []dt.ResourceHealth{ + {ObjectReference: ref("example.org/v1", "XChild", "child"), Health: notReady}, + {ObjectReference: ref("v1", "ConfigMap", "grandchild"), Health: healthy}, + }, + }, + }, + "NestedMergedOnce": { + reason: "Merging a nested composite's render adds what it observed, but not its own live copy as XR; one observed by both levels counts once.", + args: args{build: func() RenderedResources { + var r, nested RenderedResources + r.SetLive(parent) + r.AddObserved(child) + nested.SetLive(child) + nested.AddObserved(grandchild) + nested.AddObserved(child) + r.Merge(nested) + return r + }}, + want: dt.CompositeHealth{ + XR: healthy, + Composed: []dt.ResourceHealth{ + {ObjectReference: ref("example.org/v1", "XChild", "child"), Health: notReady}, + {ObjectReference: ref("v1", "ConfigMap", "grandchild"), Health: healthy}, + }, + }, + }, + } + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + r := tc.args.build() + if diff := cmp.Diff(tc.want, r.Health()); diff != "" { + t.Errorf("\n%s\nHealth(): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} diff --git a/internal/health/health.go b/internal/health/health.go index 8ada72c4..161d5d4b 100644 --- a/internal/health/health.go +++ b/internal/health/health.go @@ -24,6 +24,7 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" xpmeta "github.com/crossplane/crossplane-runtime/v2/pkg/meta" + xpv2 "github.com/crossplane/crossplane/apis/v2/core/v2" "github.com/crossplane/cli/v2/pkg/resource" From cef0b345755d3b9bdac5e1dd10fb38059cad4d6e Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Wed, 18 Nov 2026 00:29:27 -0500 Subject: [PATCH 03/11] feat(simulate): report live health in the structured result Each plan with a live object carries its health; each composite carries the health of its live XR and lists the not-healthy composed resources that have no plan of their own. The summary counts unhealthy composites and failing, notReady and paused resources, each once. Bump the result format version to 0.2 and document the new fields. Text and diff output are unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/plan/output.go | 2 +- internal/plan/types.go | 7 ++ internal/simulate/help/output.md | 12 ++- internal/simulate/report.go | 45 +++++++++- internal/simulate/report_test.go | 143 +++++++++++++++++++++++++++++++ internal/simulate/result.go | 97 ++++++++++++++++++++- internal/simulate/result_test.go | 77 +++++++++++++++++ 7 files changed, 374 insertions(+), 9 deletions(-) diff --git a/internal/plan/output.go b/internal/plan/output.go index f17f67b5..b037465a 100644 --- a/internal/plan/output.go +++ b/internal/plan/output.go @@ -87,7 +87,7 @@ func Summarize(plans []*ResourcePlan) Summary { // ResultFormatVersion versions the serialized result schema so automation // consuming it can detect incompatible changes. The schema is alpha; the // version moves to 1.0 when it stabilizes. -const ResultFormatVersion = "0.1" +const ResultFormatVersion = "0.2" // Result is the serialized form of a simulate run, for -o json|yaml. Errored // is the primary gate for wrapping automation: when true, at least one diff --git a/internal/plan/types.go b/internal/plan/types.go index f3e79fc8..e26b91fa 100644 --- a/internal/plan/types.go +++ b/internal/plan/types.go @@ -27,6 +27,8 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" xpfieldpath "github.com/crossplane/crossplane-runtime/v2/pkg/fieldpath" + + "github.com/crossplane/cli/v2/internal/health" ) // Action is what applying a resource would do. @@ -126,6 +128,11 @@ type ResourcePlan struct { // paths the provider marks sensitive, are redacted (see RedactSecret). Before *unstructured.Unstructured `json:"before,omitempty"` After *unstructured.Unstructured `json:"after,omitempty"` + + // Health is the live object's health, read from its Synced and Ready + // conditions and paused annotation before apply; nil when there is no + // live object, as for a create. + Health *health.Health `json:"health,omitempty"` } // ResourceRef identifies a resource. diff --git a/internal/simulate/help/output.md b/internal/simulate/help/output.md index e6612f69..d48ad27c 100644 --- a/internal/simulate/help/output.md +++ b/internal/simulate/help/output.md @@ -15,7 +15,17 @@ The `-o` flag picks the output format: in the changes. Each composite has a `status`: `changed`, `unchanged`, `error`, `deferred`, `skipped`, or `unknown` when the engine reports a status this version - doesn't recognize. + doesn't recognize. That status is the simulated outcome. Separately, + `health` reports the live object's state before apply: `health.state` is + `failing` (its Synced condition is False), `notReady` (its Ready condition + is False), `paused` (it carries the `crossplane.io/paused: "true"` + annotation, whatever its conditions), or `healthy`, with the `synced` and + `ready` conditions it was read from. A composite or plan has no `health` + when there is no live object, as for a create. Each composite also lists + under `unhealthy` the composed resources, nested composites' included, that + are not healthy and have no plan of their own. `summary` counts the + composites that are not healthy (`unhealthyComposites`), and the other + resources that are `failing`, `notReady` or `paused`, each once. - `diff` prints a line diff of each changed resource's manifest. Every Secret value, and any value a provider marks sensitive, reads `(sensitive value)`; a value the provider computes on apply reads diff --git a/internal/simulate/report.go b/internal/simulate/report.go index faa79db8..218c30fd 100644 --- a/internal/simulate/report.go +++ b/internal/simulate/report.go @@ -25,10 +25,12 @@ import ( corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" apiextensionsv1 "github.com/crossplane/crossplane/apis/v2/apiextensions/v1" dt "github.com/crossplane/cli/v2/internal/diff/result" + "github.com/crossplane/cli/v2/internal/health" "github.com/crossplane/cli/v2/internal/plan" ) @@ -78,7 +80,7 @@ func FromXRReport(r *dt.XRReport, plans *ProviderPlans, keep func(*unstructured. if a.addDiffs(g.Diffs, &xr) && c.Status == CompositeUnchanged { c.Status = CompositeChanged } - a.composites = append(a.composites, c) + a.addComposite(c, g.Health) } a.addRunErrors(r.Errors, owned) @@ -144,7 +146,7 @@ func FromCompReport(o *dt.CompDiffOutput, plans *ProviderPlans, keep func(*unstr if a.addDiffs(impact.Diffs, &xr) && c.Status == CompositeUnchanged { c.Status = CompositeChanged } - a.composites = append(a.composites, c) + a.addComposite(c, impact.Health) } } @@ -220,7 +222,10 @@ type assembler struct { keep func(*unstructured.Unstructured) bool plans []*plan.ResourcePlan composites []CompositeResult - errors []Error + // composed holds, by composite, the health of what it composed, which + // result reduces to Unhealthy once every plan is known. + composed [][]dt.ResourceHealth + errors []Error // listed holds, per resource, the unredacted changes already planned, // so a change two inputs reach identically is listed once. listed map[string][]listedChange @@ -239,6 +244,37 @@ func newAssembler(provider *ProviderPlans, keep func(*unstructured.Unstructured) return &assembler{provider: provider, keep: keep, plans: []*plan.ResourcePlan{}, listed: map[string][]listedChange{}} } +// addComposite adds c with the live health h the engine read for it. +func (a *assembler) addComposite(c CompositeResult, h dt.CompositeHealth) { + c.Health = h.XR + a.composites = append(a.composites, c) + a.composed = append(a.composed, h.Composed) +} + +// unhealthy sets each composite's Unhealthy: what it composed that is not +// healthy and has no plan in the run, matched across API versions. A +// resource with a plan shows its health there. +func (a *assembler) unhealthy() { + planned := map[schema.GroupKind]map[[2]string]bool{} + for _, p := range a.plans { + gk := p.GroupVersionKind().GroupKind() + if planned[gk] == nil { + planned[gk] = map[[2]string]bool{} + } + planned[gk][[2]string{p.Namespace, p.Name}] = true + } + + for i, composed := range a.composed { + for _, r := range composed { + gk := schema.FromAPIVersionAndKind(r.APIVersion, r.Kind).GroupKind() + if !r.Health.Unhealthy() || planned[gk][[2]string{r.Namespace, r.Name}] { + continue + } + a.composites[i].Unhealthy = append(a.composites[i].Unhealthy, UnhealthyResource{Ref: resourceRef(r.ObjectReference), Health: r.Health}) + } + } +} + // addDiffs adds a plan per diff, in the structured renderer's canonical order. // It reports whether a provider plan changed any of them, which the engine's // verdict alone does not show. @@ -367,6 +403,7 @@ func (a *assembler) addRunErrors(all, owned []dt.OutputError) { } func (a *assembler) result(warnings []dt.OutputWarning) Result { + a.unhealthy() res := NewResult(a.plans, a.composites, a.errors) if a.provider == nil { res.Notes = []string{noteProviderPlanNotRun} @@ -395,6 +432,8 @@ func resourcePlan(d *dt.ResourceDiff) *plan.ResourcePlan { // neither: its Raw views are uncleaned, unlike every other plan's. Before: plan.RedactSecret(d.Current.Clean), After: plan.RedactSecret(d.Desired.Clean), + // Read from the uncleaned live object: Clean has no status. + Health: health.Of(d.Current.Raw), } switch d.DiffType { diff --git a/internal/simulate/report_test.go b/internal/simulate/report_test.go index 241ee7b3..1cba7315 100644 --- a/internal/simulate/report_test.go +++ b/internal/simulate/report_test.go @@ -28,6 +28,7 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" dt "github.com/crossplane/cli/v2/internal/diff/result" + "github.com/crossplane/cli/v2/internal/health" "github.com/crossplane/cli/v2/internal/plan" ) @@ -610,3 +611,145 @@ func TestProviderPlanOnlyForItsRendering(t *testing.T) { t.Errorf("For(removal) = %v, want no plan", p) } } + +// TestHealth covers how the engine's live health reaches the result: on each +// plan from its live object, on each composite, and in each composite's +// unhealthy list for what has no plan; and how Result.Health counts it. +func TestHealth(t *testing.T) { + cond := func(typ, status string) map[string]any { + return map[string]any{"status": map[string]any{"conditions": []any{map[string]any{"type": typ, "status": status, "reason": "R"}}}} + } + live := func(d *dt.ResourceDiff, fields map[string]any) *dt.ResourceDiff { + d.Current.Raw = obj(d.Gvk, d.ResourceName, fields) + return d + } + failing := &health.Health{State: health.Failing, Synced: &health.Condition{Status: corev1.ConditionFalse, Reason: "R"}} + notReady := &health.Health{State: health.NotReady, Ready: &health.Condition{Status: corev1.ConditionFalse, Reason: "R"}} + healthy := &health.Health{State: health.Healthy} + ref := func(apiVersion, kind, name string) corev1.ObjectReference { + return corev1.ObjectReference{APIVersion: apiVersion, Kind: kind, Name: name} + } + cmRef := func(name string) corev1.ObjectReference { return ref("v1", "ConfigMap", name) } + cmPlan := func(name string) plan.ResourceRef { + return plan.ResourceRef{APIVersion: "v1", Kind: "ConfigMap", Name: name} + } + bucketV1 := ref("s3.example.org/v1", "Bucket", "b") + bucketV2 := ref("s3.example.org/v2", "Bucket", "b") + + type want struct { + plans map[string]*health.Health // plan name -> health + composites []CompositeResult + summary HealthSummary + } + cases := map[string]struct { + reason string + in *dt.XRReport + want want + }{ + "AllHealthy": { + reason: "A healthy run carries health on the composite and plans but emits no unhealthy entries, and counts nothing.", + in: &dt.XRReport{Groups: []dt.XRDiffGroup{{ + XR: xrRef, + Diffs: diffs(live(rdiff(cmGVK, "cm", dt.DiffTypeModified, map[string]any{}, map[string]any{"data": "x"}), nil)), + Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{{ObjectReference: cmRef("cm"), Health: healthy}}}, + }}}, + want: want{ + plans: map[string]*health.Health{"cm": healthy}, + composites: []CompositeResult{{Ref: xrPlan, Status: CompositeChanged, Health: healthy}}, + }, + }, + "CreateHasNoHealth": { + reason: "A created resource has no live object, so its plan carries no health; nor does a composite not in the cluster.", + in: &dt.XRReport{Groups: []dt.XRDiffGroup{{ + XR: xrRef, + Diffs: diffs(rdiff(cmGVK, "new", dt.DiffTypeAdded, nil, map[string]any{})), + }}}, + want: want{ + plans: map[string]*health.Health{"new": nil}, + composites: []CompositeResult{{Ref: xrPlan, Status: CompositeChanged}}, + }, + }, + "PlannedAndUnplanned": { + reason: "An unhealthy resource with a plan shows its health there; one without a plan, under a version the plan does not use either, is listed as unhealthy once.", + in: &dt.XRReport{Groups: []dt.XRDiffGroup{{ + XR: xrRef, + Diffs: diffs(live(rdiff(cmGVK, "cm", dt.DiffTypeRemoved, map[string]any{}, nil), cond("Ready", "False"))), + Health: dt.CompositeHealth{XR: failing, Composed: []dt.ResourceHealth{ + {ObjectReference: cmRef("cm"), Health: notReady}, + {ObjectReference: cmRef("quiet"), Health: healthy}, + {ObjectReference: bucketV1, Health: failing}, + }}, + }}}, + want: want{ + plans: map[string]*health.Health{"cm": notReady}, + composites: []CompositeResult{{ + Ref: xrPlan, Status: CompositeChanged, Health: failing, + Unhealthy: []UnhealthyResource{{Ref: resourceRef(bucketV1), Health: failing}}, + }}, + summary: HealthSummary{Composites: 1, Failing: 1, NotReady: 1}, + }, + }, + "PlannedAcrossVersions": { + reason: "A composed resource observed under another API version than its plan's is matched to the plan, not listed again.", + in: &dt.XRReport{Groups: []dt.XRDiffGroup{{ + XR: xrRef, + Diffs: diffs(live(rdiff(schema.FromAPIVersionAndKind(bucketV2.APIVersion, bucketV2.Kind), "b", dt.DiffTypeModified, + map[string]any{}, map[string]any{"spec": "x"}), cond("Synced", "False"))), + Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{{ObjectReference: bucketV1, Health: failing}}}, + }}}, + want: want{ + plans: map[string]*health.Health{"b": failing}, + composites: []CompositeResult{{Ref: xrPlan, Status: CompositeChanged, Health: healthy}}, + summary: HealthSummary{Failing: 1}, + }, + }, + "NestedCountedOnce": { + reason: "A nested composite that is its own input is counted as a composite, not again as a resource, and a resource two composites reach counts once.", + in: &dt.XRReport{Groups: []dt.XRDiffGroup{ + { + XR: xrRef, + Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{ + {ObjectReference: ref("example.org/v1", "XSubnet", "child"), Health: notReady}, + {ObjectReference: cmRef("deep"), Health: failing}, + }}, + }, + { + XR: ref("example.org/v1", "XSubnet", "child"), + Health: dt.CompositeHealth{XR: notReady, Composed: []dt.ResourceHealth{{ObjectReference: cmRef("deep"), Health: failing}}}, + }, + }}, + want: want{ + plans: map[string]*health.Health{}, + composites: []CompositeResult{ + {Ref: xrPlan, Status: CompositeUnchanged, Health: healthy, Unhealthy: []UnhealthyResource{ + {Ref: plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XSubnet", Name: "child"}, Health: notReady}, + {Ref: cmPlan("deep"), Health: failing}, + }}, + {Ref: plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XSubnet", Name: "child"}, Status: CompositeUnchanged, Health: notReady, Unhealthy: []UnhealthyResource{ + {Ref: cmPlan("deep"), Health: failing}, + }}, + }, + summary: HealthSummary{Composites: 1, Failing: 1}, + }, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + got := FromXRReport(tc.in, nil, nil) + gotPlans := map[string]*health.Health{} + for _, p := range got.Plans { + gotPlans[p.Name] = p.Health + } + if diff := cmp.Diff(tc.want.plans, gotPlans, cmpopts.EquateEmpty()); diff != "" { + t.Errorf("%s\nFromXRReport(...) plan health: -want, +got:\n%s", tc.reason, diff) + } + if diff := cmp.Diff(tc.want.composites, got.Composites, cmpopts.EquateEmpty()); diff != "" { + t.Errorf("%s\nFromXRReport(...) composites: -want, +got:\n%s", tc.reason, diff) + } + if diff := cmp.Diff(tc.want.summary, got.Health()); diff != "" { + t.Errorf("%s\nHealth(): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} diff --git a/internal/simulate/result.go b/internal/simulate/result.go index dfc2fa09..e686f07f 100644 --- a/internal/simulate/result.go +++ b/internal/simulate/result.go @@ -28,6 +28,7 @@ import ( "github.com/crossplane/crossplane-runtime/v2/pkg/errors" + "github.com/crossplane/cli/v2/internal/health" "github.com/crossplane/cli/v2/internal/plan" ) @@ -86,6 +87,32 @@ type CompositeResult struct { // ComposedBy references the parent composite of a nested XR; nil for a // top-level XR. ComposedBy *plan.ResourceRef `json:"composedBy,omitempty"` + // Health is the live composite's health before apply, which is distinct + // from Status, the simulated outcome; nil when the cluster has no such + // composite, or it was not simulated. + Health *health.Health `json:"health,omitempty"` + // Unhealthy lists the composed resources, nested composites' included, + // that are live, not healthy, and have no plan in the run (so no health + // of their own to show). + Unhealthy []UnhealthyResource `json:"unhealthy,omitempty"` +} + +// UnhealthyResource is a composed resource that is not healthy before apply. +type UnhealthyResource struct { + Ref plan.ResourceRef `json:"ref"` + Health *health.Health `json:"health"` +} + +// HealthSummary counts what is not healthy before apply, serialized among +// the summary's other counts. Composites counts +// the composites whose own health is not healthy; Failing, NotReady and +// Paused count the other resources, each once however many composites or +// plans reach it. +type HealthSummary struct { + Composites int `json:"unhealthyComposites"` + Failing int `json:"failing"` + NotReady int `json:"notReady"` + Paused int `json:"paused"` } // Error is an error from a simulate run, optionally anchored to a resource. @@ -180,14 +207,76 @@ func (r Result) Deferred() int { return n } +// Health counts the unhealthy composites, and the other resources by health +// state, from Composites and Plans. A resource counts once, under the state +// its first live copy reports, matched across API versions. +func (r Result) Health() HealthSummary { + var s HealthSummary + composites := map[schema.GroupKind]map[[2]string]bool{} + isComposite := func(ref plan.ResourceRef) bool { + return composites[groupKind(ref)][[2]string{ref.Namespace, ref.Name}] + } + for _, c := range r.Composites { + gk := groupKind(c.Ref) + if composites[gk] == nil { + composites[gk] = map[[2]string]bool{} + } + composites[gk][[2]string{c.Ref.Namespace, c.Ref.Name}] = true + if c.Health.Unhealthy() { + s.Composites++ + } + } + + seen := map[schema.GroupKind]map[[2]string]bool{} + count := func(ref plan.ResourceRef, h *health.Health) { + if h == nil || isComposite(ref) { + return + } + gk, id := groupKind(ref), [2]string{ref.Namespace, ref.Name} + if seen[gk][id] { + return + } + if seen[gk] == nil { + seen[gk] = map[[2]string]bool{} + } + seen[gk][id] = true + switch h.State { + case health.Failing: + s.Failing++ + case health.NotReady: + s.NotReady++ + case health.Paused: + s.Paused++ + case health.Healthy: + } + } + for _, p := range r.Plans { + count(p.ResourceRef(), p.Health) + } + for _, c := range r.Composites { + for _, u := range c.Unhealthy { + count(u.Ref, u.Health) + } + } + return s +} + +// groupKind is ref's version-independent type. +func groupKind(ref plan.ResourceRef) schema.GroupKind { + return schema.FromAPIVersionAndKind(ref.APIVersion, ref.Kind).GroupKind() +} + // MarshalJSON writes the result with summary, composites and compositions -// ahead of the plans, which can be long, and with the deferred count inside -// summary. YAML goes through it too. Decoding needs no counterpart: summary -// decodes into Result.Summary, and Deferred is counted from Composites. +// ahead of the plans, which can be long, and with the deferred and health +// counts inside summary. YAML goes through it too. Decoding needs no +// counterpart: summary decodes into Result.Summary, Deferred is counted from +// Composites, and Health from Composites and Plans. func (r Result) MarshalJSON() ([]byte, error) { type summary struct { plan.Summary + HealthSummary + Deferred int `json:"deferred"` } return json.Marshal(struct { @@ -203,7 +292,7 @@ func (r Result) MarshalJSON() ([]byte, error) { }{ FormatVersion: r.FormatVersion, Errored: r.Errored, - Summary: summary{Summary: r.Summary, Deferred: r.Deferred()}, + Summary: summary{Summary: r.Summary, HealthSummary: r.Health(), Deferred: r.Deferred()}, Composites: r.Composites, Compositions: r.Compositions, Plans: r.Plans, diff --git a/internal/simulate/result_test.go b/internal/simulate/result_test.go index 8da19d12..7d9038fe 100644 --- a/internal/simulate/result_test.go +++ b/internal/simulate/result_test.go @@ -24,6 +24,7 @@ import ( "github.com/google/go-cmp/cmp" + "github.com/crossplane/cli/v2/internal/health" "github.com/crossplane/cli/v2/internal/plan" ) @@ -303,3 +304,79 @@ func TestNewResult(t *testing.T) { }) } } + +func TestRenderJSONHealth(t *testing.T) { + xr := plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XNetwork", Name: "prod"} + failing := &health.Health{State: health.Failing, Synced: &health.Condition{Status: "False", Reason: "ReconcileError", Message: "boom"}} + + type want struct { + composites string + plans string + summary string + } + cases := map[string]struct { + reason string + in Result + want want + }{ + "NoLiveObjects": { + reason: "Without live objects no health or unhealthy key is written, and every health count is zero.", + in: NewResult( + []*plan.ResourcePlan{{APIVersion: "v1", Kind: "ConfigMap", Name: "cm", Action: plan.ActionCreate, Composite: &xr}}, + []CompositeResult{{Ref: xr, Status: CompositeChanged}}, nil), + want: want{ + composites: `[{"ref":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"status":"changed"}]`, + plans: `[{"apiVersion":"v1","kind":"ConfigMap","name":"cm","action":"create","composite":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"}}]`, + summary: `{"create":1,"update":0,"destroy":0,"replace":0,"noop":0,"approximate":0,"errored":0,"unhealthyComposites":0,"failing":0,"notReady":0,"paused":0,"deferred":0}`, + }, + }, + "Unhealthy": { + reason: "Composite and plan health, and the unhealthy list, are written under their keys with the conditions they came from.", + in: NewResult( + []*plan.ResourcePlan{{APIVersion: "v1", Kind: "ConfigMap", Name: "cm", Action: plan.ActionNoOp, Composite: &xr, Health: &health.Health{State: health.Paused}}}, + []CompositeResult{{ + Ref: xr, Status: CompositeUnchanged, Health: failing, + Unhealthy: []UnhealthyResource{{Ref: plan.ResourceRef{APIVersion: "v1", Kind: "Secret", Name: "s"}, Health: &health.Health{State: health.NotReady, Ready: &health.Condition{Status: "False"}}}}, + }}, nil), + want: want{ + composites: `[{"ref":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"status":"unchanged",` + + `"health":{"state":"failing","synced":{"status":"False","reason":"ReconcileError","message":"boom"}},` + + `"unhealthy":[{"ref":{"apiVersion":"v1","kind":"Secret","name":"s"},"health":{"state":"notReady","ready":{"status":"False"}}}]}]`, + plans: `[{"apiVersion":"v1","kind":"ConfigMap","name":"cm","action":"no-op","composite":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"health":{"state":"paused"}}]`, + summary: `{"create":0,"update":0,"destroy":0,"replace":0,"noop":1,"approximate":0,"errored":0,"unhealthyComposites":1,"failing":0,"notReady":1,"paused":1,"deferred":0}`, + }, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + var buf bytes.Buffer + r, _ := NewRenderer(plan.FormatJSON) + if err := r.Render(&buf, tc.in); err != nil { + t.Fatalf("%s\nRender(json): unexpected error: %v", tc.reason, err) + } + var top map[string]json.RawMessage + if err := json.Unmarshal(buf.Bytes(), &top); err != nil { + t.Fatalf("%s\nRender(json): output is not valid JSON: %v", tc.reason, err) + } + compact := func(raw json.RawMessage) string { + var b bytes.Buffer + _ = json.Compact(&b, raw) + return b.String() + } + got := want{composites: compact(top["composites"]), plans: compact(top["plans"]), summary: compact(top["summary"])} + if diff := cmp.Diff(tc.want, got, cmp.AllowUnexported(want{})); diff != "" { + t.Errorf("%s\nRender(json): -want, +got:\n%s", tc.reason, diff) + } + + // What is written decodes back to what was rendered. + var back Result + if err := json.Unmarshal(buf.Bytes(), &back); err != nil { + t.Fatalf("%s\nRender(json): cannot decode: %v", tc.reason, err) + } + if diff := cmp.Diff(tc.in, back); diff != "" { + t.Errorf("%s\nRender(json) round trip: -want, +got:\n%s", tc.reason, diff) + } + }) + } +} From c5abee572109985e6ec9aa2a11c2ed1d0d031b31 Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Wed, 18 Nov 2026 10:40:34 -0500 Subject: [PATCH 04/11] fix(diff): read a claim's health from its backing XR and list nested health once A claim mirrors only part of its backing XR's conditions, so the composite health of a claim input is now its backing XR's. RenderedResources classifies health as it records the live objects instead of retaining them. Merge now records each nested composite's health, with the nested composite as the via of what it composes directly, so every composed resource is listed once with the composite that composes it. That also covers a nested XR found by name rather than in its parent's observed set, which previously lost its health when it had no plan. The comp path stores each XR's computed health rather than its render. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/diff/diffprocessor/comp_processor.go | 19 +- .../diff/diffprocessor/comp_processor_test.go | 26 +- internal/diff/diffprocessor/diff_processor.go | 8 +- .../diff/diffprocessor/diff_processor_test.go | 232 ++++++++++++++++++ internal/diff/result/types.go | 8 +- internal/diff/types/types.go | 92 ++++--- internal/diff/types/types_test.go | 71 +++++- 7 files changed, 391 insertions(+), 65 deletions(-) diff --git a/internal/diff/diffprocessor/comp_processor.go b/internal/diff/diffprocessor/comp_processor.go index b14e1efa..dd89d35a 100644 --- a/internal/diff/diffprocessor/comp_processor.go +++ b/internal/diff/diffprocessor/comp_processor.go @@ -53,9 +53,11 @@ type XRDiffResult struct { // Error contains any error that occurred while processing this XR. // nil means processing was successful. Error error - // rendered is what the render produced: the unchanged renderings Diffs leaves out, for the overlap - // check, and the live objects the impact's health is read from. - rendered dtypes.RenderedResources + // unchanged holds the unchanged renderings Diffs leaves out, for the overlap check only. + unchanged map[string]*dt.ResourceDiff + // health is the live health the render read, computed as the XR is diffed so that the live objects + // are not retained until impact analysis. + health dt.CompositeHealth } // HasChanges returns true if this XR has downstream resource changes. @@ -601,7 +603,7 @@ func (p *DefaultCompDiffProcessor) processSingleComposition(ctx context.Context, for _, xr := range keptXRs { if r := xrResults[dt.MakeDiffKeyFromResource(xr)]; r != nil && !r.HasError() { group := dt.XRDiffGroup{XR: objectRef(xr), Diffs: r.Diffs} - composites = append(composites, renderedComposite{xr: xr, group: withUnchanged([]dt.XRDiffGroup{group}, []map[string]*dt.ResourceDiff{r.rendered.Unchanged()})[0]}) + composites = append(composites, renderedComposite{xr: xr, group: withUnchanged([]dt.XRDiffGroup{group}, []map[string]*dt.ResourceDiff{r.unchanged})[0]}) } } @@ -830,8 +832,9 @@ func (p *DefaultCompDiffProcessor) collectXRDiffs(ctx context.Context, xrs []*un } else { // Store successful result with diffs results[resourceID] = &XRDiffResult{ - Diffs: diffs, - rendered: rendered, + Diffs: diffs, + unchanged: rendered.Unchanged(), + health: rendered.Health(), } } } @@ -1643,7 +1646,7 @@ func (p *DefaultCompDiffProcessor) buildImpactAnalysis(xrs []*un.Unstructured, r case result != nil && result.HasChanges(): impact.Status = dt.XRStatusChanged impact.Diffs = result.Diffs - impact.Health = result.rendered.Health() + impact.Health = result.health summary.WithChanges++ default: impact.Status = dt.XRStatusUnchanged @@ -1653,7 +1656,7 @@ func (p *DefaultCompDiffProcessor) buildImpactAnalysis(xrs []*un.Unstructured, r impact.Diffs = result.Diffs } if result != nil { - impact.Health = result.rendered.Health() + impact.Health = result.health } summary.Unchanged++ } diff --git a/internal/diff/diffprocessor/comp_processor_test.go b/internal/diff/diffprocessor/comp_processor_test.go index 24814f92..c3466a06 100644 --- a/internal/diff/diffprocessor/comp_processor_test.go +++ b/internal/diff/diffprocessor/comp_processor_test.go @@ -3030,16 +3030,20 @@ func TestDefaultCompDiffProcessor_DiffComposition_Health(t *testing.T) { status dt.XRStatus health dt.CompositeHealth } + type args struct { + // changed makes the render produce a change; renderErr makes it fail. + changed bool + renderErr error + } cases := map[string]struct { reason string - // changed makes the render produce a change; errs makes it fail. - changed, errs bool - want want + args args + want want }{ "Changed": { - reason: "A changed composite carries the health its render read.", - changed: true, - want: want{status: dt.XRStatusChanged, health: live}, + reason: "A changed composite carries the health its render read.", + args: args{changed: true}, + want: want{status: dt.XRStatusChanged, health: live}, }, "Unchanged": { reason: "An unchanged composite carries its health too: being unchanged does not make it healthy.", @@ -3047,7 +3051,7 @@ func TestDefaultCompDiffProcessor_DiffComposition_Health(t *testing.T) { }, "Errored": { reason: "A composite whose render failed carries no health.", - errs: true, + args: args{renderErr: errors.New("render failed")}, want: want{status: dt.XRStatusError}, }, } @@ -3058,14 +3062,14 @@ func TestDefaultCompDiffProcessor_DiffComposition_Health(t *testing.T) { proc := NewCompDiffProcessor(&tu.MockDiffProcessor{ DiffSingleResourceFn: func(_ context.Context, res *un.Unstructured, _ types.CompositionProvider) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { - if tc.errs { - return nil, types.RenderedResources{}, errors.New("render failed") + if tc.args.renderErr != nil { + return nil, types.RenderedResources{}, tc.args.renderErr } var rendered types.RenderedResources - rendered.SetLive(res) + rendered.SetComposite(res) rendered.AddObserved(bucket) diffs := map[string]*dt.ResourceDiff{} - if tc.changed { + if tc.args.changed { d := &dt.ResourceDiff{Gvk: bucket.GroupVersionKind(), ResourceName: "bucket", DiffType: dt.DiffTypeModified, Current: dt.ResourceViews{Raw: bucket}, Desired: dt.ResourceViews{Raw: bucket}} diffs[d.GetDiffKey()] = d } diff --git a/internal/diff/diffprocessor/diff_processor.go b/internal/diff/diffprocessor/diff_processor.go index 4237b05d..f53eb086 100644 --- a/internal/diff/diffprocessor/diff_processor.go +++ b/internal/diff/diffprocessor/diff_processor.go @@ -528,9 +528,11 @@ func (p *DefaultDiffProcessor) diffSingleResourceInternal(ctx context.Context, r return nil, types.RenderedResources{}, errors.Wrap(err, "cannot calculate diffs for composed resources") } - // Record the live objects already fetched, for health. The observed resources are the cluster's, - // never the copies --eventual-state synthesizes Ready on (see RenderToStableState). - rendered.SetLive(composite.Cluster) + // Record the health of the live objects already fetched: the composite that composes (for a claim, + // its backing XR, whose conditions the claim only partly mirrors) and what it composes. The observed + // resources are the cluster's, never the copies --eventual-state synthesizes Ready on (see + // RenderToStableState). + rendered.SetComposite(composite.Composed()) for i := range observedResources { rendered.AddObserved(&observedResources[i].Unstructured) diff --git a/internal/diff/diffprocessor/diff_processor_test.go b/internal/diff/diffprocessor/diff_processor_test.go index de257e3a..b1065416 100644 --- a/internal/diff/diffprocessor/diff_processor_test.go +++ b/internal/diff/diffprocessor/diff_processor_test.go @@ -1117,6 +1117,238 @@ func TestDefaultDiffProcessor_PerformDiff_Groups(t *testing.T) { } } +// TestDefaultDiffProcessor_PerformDiff_Health covers the health each group carries, end to end through +// composite resolution, the observed-resource fetch, the nested XR merge and the input validator. The +// composite reports the cluster XR's own health (for a claim, its backing XR's), and every composed +// resource is listed once, nested composites' own included, each with the nested composite that +// directly composes it. +func TestDefaultDiffProcessor_PerformDiff_Health(t *testing.T) { + ctx := t.Context() + + const apiVersion = testGroup + "/" + testAPIVersion + + parentCluster := tu.NewResource(apiVersion, testKind, "parent").WithUID("parent-uid"). + WithCondition("Synced", "False", "ReconcileError"). + Build() + childCluster := tu.NewResource(apiVersion, "XChild", "child").WithUID("child-uid"). + WithCompositionResourceName("child"). + ControlledBy(parentCluster). + WithCondition("Ready", "False", "Creating"). + Build() + bucketA := tu.NewResource(apiVersion, "Bucket", "bucket-a"). + WithCompositionResourceName("bucket-a"). + ControlledBy(parentCluster). + WithCondition("Ready", "False", "Creating"). + Build() + bucketB := tu.NewResource(apiVersion, "Bucket", "bucket-b"). + WithCompositionResourceName("bucket-b"). + ControlledBy(childCluster). + WithCondition("Synced", "False", "ReconcileError"). + Build() + // The claim is healthy, so only its backing XR (parent) can make the composite failing. + claimCluster := tu.NewResource(apiVersion, "Claim", "my-claim").InNamespace("ns"). + WithSpecField("resourceRef", map[string]any{"apiVersion": apiVersion, "kind": testKind, "name": "parent"}). + WithCondition("Synced", "True", "ReconcileSuccess"). + WithCondition("Ready", "True", "Available"). + Build() + + parentInput := tu.NewResource(apiVersion, testKind, "parent").WithSpecField("coolField", "value").Build() + claimInput := tu.NewResource(apiVersion, "Claim", "my-claim").InNamespace("ns").WithSpecField("coolField", "value").Build() + + fullTree := tu.NewTreeNode(parentCluster).WithChildren( + tu.NewTreeNode(childCluster).WithChildren(tu.NewTreeNode(bucketB)), + tu.NewTreeNode(bucketA), + ).Build() + // The tree without the nested XR, as when the tree client cannot walk to it: the nested XR is then + // found by name instead. + treeWithoutChild := tu.NewTreeNode(parentCluster).WithChildren(tu.NewTreeNode(bucketA)).Build() + childTree := tu.NewTreeNode(childCluster).WithChildren(tu.NewTreeNode(bucketB)).Build() + + xrds := map[string]*un.Unstructured{ + testKind: tu.NewXRD(testCRDName, testGroup, testKind).WithPlural(testPlural).WithSingular(testSingular).BuildAsUnstructured(), + "XChild": tu.NewXRD("xchilds."+testGroup, testGroup, "XChild").WithPlural("xchilds").WithSingular("xchild").BuildAsUnstructured(), + } + crds := map[string]*extv1.CustomResourceDefinition{ + testCRDName: makeTestCRD(testCRDName, testKind, testGroup, testAPIVersion), + "xchilds." + testGroup: makeTestCRD("xchilds."+testGroup, "XChild", testGroup, testAPIVersion), + } + compositions := map[string]*apiextensionsv1.Composition{ + testKind: tu.NewComposition("parent-comp").WithCompositeTypeRef(apiVersion, testKind). + WithPipelineMode().WithPipelineStep("step1", "function-test", nil).Build(), + "XChild": tu.NewComposition("child-comp").WithCompositeTypeRef(apiVersion, "XChild"). + WithPipelineMode().WithPipelineStep("step1", "function-test", nil).Build(), + } + // rendered is what each composite's composition renders, by the composite's kind. + rendered := map[string][]cpd.Unstructured{ + testKind: { + *tu.NewResource(apiVersion, "XChild", "child").WithCompositionResourceName("child").BuildUComposed(), + *tu.NewResource(apiVersion, "Bucket", "bucket-a").WithCompositionResourceName("bucket-a").BuildUComposed(), + }, + "XChild": {*tu.NewResource(apiVersion, "Bucket", "bucket-b").WithCompositionResourceName("bucket-b").BuildUComposed()}, + } + cluster := map[string]*un.Unstructured{} + for _, u := range []*un.Unstructured{parentCluster, childCluster, claimCluster} { + cluster[dt.MakeDiffKeyFromResource(u)] = u + } + + ref := func(kind, name string) corev1.ObjectReference { + return corev1.ObjectReference{APIVersion: apiVersion, Kind: kind, Name: name} + } + via := ref("XChild", "child") + failing := &health.Health{State: health.Failing, Synced: &health.Condition{Status: corev1.ConditionFalse, Reason: "ReconcileError"}} + notReady := &health.Health{State: health.NotReady, Ready: &health.Condition{Status: corev1.ConditionFalse, Reason: "Creating"}} + nested := dt.CompositeHealth{ + XR: failing, + Composed: []dt.ResourceHealth{ + {ObjectReference: ref("Bucket", "bucket-a"), Health: notReady}, + {ObjectReference: ref("Bucket", "bucket-b"), Via: &via, Health: failing}, + {ObjectReference: ref("XChild", "child"), Health: notReady}, + }, + } + + type args struct { + input *un.Unstructured + parentTree *resource.Resource + eventualState bool + verdict error + } + + tests := map[string]struct { + reason string + args args + want dt.CompositeHealth + }{ + "NestedXRResourcesListedOnceWithVia": { + reason: "The nested XR is a resource of its parent, and what it composes is listed once with it as via.", + args: args{input: parentInput, parentTree: fullTree}, + want: nested, + }, + "NestedXRFoundByNameKeepsItsHealth": { + reason: "A nested XR absent from the parent's observed set, found by name instead, is still listed.", + args: args{input: parentInput, parentTree: treeWithoutChild}, + want: nested, + }, + "ClaimReportsItsBackingXR": { + reason: "A claim's health is its backing XR's, which here is failing while the claim is healthy.", + args: args{input: claimInput, parentTree: fullTree}, + want: nested, + }, + "EventualStateLeavesHealthAsObserved": { + reason: "--eventual-state synthesizes Ready only for the next render; bucket-a stays notReady.", + args: args{input: parentInput, parentTree: fullTree, eventualState: true}, + want: nested, + }, + "VerdictErrorClearsHealth": { + reason: "A group the validator fails reports no health, as it reports no diffs.", + args: args{input: parentInput, parentTree: fullTree, verdict: errors.New("rejected")}, + want: dt.CompositeHealth{}, + }, + } + + for name, tc := range tests { + t.Run(name, func(t *testing.T) { + trees := map[string]*resource.Resource{"parent": tc.args.parentTree, "child": childTree} + + k8sClients := k8.Clients{ + Apply: tu.NewMockApplyClient().WithSuccessfulDryRun().Build(), + Resource: tu.NewMockResourceClient().WithResourcesExist(parentCluster, childCluster, claimCluster).Build(), + Schema: tu.NewMockSchemaClient(). + WithNoResourcesRequiringCRDs(). + WithGetCRDByName(func(name string) (*extv1.CustomResourceDefinition, error) { + if crd, ok := crds[name]; ok { + return crd, nil + } + return nil, errors.Errorf("CRD %s not found", name) + }). + Build(), + Type: tu.NewMockTypeConverter().Build(), + } + xpClients := xp.Clients{ + Credential: &tu.MockCredentialClient{}, + Definition: tu.NewMockDefinitionClient(). + WithGetXRDForXR(func(_ context.Context, gvk schema.GroupVersionKind) (*un.Unstructured, error) { + if xrd, ok := xrds[gvk.Kind]; ok { + return xrd, nil + } + return nil, errors.Errorf("no XRD for %s", gvk) + }). + WithIsClaimResource(func(_ context.Context, res *un.Unstructured) bool { return res.GetKind() == "Claim" }). + Build(), + Function: tu.NewMockFunctionClient(). + WithSuccessfulFunctionsFetch([]pkgv1.Function{{ObjectMeta: metav1.ObjectMeta{Name: "function-test"}}}). + Build(), + ResourceTree: tu.NewMockResourceTreeClient(). + WithGetResourceTree(func(_ context.Context, xr *un.Unstructured) (*resource.Resource, error) { + if tree, ok := trees[xr.GetName()]; ok { + return tree, nil + } + return nil, errors.Errorf("no tree for %s", xr.GetName()) + }). + Build(), + } + + opts := append(testProcessorOptions(t), + WithEventualState(tc.args.eventualState), + WithRenderFunc(func(_ context.Context, _ logging.Logger, in RenderInputs) (render.CompositionOutputs, error) { + return render.CompositionOutputs{CompositeResource: in.CompositeResource, ComposedResources: rendered[in.CompositeResource.GetKind()]}, nil + }), + WithSchemaValidatorFactory(func(k8.SchemaClient, k8.ResourceClient, xp.DefinitionClient, logging.Logger) SchemaValidator { + return &tu.MockSchemaValidator{ + ValidateResourcesFn: func(context.Context, *un.Unstructured, []cpd.Unstructured) error { return nil }, + } + }), + WithDiffCalculatorFactory(func(k8.ApplyClient, k8.AccessChecker, xp.ResourceTreeClient, ResourceManager, logging.Logger, compare.Options, DryRunOn, Defaulter, func(*un.Unstructured) bool) DiffCalculator { + return &tu.MockDiffCalculator{ + // An unchanged diff of the composite against its cluster copy, which is what + // nested processing and removal detection read the cluster XR from. + CalculateNonRemovalDiffsFn: func(_ context.Context, xr *cmp.Unstructured, _ render.CompositionOutputs) (map[string]*dt.ResourceDiff, types.RenderedResources, error) { + key := dt.MakeDiffKeyFromResource(xr.GetUnstructured()) + return map[string]*dt.ResourceDiff{key: { + Gvk: xr.GroupVersionKind(), + Namespace: xr.GetNamespace(), + ResourceName: xr.GetName(), + DiffType: dt.DiffTypeEqual, + Current: dt.ResourceViews{Raw: cluster[key]}, + }}, types.RenderedResources{}, nil + }, + } + }), + ) + + if tc.args.verdict != nil { + opts = append(opts, WithInputValidatorFactory(func(dt.Advisories, []*un.Unstructured) InputValidator { + return &tu.MockInputValidator{ + ToRenderFn: func() []types.ValidatedInput { return []types.ValidatedInput{{Resource: tc.args.input}} }, + RecordRenderFn: func(int, map[string]bool, error) {}, + VerdictsFn: func([]dt.XRDiffGroup) []error { return []error{tc.args.verdict} }, + RenderOverlapsFn: func([]dt.XRDiffGroup) []error { return nil }, + } + })) + } + + processor := NewDiffProcessor(k8sClients, xpClients, opts...) + + report, err := processor.PerformDiff(ctx, []*un.Unstructured{tc.args.input}, func(_ context.Context, res *un.Unstructured) (types.ResolvedComposition, error) { + if comp, ok := compositions[res.GetKind()]; ok { + return types.ResolvedComposition{Composition: comp}, nil + } + return types.ResolvedComposition{}, xp.ErrNoMatchingComposition + }) + if err != nil && tc.args.verdict == nil { + t.Fatalf("\n%s\nPerformDiff(...): unexpected error: %v", tc.reason, err) + } + + if len(report.Groups) != 1 { + t.Fatalf("\n%s\nPerformDiff(...): got %d groups, want 1", tc.reason, len(report.Groups)) + } + + if diff := gcmp.Diff(tc.want, report.Groups[0].Health); diff != "" { + t.Errorf("\n%s\nPerformDiff(...) group health: -want, +got:\n%s", tc.reason, diff) + } + }) + } +} + // TestDefaultDiffProcessor_PerformDiff_LateWarningsReachStructuredOutput pins the warning channel's // contract for advisories that can only be discovered during teardown. The leftover-function-container // advisory is raised from FunctionProvider.Cleanup, which used to run in the command layer's defer — diff --git a/internal/diff/result/types.go b/internal/diff/result/types.go index 62c86849..ed0cc2f0 100644 --- a/internal/diff/result/types.go +++ b/internal/diff/result/types.go @@ -56,8 +56,8 @@ type XRDiffGroup struct { // render already fetched. It describes the cluster, not the desired state: a resource the render // would create has no entry, and one it would delete has one. type CompositeHealth struct { - // XR is the health of the input's own cluster object (for a claim, the claim); nil when the - // cluster has none. + // XR is the health of the cluster object the input composes: the XR itself or, for a claim, its + // backing XR. It is nil when the cluster has none. XR *health.Health // Composed holds the health of each observed composed resource, once each, in diff key order. Composed []ResourceHealth @@ -67,6 +67,10 @@ type CompositeHealth struct { type ResourceHealth struct { corev1.ObjectReference + // Via is the nested composite that directly composes the resource, or nil when the input's own + // composite does. + Via *corev1.ObjectReference + Health *health.Health } diff --git a/internal/diff/types/types.go b/internal/diff/types/types.go index 2644d745..97f98333 100644 --- a/internal/diff/types/types.go +++ b/internal/diff/types/types.go @@ -146,52 +146,74 @@ type CredentialFetchResult struct { // It also holds, by diff key, the diff of each unchanged rendering the calculator did not keep among // the diffs it returns, so input validation sees every rendering whether or not equal diffs are kept. // -// Finally it holds the live cluster objects the render already fetched, for health reporting: the -// composite's own cluster copy, and by diff key every composed resource observed beneath it. +// Finally it holds, for health reporting, the health of the live objects the render already fetched, +// classified as they are recorded so the objects themselves are not retained: the composite's own, and +// by diff key that of every composed resource observed beneath it, with the nested composite that +// directly composes each. type RenderedResources struct { keys map[string]bool desired map[string]map[string]bool // composite identity -> composition resource names it desired unchanged map[string]*dt.ResourceDiff - live *un.Unstructured - observed map[string]*un.Unstructured + composite *dt.ResourceHealth + composed map[string]dt.ResourceHealth } -// SetLive records the composite's own cluster copy (for a claim, the claim). Merge does not carry it: -// a nested composite's cluster copy is one of its parent's observed resources. -func (r *RenderedResources) SetLive(composite *un.Unstructured) { - r.live = composite +// SetComposite records the cluster object of the composite rendered: the XR itself or, for a claim, its +// backing XR. A nil object, for a composite the cluster does not have yet, records nothing. +func (r *RenderedResources) SetComposite(live *un.Unstructured) { + if live == nil { + return + } + + h := resourceHealth(live) + r.composite = &h } -// AddObserved records a composed resource's cluster copy. A resource observed twice, as a nested -// composite is (once beneath its parent, once as the composite it is), is recorded once. +// AddObserved records a composed resource's cluster copy, which the composite rendered composes +// directly. A resource recorded twice keeps its first record. func (r *RenderedResources) AddObserved(res *un.Unstructured) { - if r.observed == nil { - r.observed = make(map[string]*un.Unstructured) + r.addComposed(resourceHealth(res)) +} + +func (r *RenderedResources) addComposed(h dt.ResourceHealth) { + key := dt.MakeDiffKey(h.APIVersion, h.Kind, h.Namespace, h.Name) + if _, ok := r.composed[key]; ok { + return } - r.observed[dt.MakeDiffKeyFromResource(res)] = res + if r.composed == nil { + r.composed = make(map[string]dt.ResourceHealth) + } + + r.composed[key] = h } -// Health classifies the live objects SetLive and AddObserved recorded. +// Health returns the health SetComposite and AddObserved recorded, and Merge carried. func (r *RenderedResources) Health() dt.CompositeHealth { - h := dt.CompositeHealth{XR: health.Of(r.live)} - - for _, key := range slices.Sorted(maps.Keys(r.observed)) { - res := r.observed[key] - h.Composed = append(h.Composed, dt.ResourceHealth{ - ObjectReference: corev1.ObjectReference{ - APIVersion: res.GetAPIVersion(), - Kind: res.GetKind(), - Name: res.GetName(), - Namespace: res.GetNamespace(), - }, - Health: health.Of(res), - }) + var h dt.CompositeHealth + if r.composite != nil { + h.XR = r.composite.Health + } + + for _, key := range slices.Sorted(maps.Keys(r.composed)) { + h.Composed = append(h.Composed, r.composed[key]) } return h } +func resourceHealth(u *un.Unstructured) dt.ResourceHealth { + return dt.ResourceHealth{ + ObjectReference: corev1.ObjectReference{ + APIVersion: u.GetAPIVersion(), + Kind: u.GetKind(), + Name: u.GetName(), + Namespace: u.GetNamespace(), + }, + Health: health.Of(u), + } +} + // AddUnchanged records the diff of an unchanged rendering that is not among the returned diffs. func (r *RenderedResources) AddUnchanged(key string, d *dt.ResourceDiff) { if r.unchanged == nil { @@ -246,8 +268,20 @@ func (r *RenderedResources) Merge(other RenderedResources) { r.AddUnchanged(key, d) } - for _, res := range other.observed { - r.AddObserved(res) + // What other's composite composed directly, it composed via that composite; and the composite + // itself is composed by r's, which records it already when it observed it (but not when the + // composite was found by name instead). + for _, h := range other.composed { + if h.Via == nil && other.composite != nil { + via := other.composite.ObjectReference + h.Via = &via + } + + r.addComposed(h) + } + + if other.composite != nil { + r.addComposed(*other.composite) } } diff --git a/internal/diff/types/types_test.go b/internal/diff/types/types_test.go index 851e22a2..3347a5de 100644 --- a/internal/diff/types/types_test.go +++ b/internal/diff/types/types_test.go @@ -47,6 +47,10 @@ func TestRenderedResourcesHealth(t *testing.T) { parent := obj("example.org/v1", "XParent", "parent", "") child := obj("example.org/v1", "XChild", "child", "False") grandchild := obj("v1", "ConfigMap", "grandchild", "") + leaf := obj("v1", "Secret", "leaf", "") + childRef := ref("example.org/v1", "XChild", "child") + grandchildRef := ref("v1", "ConfigMap", "grandchild") + leafRef := ref("v1", "Secret", "leaf") type args struct { build func() RenderedResources @@ -61,11 +65,11 @@ func TestRenderedResourcesHealth(t *testing.T) { args: args{build: func() RenderedResources { return RenderedResources{} }}, want: dt.CompositeHealth{}, }, - "LiveAndObserved": { - reason: "The live composite gives XR, and each observed resource an entry, in diff key order.", + "CompositeAndObserved": { + reason: "The composite gives XR, and each observed resource an entry with no via, in diff key order.", args: args{build: func() RenderedResources { var r RenderedResources - r.SetLive(parent) + r.SetComposite(parent) r.AddObserved(grandchild) r.AddObserved(child) return r @@ -73,28 +77,71 @@ func TestRenderedResourcesHealth(t *testing.T) { want: dt.CompositeHealth{ XR: healthy, Composed: []dt.ResourceHealth{ - {ObjectReference: ref("example.org/v1", "XChild", "child"), Health: notReady}, - {ObjectReference: ref("v1", "ConfigMap", "grandchild"), Health: healthy}, + {ObjectReference: childRef, Health: notReady}, + {ObjectReference: grandchildRef, Health: healthy}, }, }, }, - "NestedMergedOnce": { - reason: "Merging a nested composite's render adds what it observed, but not its own live copy as XR; one observed by both levels counts once.", + "NoComposite": { + reason: "A composite the cluster does not have yet records no XR health.", + args: args{build: func() RenderedResources { + var r RenderedResources + r.SetComposite(nil) + return r + }}, + want: dt.CompositeHealth{}, + }, + "NestedMergedOnceWithVia": { + reason: "Merging a nested composite's render lists what it composed with the nested composite as via, and the nested composite itself once, as the parent observed it.", args: args{build: func() RenderedResources { var r, nested RenderedResources - r.SetLive(parent) + r.SetComposite(parent) r.AddObserved(child) - nested.SetLive(child) + nested.SetComposite(child) nested.AddObserved(grandchild) - nested.AddObserved(child) r.Merge(nested) return r }}, want: dt.CompositeHealth{ XR: healthy, Composed: []dt.ResourceHealth{ - {ObjectReference: ref("example.org/v1", "XChild", "child"), Health: notReady}, - {ObjectReference: ref("v1", "ConfigMap", "grandchild"), Health: healthy}, + {ObjectReference: childRef, Health: notReady}, + {ObjectReference: grandchildRef, Via: &childRef, Health: healthy}, + }, + }, + }, + "NestedNotObservedByParent": { + reason: "A nested composite the parent did not observe (found by name instead) is still listed, from its own render.", + args: args{build: func() RenderedResources { + var r, nested RenderedResources + r.SetComposite(parent) + nested.SetComposite(child) + r.Merge(nested) + return r + }}, + want: dt.CompositeHealth{ + XR: healthy, + Composed: []dt.ResourceHealth{{ObjectReference: childRef, Health: notReady}}, + }, + }, + "DeeplyNestedKeepsDirectParent": { + reason: "Via names the composite that directly composes a resource, however deep, not an intermediate one.", + args: args{build: func() RenderedResources { + var r, nested, deeper RenderedResources + r.SetComposite(parent) + nested.SetComposite(child) + deeper.SetComposite(grandchild) + deeper.AddObserved(leaf) + nested.Merge(deeper) + r.Merge(nested) + return r + }}, + want: dt.CompositeHealth{ + XR: healthy, + Composed: []dt.ResourceHealth{ + {ObjectReference: childRef, Health: notReady}, + {ObjectReference: grandchildRef, Via: &childRef, Health: healthy}, + {ObjectReference: leafRef, Via: &grandchildRef, Health: healthy}, }, }, }, From d3deddc35501472919796a224812739e3440e97e Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Wed, 18 Nov 2026 10:40:34 -0500 Subject: [PATCH 05/11] feat(simulate): name the via of nested unhealthy resources and nest summary health Each unhealthy entry names the nested composite that composes it under via. The health counts move under summary.health, and a composite in two entries is counted once. The help documents via, summary.health, a claim's health, and that a composite that was not simulated has no health. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/simulate/help/output.md | 15 +++--- internal/simulate/report.go | 7 ++- internal/simulate/report_test.go | 87 +++++++++++++++++++------------- internal/simulate/result.go | 36 +++++++------ internal/simulate/result_test.go | 47 ++++++++++------- 5 files changed, 117 insertions(+), 75 deletions(-) diff --git a/internal/simulate/help/output.md b/internal/simulate/help/output.md index d48ad27c..bcd9c413 100644 --- a/internal/simulate/help/output.md +++ b/internal/simulate/help/output.md @@ -20,12 +20,15 @@ The `-o` flag picks the output format: `failing` (its Synced condition is False), `notReady` (its Ready condition is False), `paused` (it carries the `crossplane.io/paused: "true"` annotation, whatever its conditions), or `healthy`, with the `synced` and - `ready` conditions it was read from. A composite or plan has no `health` - when there is no live object, as for a create. Each composite also lists - under `unhealthy` the composed resources, nested composites' included, that - are not healthy and have no plan of their own. `summary` counts the - composites that are not healthy (`unhealthyComposites`), and the other - resources that are `failing`, `notReady` or `paused`, each once. + `ready` conditions it was read from. A claim's `health` is its backing + composite resource's. A composite or plan has no `health` when there is no + live object, as for a create, or, for a composite, when it was not + simulated (`error`, `skipped`, `deferred`). Each composite also lists under + `unhealthy` the composed resources that are not healthy and have no plan of + their own, each once. That includes nested composites and what they compose; + an entry a nested composite composes names it under `via`. `summary.health` + counts the composites that are not healthy (`unhealthyComposites`), and the + other resources that are `failing`, `notReady` or `paused`, each once. - `diff` prints a line diff of each changed resource's manifest. Every Secret value, and any value a provider marks sensitive, reads `(sensitive value)`; a value the provider computes on apply reads diff --git a/internal/simulate/report.go b/internal/simulate/report.go index 218c30fd..2e978109 100644 --- a/internal/simulate/report.go +++ b/internal/simulate/report.go @@ -270,7 +270,12 @@ func (a *assembler) unhealthy() { if !r.Health.Unhealthy() || planned[gk][[2]string{r.Namespace, r.Name}] { continue } - a.composites[i].Unhealthy = append(a.composites[i].Unhealthy, UnhealthyResource{Ref: resourceRef(r.ObjectReference), Health: r.Health}) + u := UnhealthyResource{Ref: resourceRef(r.ObjectReference), Health: r.Health} + if r.Via != nil { + via := resourceRef(*r.Via) + u.Via = &via + } + a.composites[i].Unhealthy = append(a.composites[i].Unhealthy, u) } } } diff --git a/internal/simulate/report_test.go b/internal/simulate/report_test.go index 1cba7315..257acf50 100644 --- a/internal/simulate/report_test.go +++ b/internal/simulate/report_test.go @@ -635,24 +635,34 @@ func TestHealth(t *testing.T) { } bucketV1 := ref("s3.example.org/v1", "Bucket", "b") bucketV2 := ref("s3.example.org/v2", "Bucket", "b") + child := ref("example.org/v1", "XSubnet", "child") + childPlan := resourceRef(child) + compRef := func(name string) *plan.ResourceRef { + return &plan.ResourceRef{APIVersion: "apiextensions.crossplane.io/v1", Kind: "Composition", Name: name} + } + unhealthyXR := dt.CompositeHealth{XR: failing, Composed: []dt.ResourceHealth{{ObjectReference: cmRef("cm"), Health: notReady}}} type want struct { plans map[string]*health.Health // plan name -> health composites []CompositeResult summary HealthSummary } + type args struct { + xr *dt.XRReport + comp *dt.CompDiffOutput + } cases := map[string]struct { reason string - in *dt.XRReport + args args want want }{ "AllHealthy": { reason: "A healthy run carries health on the composite and plans but emits no unhealthy entries, and counts nothing.", - in: &dt.XRReport{Groups: []dt.XRDiffGroup{{ + args: args{xr: &dt.XRReport{Groups: []dt.XRDiffGroup{{ XR: xrRef, Diffs: diffs(live(rdiff(cmGVK, "cm", dt.DiffTypeModified, map[string]any{}, map[string]any{"data": "x"}), nil)), Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{{ObjectReference: cmRef("cm"), Health: healthy}}}, - }}}, + }}}}, want: want{ plans: map[string]*health.Health{"cm": healthy}, composites: []CompositeResult{{Ref: xrPlan, Status: CompositeChanged, Health: healthy}}, @@ -660,10 +670,10 @@ func TestHealth(t *testing.T) { }, "CreateHasNoHealth": { reason: "A created resource has no live object, so its plan carries no health; nor does a composite not in the cluster.", - in: &dt.XRReport{Groups: []dt.XRDiffGroup{{ + args: args{xr: &dt.XRReport{Groups: []dt.XRDiffGroup{{ XR: xrRef, Diffs: diffs(rdiff(cmGVK, "new", dt.DiffTypeAdded, nil, map[string]any{})), - }}}, + }}}}, want: want{ plans: map[string]*health.Health{"new": nil}, composites: []CompositeResult{{Ref: xrPlan, Status: CompositeChanged}}, @@ -671,7 +681,7 @@ func TestHealth(t *testing.T) { }, "PlannedAndUnplanned": { reason: "An unhealthy resource with a plan shows its health there; one without a plan, under a version the plan does not use either, is listed as unhealthy once.", - in: &dt.XRReport{Groups: []dt.XRDiffGroup{{ + args: args{xr: &dt.XRReport{Groups: []dt.XRDiffGroup{{ XR: xrRef, Diffs: diffs(live(rdiff(cmGVK, "cm", dt.DiffTypeRemoved, map[string]any{}, nil), cond("Ready", "False"))), Health: dt.CompositeHealth{XR: failing, Composed: []dt.ResourceHealth{ @@ -679,7 +689,7 @@ func TestHealth(t *testing.T) { {ObjectReference: cmRef("quiet"), Health: healthy}, {ObjectReference: bucketV1, Health: failing}, }}, - }}}, + }}}}, want: want{ plans: map[string]*health.Health{"cm": notReady}, composites: []CompositeResult{{ @@ -691,61 +701,68 @@ func TestHealth(t *testing.T) { }, "PlannedAcrossVersions": { reason: "A composed resource observed under another API version than its plan's is matched to the plan, not listed again.", - in: &dt.XRReport{Groups: []dt.XRDiffGroup{{ + args: args{xr: &dt.XRReport{Groups: []dt.XRDiffGroup{{ XR: xrRef, Diffs: diffs(live(rdiff(schema.FromAPIVersionAndKind(bucketV2.APIVersion, bucketV2.Kind), "b", dt.DiffTypeModified, map[string]any{}, map[string]any{"spec": "x"}), cond("Synced", "False"))), Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{{ObjectReference: bucketV1, Health: failing}}}, - }}}, + }}}}, want: want{ plans: map[string]*health.Health{"b": failing}, composites: []CompositeResult{{Ref: xrPlan, Status: CompositeChanged, Health: healthy}}, summary: HealthSummary{Failing: 1}, }, }, - "NestedCountedOnce": { - reason: "A nested composite that is its own input is counted as a composite, not again as a resource, and a resource two composites reach counts once.", - in: &dt.XRReport{Groups: []dt.XRDiffGroup{ - { - XR: xrRef, - Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{ - {ObjectReference: ref("example.org/v1", "XSubnet", "child"), Health: notReady}, - {ObjectReference: cmRef("deep"), Health: failing}, - }}, - }, - { - XR: ref("example.org/v1", "XSubnet", "child"), - Health: dt.CompositeHealth{XR: notReady, Composed: []dt.ResourceHealth{{ObjectReference: cmRef("deep"), Health: failing}}}, - }, - }}, + "NestedVia": { + reason: "A nested composite is listed as a resource of its top-level composite, and what it composes is listed there too, once each, with via naming it.", + args: args{xr: &dt.XRReport{Groups: []dt.XRDiffGroup{{ + XR: xrRef, + Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{ + {ObjectReference: child, Health: notReady}, + {ObjectReference: cmRef("deep"), Via: &child, Health: failing}, + }}, + }}}}, want: want{ plans: map[string]*health.Health{}, + composites: []CompositeResult{{Ref: xrPlan, Status: CompositeUnchanged, Health: healthy, Unhealthy: []UnhealthyResource{ + {Ref: resourceRef(child), Health: notReady}, + {Ref: cmPlan("deep"), Via: &childPlan, Health: failing}, + }}}, + summary: HealthSummary{Failing: 1, NotReady: 1}, + }, + }, + "CompImpactsCountedOnce": { + reason: "A composition run carries each impact's health; an XR two compositions reach is one composite, so it counts once, and so does what it composes.", + args: args{comp: &dt.CompDiffOutput{Compositions: []dt.CompositionDiff{ + {Name: "a", ImpactAnalysis: []dt.XRImpact{{ObjectReference: xrRef, Status: dt.XRStatusUnchanged, Health: unhealthyXR}}}, + {Name: "b", ImpactAnalysis: []dt.XRImpact{{ObjectReference: xrRef, Status: dt.XRStatusUnchanged, Health: unhealthyXR}}}, + }}}, + want: want{ + plans: map[string]*health.Health{"a": nil, "b": nil}, composites: []CompositeResult{ - {Ref: xrPlan, Status: CompositeUnchanged, Health: healthy, Unhealthy: []UnhealthyResource{ - {Ref: plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XSubnet", Name: "child"}, Health: notReady}, - {Ref: cmPlan("deep"), Health: failing}, - }}, - {Ref: plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XSubnet", Name: "child"}, Status: CompositeUnchanged, Health: notReady, Unhealthy: []UnhealthyResource{ - {Ref: cmPlan("deep"), Health: failing}, - }}, + {Ref: xrPlan, Composition: compRef("a"), Status: CompositeUnchanged, Health: failing, Unhealthy: []UnhealthyResource{{Ref: cmPlan("cm"), Health: notReady}}}, + {Ref: xrPlan, Composition: compRef("b"), Status: CompositeUnchanged, Health: failing, Unhealthy: []UnhealthyResource{{Ref: cmPlan("cm"), Health: notReady}}}, }, - summary: HealthSummary{Composites: 1, Failing: 1}, + summary: HealthSummary{Composites: 1, NotReady: 1}, }, }, } for name, tc := range cases { t.Run(name, func(t *testing.T) { - got := FromXRReport(tc.in, nil, nil) + got := FromXRReport(tc.args.xr, nil, nil) + if tc.args.comp != nil { + got = FromCompReport(tc.args.comp, nil, nil) + } gotPlans := map[string]*health.Health{} for _, p := range got.Plans { gotPlans[p.Name] = p.Health } if diff := cmp.Diff(tc.want.plans, gotPlans, cmpopts.EquateEmpty()); diff != "" { - t.Errorf("%s\nFromXRReport(...) plan health: -want, +got:\n%s", tc.reason, diff) + t.Errorf("%s\nFrom...Report(...) plan health: -want, +got:\n%s", tc.reason, diff) } if diff := cmp.Diff(tc.want.composites, got.Composites, cmpopts.EquateEmpty()); diff != "" { - t.Errorf("%s\nFromXRReport(...) composites: -want, +got:\n%s", tc.reason, diff) + t.Errorf("%s\nFrom...Report(...) composites: -want, +got:\n%s", tc.reason, diff) } if diff := cmp.Diff(tc.want.summary, got.Health()); diff != "" { t.Errorf("%s\nHealth(): -want, +got:\n%s", tc.reason, diff) diff --git a/internal/simulate/result.go b/internal/simulate/result.go index e686f07f..6ebbb31a 100644 --- a/internal/simulate/result.go +++ b/internal/simulate/result.go @@ -91,23 +91,25 @@ type CompositeResult struct { // from Status, the simulated outcome; nil when the cluster has no such // composite, or it was not simulated. Health *health.Health `json:"health,omitempty"` - // Unhealthy lists the composed resources, nested composites' included, - // that are live, not healthy, and have no plan in the run (so no health - // of their own to show). + // Unhealthy lists the composed resources, nested composites and theirs + // included, that are live, not healthy, and have no plan in the run (so + // no health of their own to show). Unhealthy []UnhealthyResource `json:"unhealthy,omitempty"` } // UnhealthyResource is a composed resource that is not healthy before apply. type UnhealthyResource struct { - Ref plan.ResourceRef `json:"ref"` - Health *health.Health `json:"health"` + Ref plan.ResourceRef `json:"ref"` + // Via is the nested composite that directly composes the resource; nil + // when the listing composite does. + Via *plan.ResourceRef `json:"via,omitempty"` + Health *health.Health `json:"health"` } -// HealthSummary counts what is not healthy before apply, serialized among -// the summary's other counts. Composites counts +// HealthSummary counts what is not healthy before apply. Composites counts // the composites whose own health is not healthy; Failing, NotReady and -// Paused count the other resources, each once however many composites or -// plans reach it. +// Paused count the other resources. Each is counted once however many +// composites or plans reach it. type HealthSummary struct { Composites int `json:"unhealthyComposites"` Failing int `json:"failing"` @@ -217,11 +219,14 @@ func (r Result) Health() HealthSummary { return composites[groupKind(ref)][[2]string{ref.Namespace, ref.Name}] } for _, c := range r.Composites { - gk := groupKind(c.Ref) + gk, id := groupKind(c.Ref), [2]string{c.Ref.Namespace, c.Ref.Name} + if composites[gk][id] { + continue + } if composites[gk] == nil { composites[gk] = map[[2]string]bool{} } - composites[gk][[2]string{c.Ref.Namespace, c.Ref.Name}] = true + composites[gk][id] = true if c.Health.Unhealthy() { s.Composites++ } @@ -268,16 +273,15 @@ func groupKind(ref plan.ResourceRef) schema.GroupKind { // MarshalJSON writes the result with summary, composites and compositions // ahead of the plans, which can be long, and with the deferred and health -// counts inside summary. YAML goes through it too. Decoding needs no +// counts inside summary (the health ones under summary.health). YAML goes through it too. Decoding needs no // counterpart: summary decodes into Result.Summary, Deferred is counted from // Composites, and Health from Composites and Plans. func (r Result) MarshalJSON() ([]byte, error) { type summary struct { plan.Summary - HealthSummary - - Deferred int `json:"deferred"` + Health HealthSummary `json:"health"` + Deferred int `json:"deferred"` } return json.Marshal(struct { FormatVersion string `json:"formatVersion"` @@ -292,7 +296,7 @@ func (r Result) MarshalJSON() ([]byte, error) { }{ FormatVersion: r.FormatVersion, Errored: r.Errored, - Summary: summary{Summary: r.Summary, HealthSummary: r.Health(), Deferred: r.Deferred()}, + Summary: summary{Summary: r.Summary, Health: r.Health(), Deferred: r.Deferred()}, Composites: r.Composites, Compositions: r.Compositions, Plans: r.Plans, diff --git a/internal/simulate/result_test.go b/internal/simulate/result_test.go index 7d9038fe..6f72031c 100644 --- a/internal/simulate/result_test.go +++ b/internal/simulate/result_test.go @@ -215,7 +215,8 @@ func TestRenderJSONProjectFields(t *testing.T) { } // The top-level keys keep summary, composites and compositions ahead of - // the plans, and summary carries the deferred count. + // the plans, and summary carries the deferred count. Summary is not a flat + // map of counts: the health counts nest under summary.health. dec := json.NewDecoder(&buf) var keys []string if _, err := dec.Token(); err != nil { @@ -232,12 +233,16 @@ func TestRenderJSONProjectFields(t *testing.T) { t.Fatalf("Render(json): cannot read value of %q: %v", k, err) } if k == "summary" { - var sum map[string]int + var sum struct { + Destroy int `json:"destroy"` + Deferred int `json:"deferred"` + Health map[string]int `json:"health"` + } if err := json.Unmarshal(v, &sum); err != nil { - t.Fatalf("Render(json): summary is not a map of counts: %v", err) + t.Fatalf("Render(json): summary does not hold counts: %v", err) } - if sum["deferred"] != 1 || sum["destroy"] != 1 { - t.Errorf("Render(json): summary: want destroy 1 and deferred 1, got %v", sum) + if sum.Deferred != 1 || sum.Destroy != 1 || sum.Health == nil { + t.Errorf("Render(json): summary: want destroy 1, deferred 1 and health counts, got %+v", sum) } } } @@ -307,6 +312,7 @@ func TestNewResult(t *testing.T) { func TestRenderJSONHealth(t *testing.T) { xr := plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XNetwork", Name: "prod"} + nested := plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XSubnet", Name: "a"} failing := &health.Health{State: health.Failing, Synced: &health.Condition{Status: "False", Reason: "ReconcileError", Message: "boom"}} type want struct { @@ -314,36 +320,43 @@ func TestRenderJSONHealth(t *testing.T) { plans string summary string } + type args struct { + in Result + } cases := map[string]struct { reason string - in Result + args args want want }{ "NoLiveObjects": { reason: "Without live objects no health or unhealthy key is written, and every health count is zero.", - in: NewResult( + args: args{in: NewResult( []*plan.ResourcePlan{{APIVersion: "v1", Kind: "ConfigMap", Name: "cm", Action: plan.ActionCreate, Composite: &xr}}, - []CompositeResult{{Ref: xr, Status: CompositeChanged}}, nil), + []CompositeResult{{Ref: xr, Status: CompositeChanged}}, nil)}, want: want{ composites: `[{"ref":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"status":"changed"}]`, plans: `[{"apiVersion":"v1","kind":"ConfigMap","name":"cm","action":"create","composite":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"}}]`, - summary: `{"create":1,"update":0,"destroy":0,"replace":0,"noop":0,"approximate":0,"errored":0,"unhealthyComposites":0,"failing":0,"notReady":0,"paused":0,"deferred":0}`, + summary: `{"create":1,"update":0,"destroy":0,"replace":0,"noop":0,"approximate":0,"errored":0,"health":{"unhealthyComposites":0,"failing":0,"notReady":0,"paused":0},"deferred":0}`, }, }, "Unhealthy": { - reason: "Composite and plan health, and the unhealthy list, are written under their keys with the conditions they came from.", - in: NewResult( + reason: "Composite and plan health, and the unhealthy list with each entry's via, are written under their keys with the conditions they came from.", + args: args{in: NewResult( []*plan.ResourcePlan{{APIVersion: "v1", Kind: "ConfigMap", Name: "cm", Action: plan.ActionNoOp, Composite: &xr, Health: &health.Health{State: health.Paused}}}, []CompositeResult{{ Ref: xr, Status: CompositeUnchanged, Health: failing, - Unhealthy: []UnhealthyResource{{Ref: plan.ResourceRef{APIVersion: "v1", Kind: "Secret", Name: "s"}, Health: &health.Health{State: health.NotReady, Ready: &health.Condition{Status: "False"}}}}, - }}, nil), + Unhealthy: []UnhealthyResource{ + {Ref: plan.ResourceRef{APIVersion: "v1", Kind: "Secret", Name: "s"}, Health: &health.Health{State: health.NotReady, Ready: &health.Condition{Status: "False"}}}, + {Ref: plan.ResourceRef{APIVersion: "v1", Kind: "Secret", Name: "t"}, Via: &nested, Health: &health.Health{State: health.Paused}}, + }, + }}, nil)}, want: want{ composites: `[{"ref":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"status":"unchanged",` + `"health":{"state":"failing","synced":{"status":"False","reason":"ReconcileError","message":"boom"}},` + - `"unhealthy":[{"ref":{"apiVersion":"v1","kind":"Secret","name":"s"},"health":{"state":"notReady","ready":{"status":"False"}}}]}]`, + `"unhealthy":[{"ref":{"apiVersion":"v1","kind":"Secret","name":"s"},"health":{"state":"notReady","ready":{"status":"False"}}},` + + `{"ref":{"apiVersion":"v1","kind":"Secret","name":"t"},"via":{"apiVersion":"example.org/v1","kind":"XSubnet","name":"a"},"health":{"state":"paused"}}]}]`, plans: `[{"apiVersion":"v1","kind":"ConfigMap","name":"cm","action":"no-op","composite":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"health":{"state":"paused"}}]`, - summary: `{"create":0,"update":0,"destroy":0,"replace":0,"noop":1,"approximate":0,"errored":0,"unhealthyComposites":1,"failing":0,"notReady":1,"paused":1,"deferred":0}`, + summary: `{"create":0,"update":0,"destroy":0,"replace":0,"noop":1,"approximate":0,"errored":0,"health":{"unhealthyComposites":1,"failing":0,"notReady":1,"paused":2},"deferred":0}`, }, }, } @@ -352,7 +365,7 @@ func TestRenderJSONHealth(t *testing.T) { t.Run(name, func(t *testing.T) { var buf bytes.Buffer r, _ := NewRenderer(plan.FormatJSON) - if err := r.Render(&buf, tc.in); err != nil { + if err := r.Render(&buf, tc.args.in); err != nil { t.Fatalf("%s\nRender(json): unexpected error: %v", tc.reason, err) } var top map[string]json.RawMessage @@ -374,7 +387,7 @@ func TestRenderJSONHealth(t *testing.T) { if err := json.Unmarshal(buf.Bytes(), &back); err != nil { t.Fatalf("%s\nRender(json): cannot decode: %v", tc.reason, err) } - if diff := cmp.Diff(tc.in, back); diff != "" { + if diff := cmp.Diff(tc.args.in, back); diff != "" { t.Errorf("%s\nRender(json) round trip: -want, +got:\n%s", tc.reason, diff) } }) From 4d137570c2560de241d9e3f6d28f3075c1258780 Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Wed, 18 Nov 2026 10:40:34 -0500 Subject: [PATCH 06/11] test(health): use args tables in the classifier tests Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/health/health_test.go | 42 +++++++++++++++++++--------------- 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/internal/health/health_test.go b/internal/health/health_test.go index f4db7064..136ff663 100644 --- a/internal/health/health_test.go +++ b/internal/health/health_test.go @@ -43,9 +43,12 @@ func TestOf(t *testing.T) { readyFalse := cond("Ready", "False", "Creating", "") readyTrue := cond("Ready", "True", "Available", "") + type args struct { + u *unstructured.Unstructured + } cases := map[string]struct { reason string - in *unstructured.Unstructured + args args want *Health }{ "NilObject": { @@ -54,12 +57,12 @@ func TestOf(t *testing.T) { }, "NoConditions": { reason: "An object with no Synced or Ready condition, such as a ConfigMap, is healthy.", - in: obj(""), + args: args{u: obj("")}, want: &Health{State: Healthy}, }, "SyncedAndReady": { reason: "Synced=True and Ready=True is healthy, carrying both conditions.", - in: obj("", syncedTrue, readyTrue), + args: args{u: obj("", syncedTrue, readyTrue)}, want: &Health{ State: Healthy, Synced: &Condition{Status: corev1.ConditionTrue, Reason: "ReconcileSuccess"}, @@ -68,7 +71,7 @@ func TestOf(t *testing.T) { }, "Unknown": { reason: "Unknown conditions are healthy.", - in: obj("", cond("Synced", "Unknown", "", ""), cond("Ready", "Unknown", "", "")), + args: args{u: obj("", cond("Synced", "Unknown", "", ""), cond("Ready", "Unknown", "", ""))}, want: &Health{ State: Healthy, Synced: &Condition{Status: corev1.ConditionUnknown}, @@ -77,7 +80,7 @@ func TestOf(t *testing.T) { }, "SyncedFalse": { reason: "Synced=False is failing, even when Ready=False too.", - in: obj("", syncedFalse, readyFalse), + args: args{u: obj("", syncedFalse, readyFalse)}, want: &Health{ State: Failing, Synced: &Condition{Status: corev1.ConditionFalse, Reason: "ReconcileError", Message: "cannot update: denied"}, @@ -86,7 +89,7 @@ func TestOf(t *testing.T) { }, "ReadyFalse": { reason: "Ready=False with Synced not False is not ready.", - in: obj("", syncedTrue, readyFalse), + args: args{u: obj("", syncedTrue, readyFalse)}, want: &Health{ State: NotReady, Synced: &Condition{Status: corev1.ConditionTrue, Reason: "ReconcileSuccess"}, @@ -95,12 +98,12 @@ func TestOf(t *testing.T) { }, "ReadyFalseOnly": { reason: "Ready=False with no Synced condition is not ready.", - in: obj("", readyFalse), + args: args{u: obj("", readyFalse)}, want: &Health{State: NotReady, Ready: &Condition{Status: corev1.ConditionFalse, Reason: "Creating"}}, }, "PausedOverridesFailing": { reason: "The paused annotation overrides Synced=False; the stale conditions are still reported.", - in: obj("true", syncedFalse), + args: args{u: obj("true", syncedFalse)}, want: &Health{ State: Paused, Synced: &Condition{Status: corev1.ConditionFalse, Reason: "ReconcileError", Message: "cannot update: denied"}, @@ -108,7 +111,7 @@ func TestOf(t *testing.T) { }, "PausedNotTrue": { reason: "Only the value \"true\" pauses an object.", - in: obj("false", syncedFalse), + args: args{u: obj("false", syncedFalse)}, want: &Health{ State: Failing, Synced: &Condition{Status: corev1.ConditionFalse, Reason: "ReconcileError", Message: "cannot update: denied"}, @@ -116,14 +119,14 @@ func TestOf(t *testing.T) { }, "MalformedStatus": { reason: "A status whose conditions cannot be read is treated as having none.", - in: &unstructured.Unstructured{Object: map[string]any{"status": map[string]any{"conditions": "nope"}}}, + args: args{u: &unstructured.Unstructured{Object: map[string]any{"status": map[string]any{"conditions": "nope"}}}}, want: &Health{State: Healthy}, }, } for name, tc := range cases { t.Run(name, func(t *testing.T) { - got := Of(tc.in) + got := Of(tc.args.u) if diff := cmp.Diff(tc.want, got); diff != "" { t.Errorf("%s\nOf(...): -want, +got:\n%s", tc.reason, diff) } @@ -132,21 +135,24 @@ func TestOf(t *testing.T) { } func TestUnhealthy(t *testing.T) { + type args struct { + h *Health + } cases := map[string]struct { reason string - in *Health + args args want bool }{ - "Nil": {reason: "No live object is not unhealthy.", in: nil, want: false}, - "Healthy": {reason: "Healthy is not unhealthy.", in: &Health{State: Healthy}, want: false}, - "Failing": {reason: "Failing is unhealthy.", in: &Health{State: Failing}, want: true}, - "NotReady": {reason: "Not ready is unhealthy.", in: &Health{State: NotReady}, want: true}, - "Paused": {reason: "Paused is unhealthy.", in: &Health{State: Paused}, want: true}, + "Nil": {reason: "No live object is not unhealthy.", args: args{h: nil}, want: false}, + "Healthy": {reason: "Healthy is not unhealthy.", args: args{h: &Health{State: Healthy}}, want: false}, + "Failing": {reason: "Failing is unhealthy.", args: args{h: &Health{State: Failing}}, want: true}, + "NotReady": {reason: "Not ready is unhealthy.", args: args{h: &Health{State: NotReady}}, want: true}, + "Paused": {reason: "Paused is unhealthy.", args: args{h: &Health{State: Paused}}, want: true}, } for name, tc := range cases { t.Run(name, func(t *testing.T) { - if got := tc.in.Unhealthy(); got != tc.want { + if got := tc.args.h.Unhealthy(); got != tc.want { t.Errorf("%s\nUnhealthy(): want %t, got %t", tc.reason, tc.want, got) } }) From ffc70db67197d8fca261ae297be56dcbf3484ada Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Wed, 18 Nov 2026 10:53:40 -0500 Subject: [PATCH 07/11] docs(simulate): reflow the MarshalJSON comment Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/simulate/result.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/internal/simulate/result.go b/internal/simulate/result.go index 6ebbb31a..adf0483a 100644 --- a/internal/simulate/result.go +++ b/internal/simulate/result.go @@ -273,9 +273,10 @@ func groupKind(ref plan.ResourceRef) schema.GroupKind { // MarshalJSON writes the result with summary, composites and compositions // ahead of the plans, which can be long, and with the deferred and health -// counts inside summary (the health ones under summary.health). YAML goes through it too. Decoding needs no -// counterpart: summary decodes into Result.Summary, Deferred is counted from -// Composites, and Health from Composites and Plans. +// counts inside summary (the health ones under summary.health). YAML goes +// through it too. Decoding needs no counterpart: summary decodes into +// Result.Summary, Deferred is counted from Composites, and Health from +// Composites and Plans. func (r Result) MarshalJSON() ([]byte, error) { type summary struct { plan.Summary From 601f3563e94abd65d50246471e2fc156938a7ade Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Wed, 18 Nov 2026 15:10:24 -0500 Subject: [PATCH 08/11] test(project): expect healthy composites in project simulate JSON PR 1 reports each composite's live health, so the project simulate integration cases now see Health: healthy on every composite. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- cmd/crossplane/project/integration_project_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cmd/crossplane/project/integration_project_test.go b/cmd/crossplane/project/integration_project_test.go index e1a2d3e9..b1283f23 100644 --- a/cmd/crossplane/project/integration_project_test.go +++ b/cmd/crossplane/project/integration_project_test.go @@ -29,6 +29,7 @@ import ( "github.com/google/go-cmp/cmp" dp "github.com/crossplane/cli/v2/internal/diff/diffprocessor" + "github.com/crossplane/cli/v2/internal/health" "github.com/crossplane/cli/v2/internal/plan" "github.com/crossplane/cli/v2/internal/simulate" "github.com/crossplane/cli/v2/internal/testutils/integration" @@ -71,7 +72,7 @@ func TestProjectSimulateIntegration(t *testing.T) { changed := func(refs ...plan.ResourceRef) []simulate.CompositeResult { out := make([]simulate.CompositeResult, 0, len(refs)) for _, r := range refs { - out = append(out, simulate.CompositeResult{Ref: r, Status: simulate.CompositeChanged, Composition: &comp}) + out = append(out, simulate.CompositeResult{Ref: r, Status: simulate.CompositeChanged, Composition: &comp, Health: &health.Health{State: health.Healthy}}) } return out } From 2ef649840428c0f40822fe590743ed93df43e5ba Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Wed, 18 Nov 2026 15:31:00 -0500 Subject: [PATCH 09/11] test(project): expect healthy composites in project plan output JSON Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- .../project/integration_plan_output_test.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/cmd/crossplane/project/integration_plan_output_test.go b/cmd/crossplane/project/integration_plan_output_test.go index 1c0d1e4f..657d89a2 100644 --- a/cmd/crossplane/project/integration_plan_output_test.go +++ b/cmd/crossplane/project/integration_plan_output_test.go @@ -32,6 +32,7 @@ import ( dp "github.com/crossplane/cli/v2/internal/diff/diffprocessor" "github.com/crossplane/cli/v2/internal/exitcode" + "github.com/crossplane/cli/v2/internal/health" "github.com/crossplane/cli/v2/internal/plan" "github.com/crossplane/cli/v2/internal/simulate" "github.com/crossplane/cli/v2/internal/testutils/integration" @@ -73,6 +74,8 @@ func TestSimulatePlanOutput(t *testing.T) { another := xnop another.Name = "another-resource" comp := plan.ResourceRef{APIVersion: "apiextensions.crossplane.io/v1", Kind: "Composition", Name: "xnopresources.diff.example.org"} + // healthy is a live composite's health with no failing condition. + healthy := &health.Health{State: health.Healthy} xrArgs := []string{"-f", "../../../internal/testutils/integration/testdata/diff/modified-xr.yaml"} compArgs := []string{"-f", "../../../internal/testutils/integration/testdata/comp/updated-composition.yaml", "--namespace=default"} @@ -140,7 +143,7 @@ Note: Provider plan not run: no provider diff server planned these resources. args: append([]string{"-o", "json"}, xrArgs...), wantResult: &planShape{ Summary: plan.Summary{Update: 2}, - Composites: []simulate.CompositeResult{{Ref: xnop, Status: simulate.CompositeChanged}}, + Composites: []simulate.CompositeResult{{Ref: xnop, Status: simulate.CompositeChanged, Health: healthy}}, Plans: []planEntry{ {Kind: "XDownstreamResource", Name: "test-resource", Action: plan.ActionUpdate, Composite: "test-resource"}, {Kind: "XNopResource", Name: "test-resource", Action: plan.ActionUpdate, Composite: "test-resource"}, @@ -184,7 +187,7 @@ Note: Provider plan not run: no provider diff server planned these resources. args: append([]string{"-o", "json"}, compArgs...), wantResult: &planShape{ Summary: plan.Summary{Update: 3, NoOp: 2}, - Composites: []simulate.CompositeResult{{Ref: another, Status: simulate.CompositeChanged, Composition: &comp}, {Ref: xnop, Status: simulate.CompositeChanged, Composition: &comp}}, + Composites: []simulate.CompositeResult{{Ref: another, Status: simulate.CompositeChanged, Composition: &comp, Health: healthy}, {Ref: xnop, Status: simulate.CompositeChanged, Composition: &comp, Health: healthy}}, Compositions: []simulate.CompositionResult{{ Ref: comp, RevisionImpact: &simulate.RevisionImpact{ChangeScope: "spec", CreatesRevision: true, RepointedComposites: 2}, @@ -203,7 +206,7 @@ Note: Provider plan not run: no provider diff server planned these resources. args: []string{"-o", "json", "-n", "default", "--name=another-resource", "--name=test-resource"}, wantResult: &planShape{ Summary: plan.Summary{Update: 3, NoOp: 2}, - Composites: []simulate.CompositeResult{{Ref: another, Status: simulate.CompositeChanged, Composition: &comp}, {Ref: xnop, Status: simulate.CompositeChanged, Composition: &comp}}, + Composites: []simulate.CompositeResult{{Ref: another, Status: simulate.CompositeChanged, Composition: &comp, Health: healthy}, {Ref: xnop, Status: simulate.CompositeChanged, Composition: &comp, Health: healthy}}, Compositions: []simulate.CompositionResult{{ Ref: comp, RevisionImpact: &simulate.RevisionImpact{ChangeScope: "spec", CreatesRevision: true, RepointedComposites: 2}, @@ -222,7 +225,7 @@ Note: Provider plan not run: no provider diff server planned these resources. args: []string{"-o", "json", "--name=default/test-resource"}, wantResult: &planShape{ Summary: plan.Summary{Update: 2, NoOp: 1}, - Composites: []simulate.CompositeResult{{Ref: xnop, Status: simulate.CompositeChanged, Composition: &comp}}, + Composites: []simulate.CompositeResult{{Ref: xnop, Status: simulate.CompositeChanged, Composition: &comp, Health: healthy}}, Compositions: []simulate.CompositionResult{{ Ref: comp, RevisionImpact: &simulate.RevisionImpact{ChangeScope: "spec", CreatesRevision: true, RepointedComposites: 1}, From 4ce9bb1f2d18c001397af089c6758fe00599a1db Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 19 Nov 2026 14:02:48 -0500 Subject: [PATCH 10/11] docs(simulate): use contractions in the output help Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/simulate/help/output.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/simulate/help/output.md b/internal/simulate/help/output.md index bcd9c413..f9bcabb6 100644 --- a/internal/simulate/help/output.md +++ b/internal/simulate/help/output.md @@ -22,12 +22,12 @@ The `-o` flag picks the output format: annotation, whatever its conditions), or `healthy`, with the `synced` and `ready` conditions it was read from. A claim's `health` is its backing composite resource's. A composite or plan has no `health` when there is no - live object, as for a create, or, for a composite, when it was not + live object, as for a create, or, for a composite, when it wasn't simulated (`error`, `skipped`, `deferred`). Each composite also lists under - `unhealthy` the composed resources that are not healthy and have no plan of + `unhealthy` the composed resources that aren't healthy and have no plan of their own, each once. That includes nested composites and what they compose; an entry a nested composite composes names it under `via`. `summary.health` - counts the composites that are not healthy (`unhealthyComposites`), and the + counts the composites that aren't healthy (`unhealthyComposites`), and the other resources that are `failing`, `notReady` or `paused`, each once. - `diff` prints a line diff of each changed resource's manifest. Every Secret value, and any value a provider marks sensitive, reads From a1a5d400354a6c9d303e40bd32ac0e5dd87a98f8 Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 19 Nov 2026 15:10:48 -0500 Subject: [PATCH 11/11] fix(simulate): list a nested composite's health on its own entry A composition run gives a nested composite of the diffed composition's type an entry of its own, now marked composedBy. Its parent's health also lists it and what it composes, so each of those appeared in two unhealthy lists. A nested composite with an entry and health of its own now shows its health there and lists what it composes itself; its parent lists neither. One whose entry has no health, because it wasn't simulated, stays listed under its parent and counts there as a resource. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/simulate/help/output.md | 10 +++++-- internal/simulate/report.go | 48 +++++++++++++++++++++++++++----- internal/simulate/report_test.go | 42 ++++++++++++++++++++++++++++ internal/simulate/result.go | 15 ++++++---- 4 files changed, 100 insertions(+), 15 deletions(-) diff --git a/internal/simulate/help/output.md b/internal/simulate/help/output.md index f9bcabb6..f1275ac9 100644 --- a/internal/simulate/help/output.md +++ b/internal/simulate/help/output.md @@ -26,9 +26,13 @@ The `-o` flag picks the output format: simulated (`error`, `skipped`, `deferred`). Each composite also lists under `unhealthy` the composed resources that aren't healthy and have no plan of their own, each once. That includes nested composites and what they compose; - an entry a nested composite composes names it under `via`. `summary.health` - counts the composites that aren't healthy (`unhealthyComposites`), and the - other resources that are `failing`, `notReady` or `paused`, each once. + an entry a nested composite composes names it under `via`. A nested + composite that has its own entry with `health` (one with `composedBy`) + shows its health there and lists what it composes, so its parent lists + neither. + `summary.health` counts the composites that aren't healthy + (`unhealthyComposites`), and the other resources that are `failing`, + `notReady` or `paused`, each once. - `diff` prints a line diff of each changed resource's manifest. Every Secret value, and any value a provider marks sensitive, reads `(sensitive value)`; a value the provider computes on apply reads diff --git a/internal/simulate/report.go b/internal/simulate/report.go index 2e978109..d742e935 100644 --- a/internal/simulate/report.go +++ b/internal/simulate/report.go @@ -254,20 +254,44 @@ func (a *assembler) addComposite(c CompositeResult, h dt.CompositeHealth) { // unhealthy sets each composite's Unhealthy: what it composed that is not // healthy and has no plan in the run, matched across API versions. A // resource with a plan shows its health there. +// +// A nested composite with an entry and health of its own, as a composition +// run gives one of a diffed composition's type, shows its health on that +// entry and lists what it composes itself; its parent lists neither. So a +// resource is listed under the most deeply nested composite entry that +// composes it, once. func (a *assembler) unhealthy() { - planned := map[schema.GroupKind]map[[2]string]bool{} + planned := map[objectID]bool{} for _, p := range a.plans { - gk := p.GroupVersionKind().GroupKind() - if planned[gk] == nil { - planned[gk] = map[[2]string]bool{} + planned[idOf(p.APIVersion, p.Kind, p.Namespace, p.Name)] = true + } + + composes := make([]map[objectID]bool, len(a.composed)) + entries := map[objectID][]int{} + for i, composed := range a.composed { + composes[i] = map[objectID]bool{} + for _, r := range composed { + composes[i][idOf(r.APIVersion, r.Kind, r.Namespace, r.Name)] = true + } + if c := a.composites[i]; c.Health != nil { + id := idOf(c.Ref.APIVersion, c.Ref.Kind, c.Ref.Namespace, c.Ref.Name) + entries[id] = append(entries[id], i) } - planned[gk][[2]string{p.Namespace, p.Name}] = true } for i, composed := range a.composed { + // What a nested composite entry lists, and the entry itself. + ownedElsewhere := map[objectID]bool{} + for id := range composes[i] { + for _, j := range entries[id] { + ownedElsewhere[id] = true + maps.Copy(ownedElsewhere, composes[j]) + } + } + for _, r := range composed { - gk := schema.FromAPIVersionAndKind(r.APIVersion, r.Kind).GroupKind() - if !r.Health.Unhealthy() || planned[gk][[2]string{r.Namespace, r.Name}] { + id := idOf(r.APIVersion, r.Kind, r.Namespace, r.Name) + if !r.Health.Unhealthy() || planned[id] || ownedElsewhere[id] { continue } u := UnhealthyResource{Ref: resourceRef(r.ObjectReference), Health: r.Health} @@ -280,6 +304,16 @@ func (a *assembler) unhealthy() { } } +// objectID is an object's identity across API versions. +type objectID struct { + gk schema.GroupKind + namespace, name string +} + +func idOf(apiVersion, kind, namespace, name string) objectID { + return objectID{gk: schema.FromAPIVersionAndKind(apiVersion, kind).GroupKind(), namespace: namespace, name: name} +} + // addDiffs adds a plan per diff, in the structured renderer's canonical order. // It reports whether a provider plan changed any of them, which the engine's // verdict alone does not show. diff --git a/internal/simulate/report_test.go b/internal/simulate/report_test.go index 257acf50..0bc24cec 100644 --- a/internal/simulate/report_test.go +++ b/internal/simulate/report_test.go @@ -731,6 +731,48 @@ func TestHealth(t *testing.T) { summary: HealthSummary{Failing: 1, NotReady: 1}, }, }, + "NestedEntryListsItsOwn": { + reason: "A nested composite with an impact and health of its own shows its health there and lists what it composes; its parent lists neither, and the summary counts each once.", + args: args{comp: &dt.CompDiffOutput{Compositions: []dt.CompositionDiff{{Name: "a", ImpactAnalysis: []dt.XRImpact{ + {ObjectReference: xrRef, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{ + {ObjectReference: child, Health: notReady}, + {ObjectReference: cmRef("deep"), Via: &child, Health: failing}, + {ObjectReference: cmRef("cm"), Health: failing}, + }}}, + {ObjectReference: child, ComposedBy: &xrRef, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: notReady, Composed: []dt.ResourceHealth{ + {ObjectReference: cmRef("deep"), Health: failing}, + }}}, + }}}}}, + want: want{ + plans: map[string]*health.Health{"a": nil}, + composites: []CompositeResult{ + {Ref: xrPlan, Composition: compRef("a"), Status: CompositeUnchanged, Health: healthy, Unhealthy: []UnhealthyResource{{Ref: cmPlan("cm"), Health: failing}}}, + {Ref: childPlan, Composition: compRef("a"), ComposedBy: &xrPlan, Status: CompositeUnchanged, Health: notReady, Unhealthy: []UnhealthyResource{{Ref: cmPlan("deep"), Health: failing}}}, + }, + summary: HealthSummary{Composites: 1, Failing: 2}, + }, + }, + "NestedEntryWithoutHealth": { + reason: "A nested composite whose own impact has no health, as when it errored, is listed under its parent with what it composes, and counted there as a resource.", + args: args{comp: &dt.CompDiffOutput{Compositions: []dt.CompositionDiff{{Name: "a", ImpactAnalysis: []dt.XRImpact{ + {ObjectReference: xrRef, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{ + {ObjectReference: child, Health: notReady}, + {ObjectReference: cmRef("deep"), Via: &child, Health: failing}, + }}}, + {ObjectReference: child, ComposedBy: &xrRef, Status: dt.XRStatusError}, + }}}}}, + want: want{ + plans: map[string]*health.Health{"a": nil}, + composites: []CompositeResult{ + {Ref: xrPlan, Composition: compRef("a"), Status: CompositeUnchanged, Health: healthy, Unhealthy: []UnhealthyResource{ + {Ref: childPlan, Health: notReady}, + {Ref: cmPlan("deep"), Via: &childPlan, Health: failing}, + }}, + {Ref: childPlan, Composition: compRef("a"), ComposedBy: &xrPlan, Status: CompositeError}, + }, + summary: HealthSummary{Failing: 1, NotReady: 1}, + }, + }, "CompImpactsCountedOnce": { reason: "A composition run carries each impact's health; an XR two compositions reach is one composite, so it counts once, and so does what it composes.", args: args{comp: &dt.CompDiffOutput{Compositions: []dt.CompositionDiff{ diff --git a/internal/simulate/result.go b/internal/simulate/result.go index adf0483a..8ae6f792 100644 --- a/internal/simulate/result.go +++ b/internal/simulate/result.go @@ -93,7 +93,9 @@ type CompositeResult struct { Health *health.Health `json:"health,omitempty"` // Unhealthy lists the composed resources, nested composites and theirs // included, that are live, not healthy, and have no plan in the run (so - // no health of their own to show). + // no health of their own to show). A nested composite with an entry and + // health of its own lists what it composes there instead, and its + // parent lists neither it nor that. Unhealthy []UnhealthyResource `json:"unhealthy,omitempty"` } @@ -107,9 +109,10 @@ type UnhealthyResource struct { } // HealthSummary counts what is not healthy before apply. Composites counts -// the composites whose own health is not healthy; Failing, NotReady and -// Paused count the other resources. Each is counted once however many -// composites or plans reach it. +// the composite entries whose own health is not healthy; Failing, NotReady +// and Paused count the other resources, a nested composite without health of +// its own on an entry included. Each is counted once however many composites +// or plans reach it. type HealthSummary struct { Composites int `json:"unhealthyComposites"` Failing int `json:"failing"` @@ -220,7 +223,9 @@ func (r Result) Health() HealthSummary { } for _, c := range r.Composites { gk, id := groupKind(c.Ref), [2]string{c.Ref.Namespace, c.Ref.Name} - if composites[gk][id] { + // A composite with no health of its own here (one not simulated) is + // counted as a resource where its parent lists it, if anywhere. + if c.Health == nil || composites[gk][id] { continue } if composites[gk] == nil {