From 78ce67497e19eddc1bc447dbfe419f3c50d53118 Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 3 Dec 2026 13:42:53 -0500 Subject: [PATCH 01/16] test(health): add health builders Add a HealthBuilder in internal/health/healthtest for *health.Health, for the health ownership tests that follow. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/diff/testutils/mock_builder.go | 9 +++-- internal/health/healthtest/builder.go | 51 +++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 4 deletions(-) create mode 100644 internal/health/healthtest/builder.go diff --git a/internal/diff/testutils/mock_builder.go b/internal/diff/testutils/mock_builder.go index 77893058b..d26013dc3 100644 --- a/internal/diff/testutils/mock_builder.go +++ b/internal/diff/testutils/mock_builder.go @@ -32,9 +32,10 @@ import ( ) const ( - fieldSpec = "spec" - jsonTypeObject = "object" - jsonTypeString = "string" + fieldSpec = "spec" + apiExtensionsV1 = "apiextensions.crossplane.io/v1" + jsonTypeObject = "object" + jsonTypeString = "string" ) // MockBuilder provides a fluent API for building mock objects used in testing. @@ -1451,7 +1452,7 @@ func (b *ResourceBuilder) WithCompositionRevisionSelector(apiGroup string, match // v2 XRs nest crossplane spec fields under spec.crossplane; v1 keeps them under spec. path := []string{fieldSpec, "compositionRevisionSelector"} - if apiGroup != "apiextensions.crossplane.io/v1" { + if apiGroup != apiExtensionsV1 { path = []string{fieldSpec, "crossplane", "compositionRevisionSelector"} } diff --git a/internal/health/healthtest/builder.go b/internal/health/healthtest/builder.go new file mode 100644 index 000000000..703293ca4 --- /dev/null +++ b/internal/health/healthtest/builder.go @@ -0,0 +1,51 @@ +/* +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 healthtest provides builders for health values in tests. +package healthtest + +import ( + corev1 "k8s.io/api/core/v1" + + "github.com/crossplane/cli/v2/internal/health" +) + +// HealthBuilder helps construct a *health.Health for tests. +type HealthBuilder struct { + health *health.Health +} + +// NewHealth creates a new HealthBuilder in the given state, with no conditions. +func NewHealth(state health.State) *HealthBuilder { + return &HealthBuilder{health: &health.Health{State: state}} +} + +// WithSynced sets the Synced condition. +func (b *HealthBuilder) WithSynced(status corev1.ConditionStatus, reason, message string) *HealthBuilder { + b.health.Synced = &health.Condition{Status: status, Reason: reason, Message: message} + return b +} + +// WithReady sets the Ready condition. +func (b *HealthBuilder) WithReady(status corev1.ConditionStatus, reason, message string) *HealthBuilder { + b.health.Ready = &health.Condition{Status: status, Reason: reason, Message: message} + return b +} + +// Build returns the built health. +func (b *HealthBuilder) Build() *health.Health { + return b.health +} From 309e1556ec9ff3b62483a23b4885bed1bd4001ed Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 3 Dec 2026 13:44:26 -0500 Subject: [PATCH 02/16] test(health): cover Key and ownership resolution Pin today's behaviour of Key and OwnedElsewhere before the health model refactor. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/health/format_test.go | 122 +++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) diff --git a/internal/health/format_test.go b/internal/health/format_test.go index 3d44d86fc..8e3c2ac66 100644 --- a/internal/health/format_test.go +++ b/internal/health/format_test.go @@ -368,3 +368,125 @@ func TestSummaryLine(t *testing.T) { }) } } + +func TestKey(t *testing.T) { + type args struct { + apiVersion, kind, namespace, name string + } + cases := map[string]struct { + reason string + args args + want string + }{ + "CoreGroup": { + reason: "A core group resource's key is just its kind, namespace and name.", + args: args{apiVersion: "v1", kind: "ConfigMap", namespace: "ns", name: "cm"}, + want: "ConfigMap/ns/cm", + }, + "NamedGroup": { + reason: "A named group resource's key includes its group after the kind.", + args: args{apiVersion: "example.org/v1", kind: "XBucket", namespace: "ns", name: "b"}, + want: "XBucket.example.org/ns/b", + }, + "VersionIgnored": { + reason: "Another version of the same kind gives the same key.", + args: args{apiVersion: "example.org/v2", kind: "XBucket", namespace: "ns", name: "b"}, + want: "XBucket.example.org/ns/b", + }, + "ClusterScoped": { + reason: "A cluster-scoped resource's key has an empty namespace.", + args: args{apiVersion: "example.org/v1", kind: "XBucket", name: "b"}, + want: "XBucket.example.org//b", + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + got := Key(tc.args.apiVersion, tc.args.kind, tc.args.namespace, tc.args.name) + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("\n%s\nKey(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} + +func TestOwnedElsewhere(t *testing.T) { + type args struct { + entries []Entry + } + cases := map[string]struct { + reason string + args args + want []map[string]bool + }{ + "Single": { + reason: "A lone entry lists everything it composes.", + args: args{entries: []Entry{{Key: "a", HasHealth: true, Composes: []string{"r"}}}}, + want: []map[string]bool{{}}, + }, + "ChildWithHealth": { + reason: "A parent doesn't list a child with health, nor what the child composes.", + args: args{entries: []Entry{ + {Key: "a", HasHealth: true, Composes: []string{"b", "r1"}}, + {Key: "b", HasHealth: true, Composes: []string{"r2"}}, + }}, + want: []map[string]bool{{"b": true, "r2": true}, {}}, + }, + "ChildWithoutHealth": { + reason: "A child without health stays listed by its parent, with what it composes.", + args: args{entries: []Entry{ + {Key: "a", HasHealth: true, Composes: []string{"b"}}, + {Key: "b", Composes: []string{"r"}}, + }}, + want: []map[string]bool{{}, {}}, + }, + "ThreeLevels": { + reason: "Each entry drops its child and the child's direct compositions only, not the grandchild's.", + args: args{entries: []Entry{ + {Key: "a", HasHealth: true, Composes: []string{"b"}}, + {Key: "b", HasHealth: true, Composes: []string{"c"}}, + {Key: "c", HasHealth: true, Composes: []string{"r"}}, + }}, + want: []map[string]bool{{"b": true, "c": true}, {"c": true, "r": true}, {}}, + }, + "MiddleHasNoEntry": { + reason: "With no entry for the middle level, the top lists it and the bottom entry is owned by nobody.", + args: args{entries: []Entry{ + {Key: "a", HasHealth: true, Composes: []string{"b"}}, + {Key: "c", HasHealth: true, Composes: []string{"r"}}, + }}, + want: []map[string]bool{{}, {}}, + }, + "DuplicateKeys": { + reason: "Entries sharing a key with health have their compositions merged.", + args: args{entries: []Entry{ + {Key: "a", HasHealth: true, Composes: []string{"b"}}, + {Key: "b", HasHealth: true, Composes: []string{"r1"}}, + {Key: "b", HasHealth: true, Composes: []string{"r2"}}, + }}, + want: []map[string]bool{{"b": true, "r1": true, "r2": true}, {}, {}}, + }, + "ComposesItself": { + reason: "An entry that composes itself drops itself and everything it composes.", + args: args{entries: []Entry{{Key: "a", HasHealth: true, Composes: []string{"a", "r"}}}}, + want: []map[string]bool{{"a": true, "r": true}}, + }, + "OrderIndependent": { + reason: "The child listed before its parent gives the same result, by position.", + args: args{entries: []Entry{ + {Key: "b", HasHealth: true, Composes: []string{"r2"}}, + {Key: "a", HasHealth: true, Composes: []string{"b", "r1"}}, + }}, + want: []map[string]bool{{}, {"b": true, "r2": true}}, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + got := OwnedElsewhere(tc.args.entries) + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("\n%s\nOwnedElsewhere(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} From a724d8a976ac872d1389580676552fdf7fcdf140 Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 3 Dec 2026 13:46:32 -0500 Subject: [PATCH 03/16] test(renderer): pin nested-XR health ownership in xr diff output Add TestRenderDiffsHealth cases for 2- and 3-level nesting in flat and grouped layouts, a nested input XR without health, and an unchanged diff counted in the Health: line. Composed health is flattened with Via set, as RenderedResources.Merge builds it. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/diff/renderer/health_test.go | 159 ++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) diff --git a/internal/diff/renderer/health_test.go b/internal/diff/renderer/health_test.go index 845a936c1..01bc81a98 100644 --- a/internal/diff/renderer/health_test.go +++ b/internal/diff/renderer/health_test.go @@ -27,6 +27,14 @@ func liveWith(d *dt.ResourceDiff, msg string) *dt.ResourceDiff { return d } +// equalDiffFor returns modifiedDiffFor's diff marked unchanged. +func equalDiffFor(kind, name string) *dt.ResourceDiff { + d := modifiedDiffFor(kind, name) + d.DiffType = dt.DiffTypeEqual + + return d +} + func TestRenderDiffsHealth(t *testing.T) { failing := &health.Health{State: health.Failing, Synced: &health.Condition{Status: "False", Reason: "ReconcileError", Message: "vpc does not exist"}} notReady := &health.Health{State: health.NotReady, Ready: &health.Condition{Status: "False", Reason: "Creating"}} @@ -195,6 +203,157 @@ Health: 1 resource failing (Synced=False). Summary: 2 modified Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False). +`, + }, + "FlatNested": { + reason: "A single XR's composed health holds the nested XR and what it composes, flattened with Via set; the nested XR is listed and its resource nests under it. With no diffs, the XR: line is followed by two blank lines (its own and the trailer separator).", + args: args{groups: []dt.XRDiffGroup{group("a", notReady, []dt.ResourceHealth{ + {ObjectReference: ref("XNetwork", "b"), Health: notReady}, + {ObjectReference: ref("RouteTable", "rt"), Via: new(ref("XNetwork", "b")), Health: failing}, + })}}, + want: `XR: XNetwork/a ⚠ not ready (Ready=False, Creating) + + +Unhealthy resources without changes: + XNetwork/b ⚠ not ready (Ready=False, Creating) + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False), 1 not ready. +`, + }, + "FlatNestedThreeLevels": { + reason: "A single XR over a 3-level chain A > B > C lists every level, each resource nested under the XR that composes it.", + args: args{groups: []dt.XRDiffGroup{group("a", notReady, []dt.ResourceHealth{ + {ObjectReference: ref("XNetwork", "b"), Health: notReady}, + {ObjectReference: ref("XNetwork", "c"), Via: new(ref("XNetwork", "b")), Health: notReady}, + {ObjectReference: ref("RouteTable", "rt"), Via: new(ref("XNetwork", "b")), Health: failing}, + {ObjectReference: ref("Subnet", "sn"), Via: new(ref("XNetwork", "c")), Health: failing}, + })}}, + want: `XR: XNetwork/a ⚠ not ready (Ready=False, Creating) + + +Unhealthy resources without changes: + XNetwork/b ⚠ not ready (Ready=False, Creating) + XNetwork/c ⚠ not ready (Ready=False, Creating) + Subnet/sn ⚠ failing (Synced=False, ReconcileError): vpc does not exist + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +Health: 1 of 1 XR unhealthy before apply; 2 resources failing (Synced=False), 2 not ready. +`, + }, + "GroupedNested": { + reason: "A parent with health of its own and a nested input XR with health: the parent lists only its own resource, the nested XR lists what it composes.", + args: args{groups: []dt.XRDiffGroup{ + group("a", notReady, []dt.ResourceHealth{ + {ObjectReference: ref("Bucket", "bk"), Health: failing}, + {ObjectReference: ref("XNetwork", "b"), Health: notReady}, + {ObjectReference: ref("RouteTable", "rt"), Via: new(ref("XNetwork", "b")), Health: failing}, + }), + group("b", notReady, []dt.ResourceHealth{{ObjectReference: ref("RouteTable", "rt"), Health: failing}}), + }}, + want: `=== XNetwork/a === + +⚠ not ready (Ready=False, Creating) + +No changes. + +Unhealthy resources without changes: + Bucket/bk ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +=== XNetwork/b === + +⚠ not ready (Ready=False, Creating) + +No changes. + +Unhealthy resources without changes: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +================================================================================ +Total: no changes across 2 XRs (2 unchanged) +Health: 2 of 2 XRs unhealthy before apply; 2 resources failing (Synced=False). +`, + }, + "GroupedNestedThreeLevels": { + reason: "A 3-level chain A > B > C, all inputs with health: each resource is listed once, under the deepest XR that composes it.", + args: args{groups: []dt.XRDiffGroup{ + group("a", notReady, []dt.ResourceHealth{ + {ObjectReference: ref("XNetwork", "b"), Health: notReady}, + {ObjectReference: ref("XNetwork", "c"), Via: new(ref("XNetwork", "b")), Health: notReady}, + {ObjectReference: ref("RouteTable", "rt"), Via: new(ref("XNetwork", "b")), Health: failing}, + {ObjectReference: ref("Subnet", "sn"), Via: new(ref("XNetwork", "c")), Health: failing}, + }), + group("b", notReady, []dt.ResourceHealth{ + {ObjectReference: ref("XNetwork", "c"), Health: notReady}, + {ObjectReference: ref("RouteTable", "rt"), Health: failing}, + {ObjectReference: ref("Subnet", "sn"), Via: new(ref("XNetwork", "c")), Health: failing}, + }), + group("c", notReady, []dt.ResourceHealth{{ObjectReference: ref("Subnet", "sn"), Health: failing}}), + }}, + want: `=== XNetwork/a === + +⚠ not ready (Ready=False, Creating) + +No changes. + +=== XNetwork/b === + +⚠ not ready (Ready=False, Creating) + +No changes. + +Unhealthy resources without changes: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +=== XNetwork/c === + +⚠ not ready (Ready=False, Creating) + +No changes. + +Unhealthy resources without changes: + Subnet/sn ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +================================================================================ +Total: no changes across 3 XRs (3 unchanged) +Health: 3 of 3 XRs unhealthy before apply; 2 resources failing (Synced=False). +`, + }, + "GroupedNestedWithoutHealth": { + reason: "A nested input XR without health is not owned elsewhere, so its parent lists it and what it composes; the nested XR lists RouteTable/rt too, so it prints twice, but counts once.", + args: args{groups: []dt.XRDiffGroup{ + group("a", notReady, []dt.ResourceHealth{ + {ObjectReference: ref("XNetwork", "b"), Health: failing}, + {ObjectReference: ref("RouteTable", "rt"), Via: new(ref("XNetwork", "b")), Health: failing}, + }), + group("b", nil, []dt.ResourceHealth{{ObjectReference: ref("RouteTable", "rt"), Health: failing}}), + }}, + want: `=== XNetwork/a === + +⚠ not ready (Ready=False, Creating) + +No changes. + +Unhealthy resources without changes: + XNetwork/b ⚠ failing (Synced=False, ReconcileError): vpc does not exist + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +=== XNetwork/b === + +No changes. + +Unhealthy resources without changes: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): vpc does not exist + +================================================================================ +Total: no changes across 2 XRs (2 unchanged) +Health: 1 of 1 XR unhealthy before apply; 2 resources failing (Synced=False). +`, + }, + "EqualDiffCounted": { + reason: "An unchanged diff with health prints nothing of its own but counts in the Health: line.", + args: args{groups: []dt.XRDiffGroup{group("net", nil, nil, liveWith(equalDiffFor("Bucket", "b"), "vpc does not exist"))}}, + want: `Health: 1 resource failing (Synced=False). `, }, } From 6f3942b47d253e548319e997a41f136848344c9a Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 3 Dec 2026 13:48:31 -0500 Subject: [PATCH 04/16] test(renderer): pin nested-XR health ownership in composition diff output Add TestRenderCompDiffHealth cases for 2- and 3-level nesting, truncated and full messages, a nested XR shared across compositions, the changed XR's repeated message, and a filtered impact. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/diff/renderer/health_test.go | 277 +++++++++++++++++++++++++- 1 file changed, 276 insertions(+), 1 deletion(-) diff --git a/internal/diff/renderer/health_test.go b/internal/diff/renderer/health_test.go index 01bc81a98..975d15e86 100644 --- a/internal/diff/renderer/health_test.go +++ b/internal/diff/renderer/health_test.go @@ -2,6 +2,7 @@ package renderer import ( "bytes" + "strings" "testing" "github.com/google/go-cmp/cmp" @@ -388,8 +389,21 @@ func TestRenderCompDiffHealth(t *testing.T) { c := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XBucket", Name: "c"} sn := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "Subnet", Name: "sn"} + q := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XBucket", Name: "q"} + long := strings.Repeat("abcdefghi ", 15) + // Expected output is built from long so no literal repeated words sit in the source. + cut := long[:119] + "…" + wrap1 := strings.TrimSpace(long[:100]) + wrap2 := strings.TrimSpace(long[100:]) + failingLong := &health.Health{State: health.Failing, Synced: &health.Condition{Status: "False", Reason: "ReconcileError", Message: long}} + type args struct { impacts []dt.XRImpact + // other, when set, is a second composition's impacts, rendered after the first. + other []dt.XRImpact + // affected, when set, replaces the first composition's default summary of 2 unchanged. + affected *dt.AffectedResourcesSummary + full bool } cases := map[string]struct { reason string @@ -502,6 +516,254 @@ XR: XBucket/p XBucket/c ⚠ failing (Synced=False, ReconcileError): boom Health: 1 resource failing (Synced=False). +`, + }, + "NestedTwoLevels": { + reason: "A healthy parent's flattened composed list holds the nested XR and what it composes, with Via set; the nested XR, listed with health of its own, lists its resource and the parent lists nothing.", + args: args{impacts: []dt.XRImpact{ + {ObjectReference: p, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{ + {ObjectReference: c, Health: notReady}, + {ObjectReference: rt, Via: &c, Health: failing}, + }}}, + {ObjectReference: c, Status: dt.XRStatusUnchanged, ComposedBy: &p, Health: dt.CompositeHealth{XR: notReady, Composed: []dt.ResourceHealth{ + {ObjectReference: rt, Health: failing}, + }}}, + }}, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ✓ XBucket/p (cluster-scoped) + ✓ XBucket/c (cluster-scoped) ⚠ not ready (Ready=False, Creating) + +Summary: 2 resources unchanged + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XBucket/c + Unhealthy resources without changes: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): boom + +Health: 1 of 2 XRs unhealthy before apply; 1 resource failing (Synced=False). +`, + }, + "NestedThreeLevels": { + reason: "Over a 3-level chain p > c > q, each resource is listed once, under the most deeply nested XR that composes it.", + args: args{impacts: []dt.XRImpact{ + {ObjectReference: p, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{ + {ObjectReference: c, Health: notReady}, + {ObjectReference: q, Via: &c, Health: notReady}, + {ObjectReference: rt, Via: &c, Health: failing}, + {ObjectReference: sn, Via: &q, Health: failing}, + }}}, + {ObjectReference: c, Status: dt.XRStatusUnchanged, ComposedBy: &p, Health: dt.CompositeHealth{XR: notReady, Composed: []dt.ResourceHealth{ + {ObjectReference: q, Health: notReady}, + {ObjectReference: rt, Health: failing}, + {ObjectReference: sn, Via: &q, Health: failing}, + }}}, + {ObjectReference: q, Status: dt.XRStatusUnchanged, ComposedBy: &c, Health: dt.CompositeHealth{XR: notReady, Composed: []dt.ResourceHealth{ + {ObjectReference: sn, Health: failing}, + }}}, + }}, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ✓ XBucket/p (cluster-scoped) + ✓ XBucket/c (cluster-scoped) ⚠ not ready (Ready=False, Creating) + ✓ XBucket/q (cluster-scoped) ⚠ not ready (Ready=False, Creating) + +Summary: 2 resources unchanged + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XBucket/c + Unhealthy resources without changes: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): boom + +XR: XBucket/q + Unhealthy resources without changes: + Subnet/sn ⚠ failing (Synced=False, ReconcileError): boom + +Health: 2 of 3 XRs unhealthy before apply; 2 resources failing (Synced=False). +`, + }, + "TruncatedMessage": { + reason: "Without --full-messages, a long message is cut to 119 runes plus an ellipsis on the affected line and in the block.", + args: args{impacts: []dt.XRImpact{ + {ObjectReference: p, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: failingLong, Composed: []dt.ResourceHealth{{ObjectReference: rt, Health: failingLong}}}}, + }}, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ✓ XBucket/p (cluster-scoped) ⚠ failing (Synced=False, ReconcileError): ` + cut + ` + +Summary: 2 resources unchanged + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XBucket/p + Unhealthy resources without changes: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): ` + cut + ` + +Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False). +`, + }, + "FullMessages": { + reason: "With --full-messages, a long message prints in full beneath its line, wrapped at 100 runes, on the affected line and in the block.", + args: args{full: true, impacts: []dt.XRImpact{ + {ObjectReference: p, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: failingLong, Composed: []dt.ResourceHealth{{ObjectReference: rt, Health: failingLong}}}}, + }}, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ✓ XBucket/p (cluster-scoped) ⚠ failing (Synced=False, ReconcileError) + ` + wrap1 + ` + ` + wrap2 + ` + +Summary: 2 resources unchanged + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XBucket/p + Unhealthy resources without changes: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError) + ` + wrap1 + ` + ` + wrap2 + ` + +Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False). +`, + }, + "SharedAcrossCompositions": { + reason: "A nested XR listed under a second composition still owns its resources: the parent under the first composition skips it, and the Health: line counts it once.", + args: args{ + impacts: []dt.XRImpact{ + {ObjectReference: p, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: healthy, Composed: []dt.ResourceHealth{ + {ObjectReference: c, Health: notReady}, + {ObjectReference: rt, Via: &c, Health: failing}, + }}}, + }, + other: []dt.XRImpact{ + {ObjectReference: c, Status: dt.XRStatusUnchanged, ComposedBy: &p, Health: dt.CompositeHealth{XR: notReady, Composed: []dt.ResourceHealth{ + {ObjectReference: rt, Health: failing}, + }}}, + }, + }, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ✓ XBucket/p (cluster-scoped) + +Summary: 2 resources unchanged + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + + +================================================================================ + +=== Composition Changes === + +No changes detected in composition xnetworks.example.org + +=== Affected Composite Resources === + + ✓ XBucket/c (cluster-scoped) ⚠ not ready (Ready=False, Creating) + +Summary: 1 resource unchanged + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XBucket/c + Unhealthy resources without changes: + RouteTable/rt ⚠ failing (Synced=False, ReconcileError): boom + +Health: 1 of 2 XRs unhealthy before apply; 1 resource failing (Synced=False). +`, + }, + "ChangedXRMessageRepeats": { + reason: "A changed unhealthy XR's message prints on its affected line and again in its own diff header. Kept for now by decision; a follow-up will print it once.", + args: args{affected: &dt.AffectedResourcesSummary{Total: 1, WithChanges: 1}, impacts: []dt.XRImpact{ + { + ObjectReference: p, Status: dt.XRStatusChanged, + Health: dt.CompositeHealth{XR: failing}, + Diffs: map[string]*dt.ResourceDiff{"p": liveWith(modifiedDiffFor("XBucket", "p"), "boom")}, + }, + }}, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ⚠ XBucket/p (cluster-scoped) ⚠ failing (Synced=False, ReconcileError): boom + +Summary: 1 resource with changes + +=== Impact Analysis === + +~~~ XBucket/p ⚠ failing (Synced=False, ReconcileError): boom +- spec: +- field: old ++ spec: ++ field: new + +--- + +Summary: 1 modified + +Health: 1 of 1 XR unhealthy before apply. +`, + }, + "FilteredImpact": { + reason: "A filtered impact has no health and no diffs; it adds nothing to the blocks or the Health: line.", + args: args{impacts: []dt.XRImpact{ + {ObjectReference: p, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: failing, Composed: []dt.ResourceHealth{{ObjectReference: rt, Health: notReady}}}}, + {ObjectReference: c, Status: dt.XRStatusFiltered}, + }}, + want: `=== Composition Changes === + +No changes detected in composition xbuckets.example.org + +=== Affected Composite Resources === + + ✓ XBucket/p (cluster-scoped) ⚠ failing (Synced=False, ReconcileError): boom + +Summary: 2 resources unchanged + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XBucket/p + Unhealthy resources without changes: + RouteTable/rt ⚠ not ready (Ready=False, Creating) + +Health: 1 of 1 XR unhealthy before apply; 1 resource not ready. `, }, } @@ -514,6 +776,7 @@ Health: 1 resource failing (Synced=False). opts.Stdout = &stdout opts.Stderr = &bytes.Buffer{} opts.UseColors = false + opts.FullMessages = tc.args.full r := NewDefaultCompDiffRenderer(tu.TestLogger(t, false), NewDiffRenderer(tu.TestLogger(t, false), opts), opts) comp := dt.CompositionDiff{ @@ -521,8 +784,20 @@ Health: 1 resource failing (Synced=False). AffectedResources: dt.AffectedResourcesSummary{Total: 2, Unchanged: 2}, ImpactAnalysis: tc.args.impacts, } + if tc.args.affected != nil { + comp.AffectedResources = *tc.args.affected + } + + comps := []dt.CompositionDiff{comp} + if tc.args.other != nil { + comps = append(comps, dt.CompositionDiff{ + Name: "xnetworks.example.org", + AffectedResources: dt.AffectedResourcesSummary{Total: 1, Unchanged: 1}, + ImpactAnalysis: tc.args.other, + }) + } - if err := r.RenderCompDiff(&dt.CompDiffOutput{Compositions: []dt.CompositionDiff{comp}}); err != nil { + if err := r.RenderCompDiff(&dt.CompDiffOutput{Compositions: comps}); err != nil { t.Fatalf("\n%s\nRenderCompDiff(...): unexpected error: %v", tc.reason, err) } From 81a750c5ffe045ae9ad0832ede1e815690a6f127 Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 3 Dec 2026 13:54:36 -0500 Subject: [PATCH 05/16] test(simulate): pin nested-XR health ownership and the health tally Pin plan text, JSON and assembled composites for 2- and 3-level nested XRs built through FromCompReport, assert Failing() agrees with what the Health: line counts, and pin the equal-diff edge where -o diff counts a resource that summary.health and exit bit 4 do not. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/simulate/report_test.go | 95 +++++++++++++++++++++++++- internal/simulate/result_test.go | 112 +++++++++++++++++++++++++++++++ 2 files changed, 205 insertions(+), 2 deletions(-) diff --git a/internal/simulate/report_test.go b/internal/simulate/report_test.go index 4f1d05c1b..e349fdf88 100644 --- a/internal/simulate/report_test.go +++ b/internal/simulate/report_test.go @@ -17,8 +17,10 @@ limitations under the License. package simulate import ( + "bytes" "maps" "slices" + "strings" "testing" "github.com/google/go-cmp/cmp" @@ -27,8 +29,11 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime/schema" + "github.com/crossplane/cli/v2/internal/diff/renderer" dt "github.com/crossplane/cli/v2/internal/diff/result" + tu "github.com/crossplane/cli/v2/internal/diff/testutils" "github.com/crossplane/cli/v2/internal/health" + ht "github.com/crossplane/cli/v2/internal/health/healthtest" "github.com/crossplane/cli/v2/internal/plan" ) @@ -623,6 +628,10 @@ func TestHealth(t *testing.T) { d.Current.Raw = obj(d.Gvk, d.ResourceName, fields) return d } + desired := func(d *dt.ResourceDiff) *dt.ResourceDiff { + d.Desired.Raw = d.Desired.Clean + 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} @@ -640,16 +649,23 @@ func TestHealth(t *testing.T) { compRef := func(name string) *plan.ResourceRef { return &plan.ResourceRef{APIVersion: "apiextensions.crossplane.io/v1", Kind: "Composition", Name: name} } + grandPlan := plan.ResourceRef{APIVersion: "example.org/v1", Kind: "XZone", Name: "grand"} + healthy3 := ht.NewHealth(health.Healthy).Build() + failing3 := ht.NewHealth(health.Failing).WithSynced(corev1.ConditionFalse, "ReconcileError", "boom").Build() + notReady3 := ht.NewHealth(health.NotReady).WithReady(corev1.ConditionFalse, "Creating", "").Build() 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 plan.HealthSummary + // diffLine, when set, is the Health: line -o diff prints for args.xr. + diffLine string } type args struct { xr *dt.XRReport comp *dt.CompDiffOutput + keep func(*unstructured.Unstructured) bool } cases := map[string]struct { reason string @@ -788,13 +804,54 @@ func TestHealth(t *testing.T) { summary: plan.HealthSummary{Composites: 1, NotReady: 1}, }, }, + "NestedTwoLevels": { + reason: "A nested composite with health lists what it composes; its parent lists only its own.", + args: args{comp: nestedCompReport(2)}, + want: want{ + plans: map[string]*health.Health{"net": nil}, + composites: []CompositeResult{ + {Ref: xrPlan, Composition: &compPlan, Status: CompositeUnchanged, Health: healthy3, Unhealthy: []UnhealthyResource{{Ref: cmPlan("a-cm"), Health: failing3}}}, + {Ref: childPlan, Composition: &compPlan, ComposedBy: &xrPlan, Status: CompositeUnchanged, Health: notReady3, Unhealthy: []UnhealthyResource{{Ref: cmPlan("b-cm"), Health: notReady3}}}, + }, + summary: plan.HealthSummary{Composites: 1, Failing: 1, NotReady: 1}, + }, + }, + "NestedThreeLevels": { + reason: "In a chain of three composites with health, each unhealthy resource is listed once, under the deepest composite.", + args: args{comp: nestedCompReport(3)}, + want: want{ + plans: map[string]*health.Health{"net": nil}, + composites: []CompositeResult{ + {Ref: xrPlan, Composition: &compPlan, Status: CompositeUnchanged, Health: healthy3, Unhealthy: []UnhealthyResource{{Ref: cmPlan("a-cm"), Health: failing3}}}, + {Ref: childPlan, Composition: &compPlan, ComposedBy: &xrPlan, Status: CompositeUnchanged, Health: notReady3, Unhealthy: []UnhealthyResource{{Ref: cmPlan("b-cm"), Health: notReady3}}}, + {Ref: grandPlan, Composition: &compPlan, ComposedBy: &childPlan, Status: CompositeUnchanged, Health: failing3, Unhealthy: []UnhealthyResource{{Ref: cmPlan("c-cm"), Health: &health.Health{State: health.Paused}}}}, + }, + summary: plan.HealthSummary{Composites: 2, Failing: 1, NotReady: 1, Paused: 1}, + }, + }, + "EqualKeptForMissingProviderPlan": { + reason: "An unhealthy equal diff kept only for a provider plan that has none, and composed by no entry, is dropped from the plans, so summary.health and exit bit 4 miss it; " + + "the -o diff Health: line still counts it as failing. Pinned as today's divergence (design open question f).", + args: args{ + xr: &dt.XRReport{Groups: []dt.XRDiffGroup{{ + XR: xrRef, + Diffs: diffs(desired(live(rdiff(cmGVK, "kept", dt.DiffTypeEqual, map[string]any{}, map[string]any{}), cond("Synced", "False")))), + }}}, + keep: func(*unstructured.Unstructured) bool { return true }, + }, + want: want{ + plans: map[string]*health.Health{}, + composites: []CompositeResult{{Ref: xrPlan, Status: CompositeUnchanged}}, + diffLine: "Health: 1 resource failing (Synced=False).", + }, + }, } for name, tc := range cases { t.Run(name, func(t *testing.T) { - got := FromXRReport(tc.args.xr, nil, nil) + got := FromXRReport(tc.args.xr, nil, tc.args.keep) if tc.args.comp != nil { - got = FromCompReport(tc.args.comp, nil, nil) + got = FromCompReport(tc.args.comp, nil, tc.args.keep) } gotPlans := map[string]*health.Health{} for _, p := range got.Plans { @@ -809,6 +866,40 @@ func TestHealth(t *testing.T) { if diff := cmp.Diff(tc.want.summary, got.Health()); diff != "" { t.Errorf("%s\nHealth(): -want, +got:\n%s", tc.reason, diff) } + // Exit bit 4 is set exactly when the Health: line counts a failing + // item: a failing resource, or a failing XR among its unhealthy XRs. + if line, want := got.HealthLine(), anyFailing(got); got.Failing() != want { + t.Errorf("%s\nFailing(): want %t, got %t; HealthLine() is %q", tc.reason, want, got.Failing(), line) + } + if tc.want.diffLine != "" { + var buf bytes.Buffer + opts := renderer.DefaultDiffOptions() + opts.Stdout, opts.Stderr = &buf, &bytes.Buffer{} + r := AnnotateXRReport(tc.args.xr, nil) + if err := renderer.NewDiffRenderer(tu.TestLogger(t, false), opts).RenderDiffs(r.Groups, r.Errors, r.Warnings); err != nil { + t.Fatalf("%s\nRenderDiffs(...): unexpected error: %v", tc.reason, err) + } + var line string + for l := range strings.Lines(buf.String()) { + if strings.HasPrefix(l, "Health:") { + line = strings.TrimSpace(l) + } + } + if diff := cmp.Diff(tc.want.diffLine, line); diff != "" { + t.Errorf("%s\n-o diff Health: line: -want, +got:\n%s", tc.reason, diff) + } + } }) } } + +// anyFailing reports whether the Health: line of r counts a failing item: a +// failing resource, or a failing composite among the XRs it counts. +func anyFailing(r Result) bool { + if r.Health().Failing > 0 { + return true + } + return slices.ContainsFunc(r.Composites, func(c CompositeResult) bool { + return c.Health != nil && c.Health.State == health.Failing + }) +} diff --git a/internal/simulate/result_test.go b/internal/simulate/result_test.go index cadaad191..7c29f5d86 100644 --- a/internal/simulate/result_test.go +++ b/internal/simulate/result_test.go @@ -23,8 +23,11 @@ import ( "testing" "github.com/google/go-cmp/cmp" + corev1 "k8s.io/api/core/v1" + dt "github.com/crossplane/cli/v2/internal/diff/result" "github.com/crossplane/cli/v2/internal/health" + ht "github.com/crossplane/cli/v2/internal/health/healthtest" "github.com/crossplane/cli/v2/internal/plan" ) @@ -309,6 +312,9 @@ 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"}} + comp := `{"apiVersion":"apiextensions.crossplane.io/v1","kind":"Composition","name":"net"}` + failingJSON := `{"state":"failing","synced":{"status":"False","reason":"ReconcileError","message":"boom"}}` + notReadyJSON := `{"state":"notReady","ready":{"status":"False","reason":"Creating"}}` type want struct { composites string @@ -354,6 +360,32 @@ func TestRenderJSONHealth(t *testing.T) { 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}`, }, }, + "NestedTwoLevels": { + reason: "Through the assembler, each unhealthy resource is under the deepest XR with health, and summary.health counts each once.", + args: args{in: FromCompReport(nestedCompReport(2), nil, nil)}, + want: want{ + composites: `[` + `{"ref":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"status":"unchanged","composition":` + comp + `,"health":{"state":"healthy"},` + + `"unhealthy":[{"ref":{"apiVersion":"v1","kind":"ConfigMap","name":"a-cm"},"health":` + failingJSON + `}]},` + + `{"ref":{"apiVersion":"example.org/v1","kind":"XSubnet","name":"child"},"status":"unchanged","composition":` + comp + `,"composedBy":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"health":` + notReadyJSON + `,` + + `"unhealthy":[{"ref":{"apiVersion":"v1","kind":"ConfigMap","name":"b-cm"},"health":` + notReadyJSON + `}]}` + `]`, + plans: `[{"apiVersion":"apiextensions.crossplane.io/v1","kind":"Composition","name":"net","action":"no-op"}]`, + summary: `{"create":0,"update":0,"destroy":0,"replace":0,"noop":1,"approximate":0,"errored":0,"health":{"unhealthyComposites":1,"failing":1,"notReady":1,"paused":0},"deferred":0}`, + }, + }, + "NestedThreeLevels": { + reason: "Through the assembler, in a chain of three XRs with health each unhealthy resource is under the deepest XR, and summary.health counts each once.", + args: args{in: FromCompReport(nestedCompReport(3), nil, nil)}, + want: want{ + composites: `[` + `{"ref":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"status":"unchanged","composition":` + comp + `,"health":{"state":"healthy"},` + + `"unhealthy":[{"ref":{"apiVersion":"v1","kind":"ConfigMap","name":"a-cm"},"health":` + failingJSON + `}]},` + + `{"ref":{"apiVersion":"example.org/v1","kind":"XSubnet","name":"child"},"status":"unchanged","composition":` + comp + `,"composedBy":{"apiVersion":"example.org/v1","kind":"XNetwork","name":"prod"},"health":` + notReadyJSON + `,` + + `"unhealthy":[{"ref":{"apiVersion":"v1","kind":"ConfigMap","name":"b-cm"},"health":` + notReadyJSON + `}]}` + `,` + + `{"ref":{"apiVersion":"example.org/v1","kind":"XZone","name":"grand"},"status":"unchanged","composition":` + comp + `,"composedBy":{"apiVersion":"example.org/v1","kind":"XSubnet","name":"child"},"health":` + failingJSON + `,` + + `"unhealthy":[{"ref":{"apiVersion":"v1","kind":"ConfigMap","name":"c-cm"},"health":{"state":"paused"}}]}]`, + plans: `[{"apiVersion":"apiextensions.crossplane.io/v1","kind":"Composition","name":"net","action":"no-op"}]`, + summary: `{"create":0,"update":0,"destroy":0,"replace":0,"noop":1,"approximate":0,"errored":0,"health":{"unhealthyComposites":2,"failing":1,"notReady":1,"paused":1},"deferred":0}`, + }, + }, } for name, tc := range cases { @@ -533,6 +565,51 @@ XR: XSubnet.aws.platform.upbound.io crossplane-system/net-sn Plan: 0 to add, 0 to change, 0 to destroy. Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False), 1 not ready. +`, + }, + "NestedTwoLevels": { + reason: "Through the assembler, a nested XR with health lists what it composes and its parent lists only its own.", + args: args{r: FromCompReport(nestedCompReport(2), nil, nil)}, + want: `[=] Composition.apiextensions.crossplane.io net (no-op) + +XR: XNetwork.example.org prod + Unhealthy resources without changes: + ConfigMap. a-cm ⚠ failing (Synced=False, ReconcileError): boom + +XR: XSubnet.example.org child ⚠ not ready (Ready=False, Creating) + ↳ composed by XNetwork.example.org prod + Unhealthy resources without changes: + ConfigMap. b-cm ⚠ not ready (Ready=False, Creating) + +Plan: 0 to add, 0 to change, 0 to destroy. +Health: 1 of 2 XRs unhealthy before apply; 1 resource failing (Synced=False), 1 not ready. + +Note: Provider plan not run. +`, + }, + "NestedThreeLevels": { + reason: "Through the assembler, in a chain of three XRs with health each unhealthy resource is listed once, under the deepest XR.", + args: args{r: FromCompReport(nestedCompReport(3), nil, nil)}, + want: `[=] Composition.apiextensions.crossplane.io net (no-op) + +XR: XNetwork.example.org prod + Unhealthy resources without changes: + ConfigMap. a-cm ⚠ failing (Synced=False, ReconcileError): boom + +XR: XSubnet.example.org child ⚠ not ready (Ready=False, Creating) + ↳ composed by XNetwork.example.org prod + Unhealthy resources without changes: + ConfigMap. b-cm ⚠ not ready (Ready=False, Creating) + +XR: XZone.example.org grand ⚠ failing (Synced=False, ReconcileError): boom + ↳ composed by XSubnet.example.org child + Unhealthy resources without changes: + ConfigMap. c-cm ⚠ paused + +Plan: 0 to add, 0 to change, 0 to destroy. +Health: 2 of 3 XRs unhealthy before apply; 1 resource failing (Synced=False), 1 not ready, 1 paused. + +Note: Provider plan not run. `, }, "UngroupedDelete": { @@ -559,6 +636,10 @@ Health: 1 resource failing (Synced=False). if diff := cmp.Diff(tc.want, buf.String()); diff != "" { t.Errorf("\n%s\nRender(plan): -want, +got:\n%s", tc.reason, diff) } + // Exit bit 4 is set exactly when the Health: line counts a failing item. + if got, want := tc.args.r.Failing(), anyFailing(tc.args.r); got != want { + t.Errorf("\n%s\nFailing(): want %t, got %t; HealthLine() is %q", tc.reason, want, got, tc.args.r.HealthLine()) + } }) } } @@ -611,3 +692,34 @@ func TestResultFailing(t *testing.T) { }) } } + +// nestedCompReport returns a composition run whose one composition reaches +// the XR xrRef composing a nested XR XSubnet "child", which at depth 3 +// composes XZone "grand". Each XR has an impact with health of its own, and +// each composes one unhealthy ConfigMap named for it. A parent's composed +// health holds every level below it, with Via naming the XR between. +func nestedCompReport(depth int) *dt.CompDiffOutput { + failing := ht.NewHealth(health.Failing).WithSynced(corev1.ConditionFalse, "ReconcileError", "boom").Build() + notReady := ht.NewHealth(health.NotReady).WithReady(corev1.ConditionFalse, "Creating", "").Build() + paused := ht.NewHealth(health.Paused).Build() + cm := func(name string) corev1.ObjectReference { + return corev1.ObjectReference{APIVersion: "v1", Kind: "ConfigMap", Name: name} + } + child := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XSubnet", Name: "child"} + grand := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XZone", Name: "grand"} + + top := []dt.ResourceHealth{{ObjectReference: cm("a-cm"), Health: failing}, {ObjectReference: child, Health: notReady}, {ObjectReference: cm("b-cm"), Via: &child, Health: notReady}} + mid := []dt.ResourceHealth{{ObjectReference: cm("b-cm"), Health: notReady}} + if depth == 3 { + top = append(top, dt.ResourceHealth{ObjectReference: grand, Via: &child, Health: failing}, dt.ResourceHealth{ObjectReference: cm("c-cm"), Via: &grand, Health: paused}) + mid = append(mid, dt.ResourceHealth{ObjectReference: grand, Health: failing}, dt.ResourceHealth{ObjectReference: cm("c-cm"), Via: &grand, Health: paused}) + } + impacts := []dt.XRImpact{ + {ObjectReference: xrRef, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: ht.NewHealth(health.Healthy).Build(), Composed: top}}, + {ObjectReference: child, ComposedBy: &xrRef, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: notReady, Composed: mid}}, + } + if depth == 3 { + impacts = append(impacts, dt.XRImpact{ObjectReference: grand, ComposedBy: &child, Status: dt.XRStatusUnchanged, Health: dt.CompositeHealth{XR: failing, Composed: []dt.ResourceHealth{{ObjectReference: cm("c-cm"), Health: paused}}}}) + } + return &dt.CompDiffOutput{Compositions: []dt.CompositionDiff{{Name: "net", ImpactAnalysis: impacts}}} +} From b3715ddc3a34f2c08a0f017dc9eec75b22648c8d Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 3 Dec 2026 14:06:28 -0500 Subject: [PATCH 06/16] test(plan): pin resource simulate health and exit status Pin the plan text health lines and Health: line for every health state, long message cutting and --full-messages wrapping, Failing per state, and the 0/3/4/7 exit bits, each checked against the Health: line's failing count. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- cmd/crossplane/simulate/simulate_test.go | 24 +++++ internal/plan/output_test.go | 111 +++++++++++++++++++++++ 2 files changed, 135 insertions(+) diff --git a/cmd/crossplane/simulate/simulate_test.go b/cmd/crossplane/simulate/simulate_test.go index c16147cdd..87ab3b955 100644 --- a/cmd/crossplane/simulate/simulate_test.go +++ b/cmd/crossplane/simulate/simulate_test.go @@ -27,6 +27,7 @@ import ( "github.com/crossplane/cli/v2/internal/exitcode" "github.com/crossplane/cli/v2/internal/health" "github.com/crossplane/cli/v2/internal/plan" + isimulate "github.com/crossplane/cli/v2/internal/simulate" ) func TestExitStatus(t *testing.T) { @@ -78,6 +79,26 @@ func TestExitStatus(t *testing.T) { }}, want: 0, }, + "BitsNone": { + reason: "Neither the changes bits (1|2) nor the failing bit 4 set: exit 0.", + args: args{plans: []*plan.ResourcePlan{{Action: plan.ActionNoOp, Health: &health.Health{State: health.Healthy}}}}, + want: 0, + }, + "BitsChangesOnly": { + reason: "Only the changes bits 1|2 set: exit 3. Failing agrees with the Health: line counting no failing resource.", + args: args{plans: []*plan.ResourcePlan{{Action: plan.ActionCreate}, {Action: plan.ActionNoOp, Health: &health.Health{State: health.Paused}}}}, + want: 3, + }, + "BitsFailingOnly": { + reason: "Only the failing bit 4 set: exit 4.", + args: args{plans: []*plan.ResourcePlan{{Kind: "VPC", Name: "a", Action: plan.ActionNoOp, Health: failing}, {Kind: "VPC", Name: "b", Action: plan.ActionNoOp, Health: &health.Health{State: health.NotReady}}}}, + want: 4, + }, + "BitsBoth": { + reason: "The changes bits 1|2 and the failing bit 4 set: exit 7, even when the failing resource is the one deleted.", + args: args{plans: []*plan.ResourcePlan{{Action: plan.ActionDelete, Health: failing}}}, + want: 7, + }, "ErroredWithFailing": { reason: "An errored plan should exit 1, not 4 or 7, even when a resource is failing.", args: args{plans: []*plan.ResourcePlan{{Action: plan.ActionUpdate, Health: failing}, {Error: "boom"}}}, @@ -98,6 +119,9 @@ func TestExitStatus(t *testing.T) { if diff := cmp.Diff(tc.want, got); diff != "" { t.Errorf("\n%s\nexitStatus(...): -want exit code, +got:\n%s", tc.reason, diff) } + if bit, line := got != 1 && got&isimulate.ExitCodeFailing != 0, plan.HealthCounts(tc.args.plans).Failing > 0 && got != 1; bit != line { + t.Errorf("\n%s\nexit bit 4 = %t, but the Health: line counts failing = %t", tc.reason, bit, line) + } }) } } diff --git a/internal/plan/output_test.go b/internal/plan/output_test.go index 3e8ea4dce..9129667b9 100644 --- a/internal/plan/output_test.go +++ b/internal/plan/output_test.go @@ -19,6 +19,7 @@ package plan import ( "bytes" "encoding/json" + "strings" "testing" "github.com/google/go-cmp/cmp" @@ -26,6 +27,7 @@ import ( "sigs.k8s.io/yaml" "github.com/crossplane/cli/v2/internal/health" + ht "github.com/crossplane/cli/v2/internal/health/healthtest" ) func testPlans() []*ResourcePlan { @@ -311,6 +313,7 @@ func TestRenderPlanHealth(t *testing.T) { failing := func(msg string) *health.Health { return &health.Health{State: health.Failing, Synced: &health.Condition{Status: "False", Reason: "ReconcileError", Message: msg}} } + longMsg := strings.Repeat("creating VPC: operation error EC2: CreateVpc, https response error StatusCode: 400, ", 3) + "api error" vpcMsg := "The vpc ID 'vpc-048777c3b8a8ee173' does not exist\nstatus code: 400" update := &ResourcePlan{ APIVersion: "ec2.aws.upbound.io/v1beta1", Kind: "Subnet", Name: "my-subnet", Action: ActionUpdate, @@ -379,6 +382,75 @@ Health: 1 resource failing (Synced=False), 1 not ready, 1 paused. Plan: 0 to add, 1 to change, 0 to destroy. Health: 1 resource failing (Synced=False). +`, + }, + "EveryState": { + reason: "Healthy, failing, not ready, paused and unknown resources: only the unhealthy ones get a ⚠ line; Unknown conditions are healthy and print nothing.", + args: args{plans: []*ResourcePlan{ + noop("healthy-vpc", ht.NewHealth(health.Healthy).WithSynced("True", "ReconcileSuccess", "").WithReady("True", "Available", "").Build()), + noop("failing-vpc", ht.NewHealth(health.Failing).WithSynced("False", "ReconcileError", "boom").Build()), + noop("other-failing-vpc", ht.NewHealth(health.Failing).WithSynced("False", "ReconcileError", "bang").Build()), + noop("notready-vpc", ht.NewHealth(health.NotReady).WithReady("False", "Creating", "").Build()), + noop("paused-vpc", ht.NewHealth(health.Paused).WithSynced("False", "ReconcileError", "ignored").Build()), + noop("unknown-vpc", ht.NewHealth(health.Healthy).WithSynced("Unknown", "", "").WithReady("Unknown", "", "").Build()), + }}, + want: `[=] VPC.ec2.aws.upbound.io healthy-vpc (no-op) + +[=] VPC.ec2.aws.upbound.io failing-vpc (no-op) + ⚠ failing (Synced=False, ReconcileError): boom + +[=] VPC.ec2.aws.upbound.io other-failing-vpc (no-op) + ⚠ failing (Synced=False, ReconcileError): bang + +[=] VPC.ec2.aws.upbound.io notready-vpc (no-op) + ⚠ not ready (Ready=False, Creating) + +[=] VPC.ec2.aws.upbound.io paused-vpc (no-op) + ⚠ paused + +[=] VPC.ec2.aws.upbound.io unknown-vpc (no-op) + +Plan: 0 to add, 0 to change, 0 to destroy. +Health: 2 resources failing (Synced=False), 1 not ready, 1 paused. +`, + }, + "OnlyNotReady": { + reason: "With nothing failing, the plural noun goes on the first non-zero part.", + args: args{plans: []*ResourcePlan{ + noop("a-vpc", ht.NewHealth(health.NotReady).WithReady("False", "Creating", "").Build()), + noop("b-vpc", ht.NewHealth(health.NotReady).WithReady("False", "Creating", "").Build()), + }}, + want: `[=] VPC.ec2.aws.upbound.io a-vpc (no-op) + ⚠ not ready (Ready=False, Creating) + +[=] VPC.ec2.aws.upbound.io b-vpc (no-op) + ⚠ not ready (Ready=False, Creating) + +Plan: 0 to add, 0 to change, 0 to destroy. +Health: 2 resources not ready. +`, + }, + "FullMessagesLong": { + reason: "With full messages, a message longer than the wrap width wraps at the wrap width beneath the ⚠ line, indented 8.", + args: args{plans: []*ResourcePlan{noop("long-vpc", ht.NewHealth(health.Failing).WithSynced("False", "ReconcileError", longMsg).Build())}, full: true}, + want: `[=] VPC.ec2.aws.upbound.io long-vpc (no-op) + ⚠ failing (Synced=False, ReconcileError) + creating VPC: operation error EC2: CreateVpc, https response error StatusCode: 400, creating VPC: + operation error EC2: CreateVpc, https response error StatusCode: 400, creating VPC: operation error + EC2: CreateVpc, https response error StatusCode: 400, api error + +Plan: 0 to add, 0 to change, 0 to destroy. +Health: 1 resource failing (Synced=False). +`, + }, + "LongCut": { + reason: "Without full messages, a long message is cut to one line with an ellipsis.", + args: args{plans: []*ResourcePlan{noop("long-vpc", ht.NewHealth(health.Failing).WithSynced("False", "ReconcileError", longMsg).Build())}}, + want: `[=] VPC.ec2.aws.upbound.io long-vpc (no-op) + ⚠ failing (Synced=False, ReconcileError): creating VPC: operation error EC2: CreateVpc, https response error StatusCode: 400, creating VPC: operation error EC2: … + +Plan: 0 to add, 0 to change, 0 to destroy. +Health: 1 resource failing (Synced=False). `, }, } @@ -392,6 +464,9 @@ Health: 1 resource failing (Synced=False). if diff := cmp.Diff(tc.want, buf.String()); diff != "" { t.Errorf("\n%s\nRender(plan): -want, +got:\n%s", tc.reason, diff) } + if got, line := Failing(tc.args.plans), HealthCounts(tc.args.plans).Failing > 0; got != line { + t.Errorf("\n%s\nFailing(...) = %t, but the Health: line counts failing = %t", tc.reason, got, line) + } }) } } @@ -539,6 +614,39 @@ func TestFailing(t *testing.T) { args: args{plans: []*ResourcePlan{{Health: &health.Health{State: health.NotReady}}, {Health: &health.Health{State: health.Paused}}}}, want: false, }, + "Healthy": { + reason: "A healthy resource is not failing.", + args: args{plans: []*ResourcePlan{{Health: ht.NewHealth(health.Healthy).Build()}}}, + want: false, + }, + "Unknown": { + reason: "A resource whose conditions are Unknown is healthy, so not failing.", + args: args{plans: []*ResourcePlan{{Health: ht.NewHealth(health.Healthy).WithSynced("Unknown", "", "").Build()}}}, + want: false, + }, + "NotReady": { + reason: "A not ready resource is not failing.", + args: args{plans: []*ResourcePlan{{Health: ht.NewHealth(health.NotReady).WithReady("False", "Creating", "").Build()}}}, + want: false, + }, + "Paused": { + reason: "A paused resource is not failing, even with Synced=False.", + args: args{plans: []*ResourcePlan{{Health: ht.NewHealth(health.Paused).WithSynced("False", "ReconcileError", "boom").Build()}}}, + want: false, + }, + "Failing": { + reason: "A failing resource is failing.", + args: args{plans: []*ResourcePlan{{Action: ActionNoOp, Health: ht.NewHealth(health.Failing).WithSynced("False", "ReconcileError", "boom").Build()}}}, + want: true, + }, + "FailingAmongHealthy": { + reason: "One failing resource among healthy ones makes the plans failing.", + args: args{plans: []*ResourcePlan{ + {Kind: "VPC", Name: "a", Health: ht.NewHealth(health.Healthy).Build()}, + {Kind: "VPC", Name: "b", Health: ht.NewHealth(health.Failing).Build()}, + }}, + want: true, + }, "FailingDelete": { reason: "A failing resource sets the bit, even one the plan deletes.", args: args{plans: []*ResourcePlan{{Action: ActionDelete, Health: &health.Health{State: health.Failing}}}}, @@ -550,6 +658,9 @@ func TestFailing(t *testing.T) { if diff := cmp.Diff(tc.want, Failing(tc.args.plans)); diff != "" { t.Errorf("\n%s\nFailing(...): -want, +got:\n%s", tc.reason, diff) } + if line := HealthCounts(tc.args.plans).Failing > 0; line != tc.want { + t.Errorf("\n%s\nthe Health: line counts failing = %t, want %t", tc.reason, line, tc.want) + } }) } } From 0ed380102678d2d850d989c9b15a327e00231aca Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 3 Dec 2026 17:45:40 -0500 Subject: [PATCH 07/16] refactor(health): build a run's health once Add health.Run and health.Build, which resolve a run's health ownership and tally its counts and failing bit in one pass, in simulate's order. Shown resources with no kind and no name never share a key. Nothing calls Build yet. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/health/format.go | 7 ++ internal/health/run.go | 114 +++++++++++++++++++++++++++++ internal/health/run_test.go | 141 ++++++++++++++++++++++++++++++++++++ 3 files changed, 262 insertions(+) create mode 100644 internal/health/run.go create mode 100644 internal/health/run_test.go diff --git a/internal/health/format.go b/internal/health/format.go index 13b5677ee..cea8f6fc1 100644 --- a/internal/health/format.go +++ b/internal/health/format.go @@ -266,10 +266,15 @@ type Tally struct { composites map[string]bool resources map[string]State order []string + // failing is set when anything is added failing, before the first-add + // dedup, so a failing resource counted under another state still sets it. + failing bool } // Composite adds a composite with key and health h. func (t *Tally) Composite(key string, h *Health) { + t.failing = t.failing || (h != nil && h.State == Failing) + if t.composites == nil { t.composites = map[string]bool{} } @@ -286,6 +291,8 @@ func (t *Tally) Resource(key string, h *Health) { return } + t.failing = t.failing || h.State == Failing + if t.resources == nil { t.resources = map[string]State{} } diff --git a/internal/health/run.go b/internal/health/run.go new file mode 100644 index 000000000..00f2c1c07 --- /dev/null +++ b/internal/health/run.go @@ -0,0 +1,114 @@ +/* +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 ( + "strconv" + "strings" +) + +// Composite is one composite of a run as the engine observed it. +type Composite struct { + // Key is the composite's Key: the input's identity, a claim or an XR. + Key string + // Health is the composite's own live health, or nil when it has none: it + // is not in the cluster, it errored, or it was filtered out. + Health *Health + // Composed is every composed resource the engine observed, nested ones + // included with Via set, in the engine's order. Each ID is its Key. + Composed []Item +} + +// Run is a run's health, summarized once by Build. +type Run struct { + // Owned holds, for each composite, the indexes into its Composed of the + // unhealthy resources it lists, ownership resolved by OwnedElsewhere, and + // before any renderer filters out the resources it shows elsewhere. + Owned [][]int + // Counts are the run's health counts, for its summary line. + Counts Counts + // Failing reports whether anything in the run is failing, which sets exit + // bit 4. + Failing bool +} + +// Build summarizes the health of a run of composites, which shows the shown +// resources (its plans) itself. It tallies, in order, the composites with +// health of their own, the shown resources, and each owned resource that is +// not shown. Failing is set when anything tallied is failing, before the +// tally drops repeats, so it can be set by a resource that counts under an +// earlier health. +// +// A shown resource whose ID has no kind and no name, as a plan's can, is +// never taken for another, so each counts. +func Build(composites []Composite, shown []Item) Run { + entries := make([]Entry, len(composites)) + for i, c := range composites { + entries[i] = Entry{Key: c.Key, HasHealth: c.Health != nil} + for _, it := range c.Composed { + entries[i].Composes = append(entries[i].Composes, it.ID) + } + } + ownedElsewhere := OwnedElsewhere(entries) + + r := Run{Owned: make([][]int, len(composites))} + for i, c := range composites { + for j, it := range c.Composed { + if it.Health.Unhealthy() && !ownedElsewhere[i][it.ID] { + r.Owned[i] = append(r.Owned[i], j) + } + } + } + + t := &Tally{} + for _, c := range composites { + if c.Health != nil { + t.Composite(c.Key, c.Health) + } + } + + isShown := map[string]bool{} + for i, it := range shown { + key := it.ID + if unnamed(key) { + // A Key starts with a kind or "/", so this one can match no other. + key = "#" + strconv.Itoa(i) + } + isShown[key] = true + t.Resource(key, it.Health) + } + + for i, owned := range r.Owned { + for _, j := range owned { + it := composites[i].Composed[j] + if !isShown[it.ID] { + t.Resource(it.ID, it.Health) + } + } + } + + r.Counts = t.Counts() + r.Failing = t.failing + + return r +} + +// unnamed reports whether id is the Key of a resource with no kind and no +// name, such as Key("", "", ns, ""), or empty. +func unnamed(id string) bool { + return id == "" || (strings.HasPrefix(id, "/") && strings.HasSuffix(id, "/") && strings.Count(id, "/") == 2) +} diff --git a/internal/health/run_test.go b/internal/health/run_test.go new file mode 100644 index 000000000..efae268f3 --- /dev/null +++ b/internal/health/run_test.go @@ -0,0 +1,141 @@ +/* +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" +) + +func TestBuild(t *testing.T) { + failing := &Health{State: Failing} + notReady := &Health{State: NotReady} + healthy := &Health{State: Healthy} + + xr := Key("example.org/v1", "XR", "", "xr") + child := Key("example.org/v1", "Child", "", "child") + grand := Key("example.org/v1", "Grand", "", "grand") + a := Key("v1", "ConfigMap", "ns", "a") + b := Key("v1", "ConfigMap", "ns", "b") + unnamedNs := Key("", "", "ns", "") + + type args struct { + composites []Composite + shown []Item + } + cases := map[string]struct { + reason string + args args + want Run + }{ + "Nil": { + reason: "No composites and nothing shown is an empty run.", + want: Run{Owned: [][]int{}}, + }, + "Empty": { + reason: "Empty input is an empty run.", + args: args{composites: []Composite{}, shown: []Item{}}, + want: Run{Owned: [][]int{}}, + }, + "CompositeWinsOverResource": { + reason: "A composite also shown as a resource counts only as a composite.", + args: args{ + composites: []Composite{{Key: xr, Health: notReady}}, + shown: []Item{{ID: xr, Health: failing}}, + }, + want: Run{Owned: [][]int{nil}, Counts: Counts{Composites: 1, UnhealthyComposites: 1}, Failing: true}, + }, + "CompositeWithoutHealthNotCounted": { + reason: "A composite with no health of its own is not counted as a composite.", + args: args{composites: []Composite{{Key: xr}}}, + want: Run{Owned: [][]int{nil}}, + }, + "FirstShownWins": { + reason: "A resource shown twice counts once, under the health it was first shown with.", + args: args{shown: []Item{{ID: a, Health: notReady}, {ID: a, Health: failing}}}, + want: Run{Owned: [][]int{}, Counts: Counts{NotReady: 1}, Failing: true}, + }, + "FailingFromComposite": { + reason: "A failing composite sets Failing.", + args: args{composites: []Composite{{Key: xr, Health: failing}}}, + want: Run{Owned: [][]int{nil}, Counts: Counts{Composites: 1, UnhealthyComposites: 1}, Failing: true}, + }, + "FailingFromOwned": { + reason: "A failing owned resource sets Failing and counts.", + args: args{composites: []Composite{{Key: xr, Health: healthy, Composed: []Item{ + {ID: a, Health: healthy}, + {ID: b, Health: failing}, + }}}}, + want: Run{Owned: [][]int{{1}}, Counts: Counts{Composites: 1, Failing: 1}, Failing: true}, + }, + "OwnedMinusShownCountedOnce": { + reason: "An owned resource that is also shown counts once, with its shown health, and its owned health is not tallied, as simulate lists it only on its plan.", + args: args{ + composites: []Composite{{Key: xr, Health: healthy, Composed: []Item{{ID: a, Health: failing}}}}, + shown: []Item{{ID: a, Health: notReady}}, + }, + want: Run{Owned: [][]int{{0}}, Counts: Counts{Composites: 1, NotReady: 1}}, + }, + "NestedOwnership": { + reason: "A resource is owned by the most deeply nested composite with health that composes it, three levels down.", + args: args{composites: []Composite{ + {Key: xr, Health: healthy, Composed: []Item{ + {ID: child, Health: notReady}, + {ID: grand, Via: child, Health: notReady}, + {ID: a, Via: grand, Health: failing}, + }}, + {Key: child, Health: notReady, Composed: []Item{ + {ID: grand, Health: notReady}, + {ID: a, Via: grand, Health: failing}, + }}, + {Key: grand, Health: notReady, Composed: []Item{{ID: a, Health: failing}}}, + }}, + want: Run{ + Owned: [][]int{nil, nil, {0}}, + Counts: Counts{Composites: 3, UnhealthyComposites: 2, Failing: 1}, + Failing: true, + }, + }, + "IdempotentOnResolved": { + reason: "Already resolved composites resolve to themselves: a nested entry without health stays with its parent.", + args: args{composites: []Composite{ + {Key: xr, Health: healthy, Composed: []Item{{ID: child, Health: notReady}}}, + {Key: child, Composed: []Item{{ID: a, Health: failing}}}, + }}, + want: Run{Owned: [][]int{{0}, {0}}, Counts: Counts{Composites: 1, NotReady: 1, Failing: 1}, Failing: true}, + }, + "UnnamedShownEachCount": { + reason: "Shown resources with no kind and no name never share a key, so the failing count agrees with Failing.", + args: args{shown: []Item{ + {ID: unnamedNs, Health: notReady}, + {ID: unnamedNs, Health: failing}, + {Health: failing}, + }}, + want: Run{Owned: [][]int{}, Counts: Counts{NotReady: 1, Failing: 2}, Failing: true}, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + got := Build(tc.args.composites, tc.args.shown) + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("\n%s\nBuild(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} From fbb1d1752d8a223da8d6be063b904a9dc3111edf Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 3 Dec 2026 17:51:40 -0500 Subject: [PATCH 08/16] refactor(simulate): build the run's health in the assembler The assembler builds a health.Run once with health.Build and lists each composite's Unhealthy from Run.Owned. Result's Health, Failing and HealthLine read a Run built from its resolved lists, so healthTally goes. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/simulate/report.go | 36 +++++++++++++++------------ internal/simulate/result.go | 49 +++++++++++++++++-------------------- 2 files changed, 43 insertions(+), 42 deletions(-) diff --git a/internal/simulate/report.go b/internal/simulate/report.go index 81c1cf53a..245d388ce 100644 --- a/internal/simulate/report.go +++ b/internal/simulate/report.go @@ -261,26 +261,16 @@ func (a *assembler) addComposite(c CompositeResult, h dt.CompositeHealth) { // 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() { +func (a *assembler) unhealthy(run health.Run) { planned := map[string]bool{} for _, p := range a.plans { planned[health.Key(p.APIVersion, p.Kind, p.Namespace, p.Name)] = true } - entries := make([]health.Entry, len(a.composed)) - for i, composed := range a.composed { - c := a.composites[i] - entries[i] = health.Entry{Key: healthKey(c.Ref), HasHealth: c.Health != nil} - for _, r := range composed { - entries[i].Composes = append(entries[i].Composes, health.Key(r.APIVersion, r.Kind, r.Namespace, r.Name)) - } - } - ownedElsewhere := health.OwnedElsewhere(entries) - - for i, composed := range a.composed { - for _, r := range composed { - id := health.Key(r.APIVersion, r.Kind, r.Namespace, r.Name) - if !r.Health.Unhealthy() || planned[id] || ownedElsewhere[i][id] { + for i, owned := range run.Owned { + for _, j := range owned { + r := a.composed[i][j] + if planned[health.Key(r.APIVersion, r.Kind, r.Namespace, r.Name)] { continue } u := UnhealthyResource{Ref: resourceRef(r.ObjectReference), Health: r.Health} @@ -293,6 +283,19 @@ func (a *assembler) unhealthy() { } } +// run builds the run's health from every composite, what it composed, and +// the plans. +func (a *assembler) run() health.Run { + composites := make([]health.Composite, len(a.composites)) + for i, c := range a.composites { + composites[i] = health.Composite{Key: healthKey(c.Ref), Health: c.Health} + for _, r := range a.composed[i] { + composites[i].Composed = append(composites[i].Composed, health.Item{ID: health.Key(r.APIVersion, r.Kind, r.Namespace, r.Name), Health: r.Health}) + } + } + return health.Build(composites, planItems(a.plans)) +} + // 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. @@ -421,7 +424,8 @@ func (a *assembler) addRunErrors(all, owned []dt.OutputError) { } func (a *assembler) result(warnings []dt.OutputWarning) Result { - a.unhealthy() + run := a.run() + a.unhealthy(run) res := NewResult(a.plans, a.composites, a.errors) if a.provider == nil { res.Notes = []string{noteProviderPlanNotRun} diff --git a/internal/simulate/result.go b/internal/simulate/result.go index 2b1f2b364..e16cad414 100644 --- a/internal/simulate/result.go +++ b/internal/simulate/result.go @@ -207,49 +207,46 @@ func (r Result) Deferred() int { // 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() plan.HealthSummary { - c := r.healthTally().Counts() + c := r.healthRun().Counts return plan.HealthSummary{Composites: c.UnhealthyComposites, Failing: c.Failing, NotReady: c.NotReady, Paused: c.Paused} } -// healthTally adds r's composites and resources to a health.Tally. A -// composite with no health of its own here (one not simulated) isn't added as -// a composite, so it counts as a resource where its parent lists it, if -// anywhere. -func (r Result) healthTally() *health.Tally { - t := &health.Tally{} - for _, c := range r.Composites { - if c.Health != nil { - t.Composite(healthKey(c.Ref), c.Health) - } - } - for _, p := range r.Plans { - t.Resource(healthKey(p.ResourceRef()), p.Health) - } - for _, c := range r.Composites { +// healthRun builds the run's health from Composites and Plans. Each +// Unhealthy list is already resolved, which Build leaves as it is, so this +// matches the Run the assembler built them from. A composite with no health of its own here (one not +// simulated) isn't added as a composite, so it counts as a resource where its +// parent lists it, if anywhere. +func (r Result) healthRun() health.Run { + composites := make([]health.Composite, len(r.Composites)) + for i, c := range r.Composites { + composites[i] = health.Composite{Key: healthKey(c.Ref), Health: c.Health} for _, u := range c.Unhealthy { - t.Resource(healthKey(u.Ref), u.Health) + composites[i].Composed = append(composites[i].Composed, health.Item{ID: healthKey(u.Ref), Health: u.Health}) } } - return t + return health.Build(composites, planItems(r.Plans)) +} + +// planItems returns plans as the resources a run shows itself. +func planItems(plans []*plan.ResourcePlan) []health.Item { + items := make([]health.Item, len(plans)) + for i, p := range plans { + items[i] = health.Item{ID: healthKey(p.ResourceRef()), Health: p.Health} + } + return items } // Failing reports whether a composite or any resource in r is failing, which // sets exit bit 4. func (r Result) Failing() bool { - failing := func(h *health.Health) bool { return h != nil && h.State == health.Failing } - for _, c := range r.Composites { - if failing(c.Health) || slices.ContainsFunc(c.Unhealthy, func(u UnhealthyResource) bool { return failing(u.Health) }) { - return true - } - } - return slices.ContainsFunc(r.Plans, func(p *plan.ResourcePlan) bool { return failing(p.Health) }) + return r.healthRun().Failing } // HealthLine returns the Health: line summarizing r, or "" when nothing in // it is unhealthy. Its XRs are the composites with health of their own, each // once. func (r Result) HealthLine() string { - return health.SummaryLine(r.healthTally().Counts()) + return health.SummaryLine(r.healthRun().Counts) } // healthKey identifies ref across API versions, as health.Key does. From 14aa8bd88b6b33b5fa60682aff698ae479fa22fd Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 3 Dec 2026 17:56:01 -0500 Subject: [PATCH 09/16] refactor(simulate): build resource simulate's health once Resource simulate builds one health.Run from its plans with health.Build. The Health: line, summary.health and exit bit 4 read it; plan.HealthCounts and plan.Failing stay for their test callers until they are removed. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- cmd/crossplane/simulate/simulate.go | 2 +- internal/plan/output.go | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/cmd/crossplane/simulate/simulate.go b/cmd/crossplane/simulate/simulate.go index 82b6b3016..304a6046a 100644 --- a/cmd/crossplane/simulate/simulate.go +++ b/cmd/crossplane/simulate/simulate.go @@ -192,7 +192,7 @@ func exitStatus(plans []*plan.ResourcePlan) error { if s.Changes() > 0 { code |= isimulate.ExitCodeChanges } - if plan.Failing(plans) { + if plan.HealthRun(plans).Failing { code |= isimulate.ExitCodeFailing } if code == 0 { diff --git a/internal/plan/output.go b/internal/plan/output.go index 7700717a8..9e870d816 100644 --- a/internal/plan/output.go +++ b/internal/plan/output.go @@ -134,6 +134,20 @@ func Failing(plans []*ResourcePlan) bool { return slices.ContainsFunc(plans, func(p *ResourcePlan) bool { return p.Health != nil && p.Health.State == health.Failing }) } +// HealthRun returns the run's health: plans are the resources it shows, with +// no composites of its own. +func HealthRun(plans []*ResourcePlan) health.Run { + items := make([]health.Item, len(plans)) + for i, p := range plans { + ns := p.Namespace + if p.LiveNamespace != "" { + ns = p.LiveNamespace + } + items[i] = health.Item{ID: health.Key(p.APIVersion, p.Kind, ns, p.Name), Health: p.Health} + } + return health.Build(nil, items) +} + // MarshalJSON writes the result with its plans' health counts under // summary.health. YAML goes through it too. Decoding needs no counterpart: // summary decodes into Summary, and the health counts come from Plans. @@ -143,7 +157,7 @@ func (r Result) MarshalJSON() ([]byte, error) { Health HealthSummary `json:"health"` } - c := HealthCounts(r.Plans) + c := HealthRun(r.Plans).Counts return json.Marshal(struct { FormatVersion string `json:"formatVersion"` Errored bool `json:"errored"` @@ -230,7 +244,7 @@ func (pr planRenderer) Render(w io.Writer, plans []*ResourcePlan) error { } s := Summarize(plans) RenderSummaryLine(w, s) - if line := health.SummaryLine(HealthCounts(plans)); line != "" { + if line := health.SummaryLine(HealthRun(plans).Counts); line != "" { _, _ = fmt.Fprintln(w, line) } RenderSummaryWarnings(w, plans, s) From 2123c658d08d2291827927abb8043da69455cce8 Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 3 Dec 2026 18:05:17 -0500 Subject: [PATCH 10/16] refactor(renderer): render xr diff health from the run's model The xr -o diff renderer reads one health.Run, passed in through the new DiffOptions.Health, for which group lists each unhealthy resource and for the Health: line, in both the flat and grouped layouts. renderXRReport builds it from the Result's composites and plans, so the Health: line now counts plans, as summary.health and exit bit 4 do (D-1): an unhealthy equal diff dropped for a missing provider plan is no longer counted. groupsOwnedElsewhere loses its last caller and goes. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/diff/renderer/diff_formatter.go | 6 ++ internal/diff/renderer/diff_renderer.go | 37 ++++---- internal/diff/renderer/health.go | 103 +++++++++++++++++------ internal/simulate/report.go | 31 +++++-- internal/simulate/report_test.go | 14 +-- internal/simulate/run.go | 6 +- 6 files changed, 138 insertions(+), 59 deletions(-) diff --git a/internal/diff/renderer/diff_formatter.go b/internal/diff/renderer/diff_formatter.go index 0164944be..c00846d7d 100644 --- a/internal/diff/renderer/diff_formatter.go +++ b/internal/diff/renderer/diff_formatter.go @@ -10,6 +10,7 @@ import ( "github.com/sergi/go-diff/diffmatchpatch" t "github.com/crossplane/cli/v2/internal/diff/result" + "github.com/crossplane/cli/v2/internal/health" ) // DiffOptions holds configuration options for the diff output. @@ -54,6 +55,11 @@ type DiffOptions struct { // FullMessages prints health condition messages in full, wrapped, rather // than cut to one line. FullMessages bool + + // Health, when set, is the run's health, one composite per group of the + // xr diff in order: which group lists each unhealthy resource, and the + // Health: line's counts. Nil builds it from the groups. + Health *health.Run } // OutputFormat represents the desired output format for diffs. diff --git a/internal/diff/renderer/diff_renderer.go b/internal/diff/renderer/diff_renderer.go index 1947cc465..7a603fe8b 100644 --- a/internal/diff/renderer/diff_renderer.go +++ b/internal/diff/renderer/diff_renderer.go @@ -270,7 +270,7 @@ func (r *DefaultDiffRenderer) RenderDiffs(groups []dt.XRDiffGroup, errs []dt.Out if len(xrGroups) > 1 { err = r.renderGrouped(groups) } else { - err = r.renderFlat(flattenGroups(groups), xrGroups) + err = r.renderFlat(groups, xrGroups) } if err != nil { @@ -286,25 +286,25 @@ func (r *DefaultDiffRenderer) RenderDiffs(groups []dt.XRDiffGroup, errs []dt.Out // when it or what it composes is not healthy: its health on a line before the // diffs, its unhealthy resources without changes after them, and a Health: // line after the summary. -func (r *DefaultDiffRenderer) renderFlat(diffs map[string]*dt.ResourceDiff, xrGroups []dt.XRDiffGroup) error { +func (r *DefaultDiffRenderer) renderFlat(groups, xrGroups []dt.XRDiffGroup) error { stdout := r.diffOpts.Stdout full := r.diffOpts.FullMessages + diffs := flattenGroups(groups) - var ( - head, block, described string - t health.Tally - ) + var head, block, described, healthLine string if len(xrGroups) == 1 { - g := xrGroups[0] + run := groupsRun(r.diffOpts, groups) + i := slices.IndexFunc(groups, hasIdentity) + g := groups[i] if desc := healthDescription(g.Health.XR, full); len(desc) > 0 { desc[0] = "XR: " + groupTitle(g) + " " + desc[0] head = joinLines(desc) + "\n" described = refKey(g.XR) } - block = joinLines(unhealthyBlock(g.Health, g.Diffs, nil, full)) - tallyComposite(&t, g.XR, g.Health, g.Diffs) + block = joinLines(ownedBlock(g.Health, run.Owned[i], g.Diffs, full)) + healthLine = joinLines([]string{health.SummaryLine(run.Counts)}) } if err := write(stdout, head); err != nil { @@ -326,7 +326,7 @@ func (r *DefaultDiffRenderer) renderFlat(diffs map[string]*dt.ResourceDiff, xrGr // The block, Summary and Health lines are separated by blank lines from // whatever precedes them. written := head != "" || counts.output > 0 - for _, s := range []string{block, summaryText(summary), joinLines([]string{health.SummaryLine(t.Counts())})} { + for _, s := range []string{block, summaryText(summary), healthLine} { if s == "" || s == "\n" { continue } @@ -376,10 +376,9 @@ func (r *DefaultDiffRenderer) renderGrouped(groups []dt.XRDiffGroup) error { xrCount int unchangedXR int errorXR int - t health.Tally ) - ownedElsewhere := groupsOwnedElsewhere(groups) + run := groupsRun(r.diffOpts, groups) for i, g := range groups { // An identity-less group (should not normally be mixed in here) has no @@ -398,9 +397,7 @@ func (r *DefaultDiffRenderer) renderGrouped(groups []dt.XRDiffGroup) error { xrCount++ - tallyComposite(&t, g.XR, g.Health, g.Diffs) - - counts, err := r.renderSection(g, ownedElsewhere[i]) + counts, err := r.renderSection(g, run.Owned[i]) if err != nil { return err } @@ -419,15 +416,15 @@ func (r *DefaultDiffRenderer) renderGrouped(groups []dt.XRDiffGroup) error { return err } - return writeHealthLine(stdout, &t) + return writeHealthLine(stdout, run.Counts) } // renderSection renders one input XR's section: its header and health, then // its error, or its diffs, unhealthy resources without changes and summary, // or "No changes." with those resources. It returns the section's counts, -// zero for an errored XR. Its unhealthy resources skip the keys in skip, -// which another section lists. -func (r *DefaultDiffRenderer) renderSection(g dt.XRDiffGroup, skip map[string]bool) (diffCounts, error) { +// zero for an errored XR. Its unhealthy resources are those of g's composed +// at the indexes in owned, the ones its section lists in the run's health. +func (r *DefaultDiffRenderer) renderSection(g dt.XRDiffGroup, owned []int) (diffCounts, error) { stdout := r.diffOpts.Stdout if _, err := fmt.Fprintf(stdout, "=== %s ===\n\n", groupTitle(g)); err != nil { @@ -456,7 +453,7 @@ func (r *DefaultDiffRenderer) renderSection(g dt.XRDiffGroup, skip map[string]bo return counts, err } - block := joinLines(unhealthyBlock(g.Health, g.Diffs, skip, r.diffOpts.FullMessages)) + block := joinLines(ownedBlock(g.Health, owned, g.Diffs, r.diffOpts.FullMessages)) if counts.output == 0 { if _, err := fmt.Fprintf(stdout, "No changes.\n\n"); err != nil { diff --git a/internal/diff/renderer/health.go b/internal/diff/renderer/health.go index deba2452f..2beefb30a 100644 --- a/internal/diff/renderer/health.go +++ b/internal/diff/renderer/health.go @@ -33,6 +33,47 @@ func refName(ref corev1.ObjectReference) string { // resource a nested composite composes is nested under that composite, as in // plan output. It skips the keys in skip, which another entry lists. func unhealthyBlock(h dt.CompositeHealth, diffs map[string]*dt.ResourceDiff, skip map[string]bool, full bool) []string { + listed := listedDiffs(diffs) + + var items []health.Item + + for _, r := range h.Composed { + id := refKey(r.ObjectReference) + if !r.Health.Unhealthy() || listed[id] != "" || skip[id] { + continue + } + + items = append(items, blockItem(r)) + } + + return health.Block(items, listed, full) +} + +// ownedBlock returns the lines listing the resources of h.Composed at the +// indexes in owned, the unhealthy ones its entry lists in the run's health, +// that have no changes in diffs, or nil when there is nothing. A resource a +// nested composite composes is nested under that composite, as in plan +// output. +func ownedBlock(h dt.CompositeHealth, owned []int, diffs map[string]*dt.ResourceDiff, full bool) []string { + listed := listedDiffs(diffs) + + var items []health.Item + + for _, j := range owned { + r := h.Composed[j] + if listed[refKey(r.ObjectReference)] != "" { + continue + } + + items = append(items, blockItem(r)) + } + + return health.Block(items, listed, full) +} + +// listedDiffs returns, by key, how the diff list names each resource in diffs +// with changes. +func listedDiffs(diffs map[string]*dt.ResourceDiff) map[string]string { listed := map[string]string{} for _, d := range diffs { @@ -41,23 +82,47 @@ func unhealthyBlock(h dt.CompositeHealth, diffs map[string]*dt.ResourceDiff, ski } } - var items []health.Item + return listed +} - for _, r := range h.Composed { - id := refKey(r.ObjectReference) - if !r.Health.Unhealthy() || listed[id] != "" || skip[id] { +// blockItem returns r as an item of an unhealthy block. +func blockItem(r dt.ResourceHealth) health.Item { + it := health.Item{ID: refKey(r.ObjectReference), Name: refName(r.ObjectReference), Health: r.Health} + if r.Via != nil { + it.Via, it.ViaName = refKey(*r.Via), refName(*r.Via) + } + + return it +} + +// groupsRun returns the run's health for groups: opts' when set, else one +// built from groups, each a composite, which show their diffs themselves. An +// identity-less group is an empty composite, so it counts nothing. +func groupsRun(opts DiffOptions, groups []dt.XRDiffGroup) health.Run { + if opts.Health != nil { + return *opts.Health + } + + composites := make([]health.Composite, len(groups)) + + var shown []health.Item + + for i, g := range groups { + if !hasIdentity(g) { continue } - it := health.Item{ID: id, Name: refName(r.ObjectReference), Health: r.Health} - if r.Via != nil { - it.Via, it.ViaName = refKey(*r.Via), refName(*r.Via) + composites[i] = health.Composite{Key: refKey(g.XR), Health: g.Health.XR} + for _, r := range g.Health.Composed { + composites[i].Composed = append(composites[i].Composed, health.Item{ID: refKey(r.ObjectReference), Health: r.Health}) } - items = append(items, it) + for _, d := range g.Diffs { + shown = append(shown, health.Item{ID: diffKey(d), Health: health.Of(d.Current.Raw)}) + } } - return health.Block(items, listed, full) + return health.Build(composites, shown) } // joinLines returns lines, each ended by a newline, or "" when there are @@ -112,8 +177,8 @@ func tallyComposite(t *health.Tally, ref corev1.ObjectReference, h dt.CompositeH // writeHealthLine writes the run's Health: line to w, or nothing when nothing // in it is unhealthy. -func writeHealthLine(w io.Writer, t *health.Tally) error { - line := health.SummaryLine(t.Counts()) +func writeHealthLine(w io.Writer, c health.Counts) error { + line := health.SummaryLine(c) if line == "" { return nil } @@ -122,19 +187,3 @@ func writeHealthLine(w io.Writer, t *health.Tally) error { return errors.Wrap(err, "cannot write health summary") } - -// groupsOwnedElsewhere returns, by group index, the keys each group's -// unhealthy block skips: a nested XR given as an input with health of its own -// lists what it composes, so its parent lists neither, as in plan output. -func groupsOwnedElsewhere(groups []dt.XRDiffGroup) []map[string]bool { - entries := make([]health.Entry, len(groups)) - - for i, g := range groups { - entries[i] = health.Entry{Key: refKey(g.XR), HasHealth: g.Health.XR != nil} - for _, c := range g.Health.Composed { - entries[i].Composes = append(entries[i].Composes, refKey(c.ObjectReference)) - } - } - - return health.OwnedElsewhere(entries) -} diff --git a/internal/simulate/report.go b/internal/simulate/report.go index 245d388ce..c116dcf10 100644 --- a/internal/simulate/report.go +++ b/internal/simulate/report.go @@ -286,14 +286,33 @@ func (a *assembler) unhealthy(run health.Run) { // run builds the run's health from every composite, what it composed, and // the plans. func (a *assembler) run() health.Run { - composites := make([]health.Composite, len(a.composites)) - for i, c := range a.composites { - composites[i] = health.Composite{Key: healthKey(c.Ref), Health: c.Health} - for _, r := range a.composed[i] { - composites[i].Composed = append(composites[i].Composed, health.Item{ID: health.Key(r.APIVersion, r.Kind, r.Namespace, r.Name), Health: r.Health}) + return buildRun(a.composites, a.composed, a.plans) +} + +// buildRun builds a run's health from its composites, what each composed, by +// index, and its plans. +func buildRun(composites []CompositeResult, composed [][]dt.ResourceHealth, plans []*plan.ResourcePlan) health.Run { + cs := make([]health.Composite, len(composites)) + for i, c := range composites { + cs[i] = health.Composite{Key: healthKey(c.Ref), Health: c.Health} + for _, r := range composed[i] { + cs[i].Composed = append(cs[i].Composed, health.Item{ID: health.Key(r.APIVersion, r.Kind, r.Namespace, r.Name), Health: r.Health}) + } + } + return health.Build(cs, planItems(plans)) +} + +// xrRun returns the Run FromXRReport built res's health from, given the +// report r it came from: one composite per group of r, in order, as the xr +// diff renderer indexes them. +func xrRun(r *dt.XRReport, res Result) health.Run { + var composed [][]dt.ResourceHealth + if r != nil { + for _, g := range r.Groups { + composed = append(composed, g.Health.Composed) } } - return health.Build(composites, planItems(a.plans)) + return buildRun(res.Composites, composed, res.Plans) } // addDiffs adds a plan per diff, in the structured renderer's canonical order. diff --git a/internal/simulate/report_test.go b/internal/simulate/report_test.go index e349fdf88..284f35401 100644 --- a/internal/simulate/report_test.go +++ b/internal/simulate/report_test.go @@ -659,8 +659,10 @@ func TestHealth(t *testing.T) { plans map[string]*health.Health // plan name -> health composites []CompositeResult summary plan.HealthSummary - // diffLine, when set, is the Health: line -o diff prints for args.xr. - diffLine string + // diffLine, when checkDiff is set, is the Health: line -o diff prints + // for args.xr. + diffLine string + checkDiff bool } type args struct { xr *dt.XRReport @@ -831,7 +833,7 @@ func TestHealth(t *testing.T) { }, "EqualKeptForMissingProviderPlan": { reason: "An unhealthy equal diff kept only for a provider plan that has none, and composed by no entry, is dropped from the plans, so summary.health and exit bit 4 miss it; " + - "the -o diff Health: line still counts it as failing. Pinned as today's divergence (design open question f).", + "the -o diff Health: line now counts plans, the same as JSON (D-1), so it prints none.", args: args{ xr: &dt.XRReport{Groups: []dt.XRDiffGroup{{ XR: xrRef, @@ -842,7 +844,7 @@ func TestHealth(t *testing.T) { want: want{ plans: map[string]*health.Health{}, composites: []CompositeResult{{Ref: xrPlan, Status: CompositeUnchanged}}, - diffLine: "Health: 1 resource failing (Synced=False).", + checkDiff: true, }, }, } @@ -871,10 +873,12 @@ func TestHealth(t *testing.T) { if line, want := got.HealthLine(), anyFailing(got); got.Failing() != want { t.Errorf("%s\nFailing(): want %t, got %t; HealthLine() is %q", tc.reason, want, got.Failing(), line) } - if tc.want.diffLine != "" { + if tc.want.checkDiff { var buf bytes.Buffer opts := renderer.DefaultDiffOptions() opts.Stdout, opts.Stderr = &buf, &bytes.Buffer{} + run := xrRun(tc.args.xr, got) + opts.Health = &run r := AnnotateXRReport(tc.args.xr, nil) if err := renderer.NewDiffRenderer(tu.TestLogger(t, false), opts).RenderDiffs(r.Groups, r.Errors, r.Warnings); err != nil { t.Fatalf("%s\nRenderDiffs(...): unexpected error: %v", tc.reason, err) diff --git a/internal/simulate/run.go b/internal/simulate/run.go index d063eafe8..510c8f614 100644 --- a/internal/simulate/run.go +++ b/internal/simulate/run.go @@ -516,7 +516,11 @@ func (c *Runner) notes() []string { // renderReport does. func (c *Runner) renderXRReport(k *kong.Context, logger logging.Logger, r *dt.XRReport, runErr error) (outcome, error) { plans := c.providerPlans() - return c.renderReport(k, logger, runErr, FromXRReport(r, plans, c.keep), r.HasChanges(), dt.XRDryRunWarnings(r.Groups), func(opts renderer.DiffOptions) error { + res := FromXRReport(r, plans, c.keep) + return c.renderReport(k, logger, runErr, res, r.HasChanges(), dt.XRDryRunWarnings(r.Groups), func(opts renderer.DiffOptions) error { + // The Health: line counts the plans, as summary.health does. + run := xrRun(r, res) + opts.Health = &run // Annotated even without plans, so a Secret's values are redacted. r = AnnotateXRReport(r, plans) return renderer.NewDiffRenderer(logger, opts).RenderDiffs(r.Groups, r.Errors, r.Warnings) From e2caf9eede753ece2e6e8b1c4f5b12903c7b8c33 Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 3 Dec 2026 18:18:07 -0500 Subject: [PATCH 11/16] refactor(renderer): render composition diff health from the run's model The composition -o diff renderer reads one health.Run, passed in through DiffOptions.Health, for which XR lists each unhealthy resource and for the Health: line, with one composite per impact of every composition in run order. renderCompReport builds it with compRun from the Result's composites and plans. tallyComposite, unhealthyOwnedElsewhere and the renderer's unhealthyBlock lose their last callers and go. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/diff/renderer/comp_diff_renderer.go | 83 +++++++++++--------- internal/diff/renderer/diff_formatter.go | 7 +- internal/diff/renderer/health.go | 39 --------- internal/simulate/report.go | 15 ++++ internal/simulate/run.go | 6 +- 5 files changed, 68 insertions(+), 82 deletions(-) diff --git a/internal/diff/renderer/comp_diff_renderer.go b/internal/diff/renderer/comp_diff_renderer.go index 424038944..817fe4247 100644 --- a/internal/diff/renderer/comp_diff_renderer.go +++ b/internal/diff/renderer/comp_diff_renderer.go @@ -67,7 +67,8 @@ func NewDefaultCompDiffRenderer(logger logging.Logger, diffRenderer DiffRenderer // to r.opts.Stdout. Top-level errors are not printed; see CompDiffRenderer. func (r *DefaultCompDiffRenderer) RenderCompDiff(output *dt.CompDiffOutput) error { stdout := r.opts.Stdout - ownedElsewhere := unhealthyOwnedElsewhere(output.Compositions) + run := compRun(r.opts, output.Compositions) + base := 0 for i, comp := range output.Compositions { if i > 0 { @@ -76,21 +77,16 @@ func (r *DefaultCompDiffRenderer) RenderCompDiff(output *dt.CompDiffOutput) erro } } - if err := r.renderComposition(&comp, ownedElsewhere); err != nil { + owned := run.Owned[base : base+len(comp.ImpactAnalysis)] + base += len(comp.ImpactAnalysis) + + if err := r.renderComposition(&comp, owned); err != nil { return err } } // What is not healthy before apply is summarized once for the run, as in plan output. - var t health.Tally - - for _, comp := range output.Compositions { - for _, impact := range comp.ImpactAnalysis { - tallyComposite(&t, impact.ObjectReference, impact.Health, impact.Diffs) - } - } - - if line := health.SummaryLine(t.Counts()); line != "" { + if line := health.SummaryLine(run.Counts); line != "" { if _, err := fmt.Fprintf(stdout, "\n%s\n", line); err != nil { return errors.Wrap(err, "cannot write health summary") } @@ -105,7 +101,7 @@ func (r *DefaultCompDiffRenderer) RenderCompDiff(output *dt.CompDiffOutput) erro // followed — only if it processed successfully — by the sections describing its effect on composites. // A composition that failed to process has no such sections to show; renderCompositionChanges // reported the error in their place. -func (r *DefaultCompDiffRenderer) renderComposition(comp *dt.CompositionDiff, ownedElsewhere map[string]map[string]bool) error { +func (r *DefaultCompDiffRenderer) renderComposition(comp *dt.CompositionDiff, owned [][]int) error { switch { case r.opts.MinimizeComposition: if err := r.renderMinimizedCompositionChanges(comp); err != nil { @@ -118,7 +114,7 @@ func (r *DefaultCompDiffRenderer) renderComposition(comp *dt.CompositionDiff, ow } if comp.Error == nil { - return r.renderCompositionImpact(comp, ownedElsewhere) + return r.renderCompositionImpact(comp, owned) } return nil @@ -127,7 +123,7 @@ func (r *DefaultCompDiffRenderer) renderComposition(comp *dt.CompositionDiff, ow // renderCompositionImpact renders the sections describing how a composition affects its composites: // either the note standing in for them when their evaluation was skipped, or the affected-XR list and // the downstream impact analysis. -func (r *DefaultCompDiffRenderer) renderCompositionImpact(comp *dt.CompositionDiff, ownedElsewhere map[string]map[string]bool) error { +func (r *DefaultCompDiffRenderer) renderCompositionImpact(comp *dt.CompositionDiff, owned [][]int) error { if comp.ImpactAnalysisSkipped { return r.renderSkippedComposition(comp) } @@ -144,7 +140,7 @@ func (r *DefaultCompDiffRenderer) renderCompositionImpact(comp *dt.CompositionDi } // Render impact analysis (downstream diffs) - return r.renderImpactAnalysis(comp, ownedElsewhere) + return r.renderImpactAnalysis(comp, owned) } // renderSkippedComposition stands in for the affected-XR and impact-analysis sections when a @@ -421,7 +417,7 @@ func (r *DefaultCompDiffRenderer) renderAffectedResourcesList(comp *dt.Compositi } // renderImpactAnalysis renders the impact analysis section with downstream diffs. -func (r *DefaultCompDiffRenderer) renderImpactAnalysis(comp *dt.CompositionDiff, ownedElsewhere map[string]map[string]bool) error { +func (r *DefaultCompDiffRenderer) renderImpactAnalysis(comp *dt.CompositionDiff, owned [][]int) error { stdout := r.opts.Stdout if _, err := fmt.Fprintf(stdout, headerImpactAnalysis+"\n\n"); err != nil { @@ -456,18 +452,22 @@ func (r *DefaultCompDiffRenderer) renderImpactAnalysis(comp *dt.CompositionDiff, } } - return r.renderUnhealthyBlocks(comp, ownedElsewhere, len(allDiffs) > 0) + return r.renderUnhealthyBlocks(comp, owned, len(allDiffs) > 0) } // renderUnhealthyBlocks writes, for each composite the composition affects, // the resources it composes that are not healthy and have no changes, under a // line naming the composite. afterDiffs separates the first from the diffs // above it. -func (r *DefaultCompDiffRenderer) renderUnhealthyBlocks(comp *dt.CompositionDiff, ownedElsewhere map[string]map[string]bool, afterDiffs bool) error { +func (r *DefaultCompDiffRenderer) renderUnhealthyBlocks(comp *dt.CompositionDiff, owned [][]int, afterDiffs bool) error { var sb strings.Builder - for _, impact := range listedImpacts(comp) { - block := unhealthyBlock(impact.Health, impact.Diffs, ownedElsewhere[refKey(impact.ObjectReference)], r.opts.FullMessages) + for i, impact := range comp.ImpactAnalysis { + if !comp.Scoped && impact.Status == dt.XRStatusFiltered { + continue // not listed; see listedImpacts + } + + block := ownedBlock(impact.Health, owned[i], impact.Diffs, r.opts.FullMessages) if len(block) == 0 { continue } @@ -486,30 +486,35 @@ func (r *DefaultCompDiffRenderer) renderUnhealthyBlocks(comp *dt.CompositionDiff return write(r.opts.Stdout, sb.String()) } -// unhealthyOwnedElsewhere returns, by the key of each composite the run lists, -// the keys its unhealthy block skips: a nested XR the run lists with health -// of its own, in any composition, lists what it composes, so its parent lists -// neither, as in plan output. -func unhealthyOwnedElsewhere(comps []dt.CompositionDiff) map[string]map[string]bool { - var entries []health.Entry - - for i := range comps { - for _, impact := range listedImpacts(&comps[i]) { - e := health.Entry{Key: refKey(impact.ObjectReference), HasHealth: impact.Health.XR != nil} - for _, c := range impact.Health.Composed { - e.Composes = append(e.Composes, refKey(c.ObjectReference)) +// compRun returns the run's health for comps: opts' when set, else one built +// from every impact of each composition in order, each a composite, which +// shows its diffs itself. +func compRun(opts DiffOptions, comps []dt.CompositionDiff) health.Run { + if opts.Health != nil { + return *opts.Health + } + + var ( + composites []health.Composite + shown []health.Item + ) + + for _, comp := range comps { + for _, impact := range comp.ImpactAnalysis { + c := health.Composite{Key: refKey(impact.ObjectReference), Health: impact.Health.XR} + for _, r := range impact.Health.Composed { + c.Composed = append(c.Composed, health.Item{ID: refKey(r.ObjectReference), Health: r.Health}) } - entries = append(entries, e) - } - } + composites = append(composites, c) - out := map[string]map[string]bool{} - for i, skip := range health.OwnedElsewhere(entries) { - out[entries[i].Key] = skip + for _, d := range impact.Diffs { + shown = append(shown, health.Item{ID: diffKey(d), Health: health.Of(d.Current.Raw)}) + } + } } - return out + return health.Build(composites, shown) } // impactTitle names an affected composite, e.g. "XNetwork/prod/net", as the diff --git a/internal/diff/renderer/diff_formatter.go b/internal/diff/renderer/diff_formatter.go index c00846d7d..b199c686d 100644 --- a/internal/diff/renderer/diff_formatter.go +++ b/internal/diff/renderer/diff_formatter.go @@ -56,9 +56,10 @@ type DiffOptions struct { // than cut to one line. FullMessages bool - // Health, when set, is the run's health, one composite per group of the - // xr diff in order: which group lists each unhealthy resource, and the - // Health: line's counts. Nil builds it from the groups. + // Health, when set, is the run's health: one composite per group of the + // xr diff, or per impact of each composition of the composition diff, in + // order. It gives which composite lists each unhealthy resource, and the + // Health: line's counts. Nil builds it from the groups or impacts. Health *health.Run } diff --git a/internal/diff/renderer/health.go b/internal/diff/renderer/health.go index 2beefb30a..eb421a90a 100644 --- a/internal/diff/renderer/health.go +++ b/internal/diff/renderer/health.go @@ -28,27 +28,6 @@ func refName(ref corev1.ObjectReference) string { return ref.Kind + "/" + ref.Name } -// unhealthyBlock returns the lines listing what a composite composes that is -// not healthy and has no changes in diffs, or nil when there is nothing. A -// resource a nested composite composes is nested under that composite, as in -// plan output. It skips the keys in skip, which another entry lists. -func unhealthyBlock(h dt.CompositeHealth, diffs map[string]*dt.ResourceDiff, skip map[string]bool, full bool) []string { - listed := listedDiffs(diffs) - - var items []health.Item - - for _, r := range h.Composed { - id := refKey(r.ObjectReference) - if !r.Health.Unhealthy() || listed[id] != "" || skip[id] { - continue - } - - items = append(items, blockItem(r)) - } - - return health.Block(items, listed, full) -} - // ownedBlock returns the lines listing the resources of h.Composed at the // indexes in owned, the unhealthy ones its entry lists in the run's health, // that have no changes in diffs, or nil when there is nothing. A resource a @@ -157,24 +136,6 @@ func healthDescription(h *health.Health, full bool) []string { return lines } -// tallyComposite adds a top-level composite with ref and health h, and what -// it composes, to t. A composite without health, as one not yet in the -// cluster or whose processing errored, is not counted as a composite, as in -// plan output; where its parent composes it, it counts as a resource. -func tallyComposite(t *health.Tally, ref corev1.ObjectReference, h dt.CompositeHealth, diffs map[string]*dt.ResourceDiff) { - if h.XR != nil { - t.Composite(refKey(ref), h.XR) - } - - for _, d := range diffs { - t.Resource(diffKey(d), health.Of(d.Current.Raw)) - } - - for _, r := range h.Composed { - t.Resource(refKey(r.ObjectReference), r.Health) - } -} - // writeHealthLine writes the run's Health: line to w, or nothing when nothing // in it is unhealthy. func writeHealthLine(w io.Writer, c health.Counts) error { diff --git a/internal/simulate/report.go b/internal/simulate/report.go index c116dcf10..6b1cdc7c2 100644 --- a/internal/simulate/report.go +++ b/internal/simulate/report.go @@ -315,6 +315,21 @@ func xrRun(r *dt.XRReport, res Result) health.Run { return buildRun(res.Composites, composed, res.Plans) } +// compRun returns the Run FromCompReport built res's health from, given the +// report o it came from: one composite per impact of each composition of o, +// in order, as the composition diff renderer indexes them. +func compRun(o *dt.CompDiffOutput, res Result) health.Run { + var composed [][]dt.ResourceHealth + if o != nil { + for _, comp := range o.Compositions { + for _, impact := range comp.ImpactAnalysis { + composed = append(composed, impact.Health.Composed) + } + } + } + return buildRun(res.Composites, composed, res.Plans) +} + // 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/run.go b/internal/simulate/run.go index 510c8f614..111fc0897 100644 --- a/internal/simulate/run.go +++ b/internal/simulate/run.go @@ -531,8 +531,12 @@ func (c *Runner) renderXRReport(k *kong.Context, logger logging.Logger, r *dt.XR // selects, as renderReport does. func (c *Runner) renderCompReport(k *kong.Context, logger logging.Logger, o *dt.CompDiffOutput, runErr error) (outcome, error) { plans := c.providerPlans() - return c.renderReport(k, logger, runErr, FromCompReport(o, plans, c.keep), o.HasChanges(), dt.CompDryRunWarnings(o), func(opts renderer.DiffOptions) error { + res := FromCompReport(o, plans, c.keep) + return c.renderReport(k, logger, runErr, res, o.HasChanges(), dt.CompDryRunWarnings(o), func(opts renderer.DiffOptions) error { opts.MinimizeComposition = c.sel.MinimizeComposition + // The Health: line counts the plans, as summary.health does. + run := compRun(o, res) + opts.Health = &run // Annotated even without plans, so a Secret's values are redacted. o = AnnotateCompReport(o, plans) return renderer.NewDefaultCompDiffRenderer(logger, renderer.NewDiffRenderer(logger, opts), opts).RenderCompDiff(o) From 7d23231cd1ae7b3c8ad2f9e836591ab3fd73c834 Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Thu, 3 Dec 2026 18:28:40 -0500 Subject: [PATCH 12/16] refactor(health): delete render-time health tallies Delete plan.HealthCounts and plan.Failing; tests read plan.HealthRun instead. Pin that plans with no kind and no name each count on their own. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- cmd/crossplane/simulate/simulate_test.go | 2 +- internal/plan/output.go | 20 -------------------- internal/plan/output_test.go | 18 +++++++++++++----- 3 files changed, 14 insertions(+), 26 deletions(-) diff --git a/cmd/crossplane/simulate/simulate_test.go b/cmd/crossplane/simulate/simulate_test.go index 87ab3b955..c327ad058 100644 --- a/cmd/crossplane/simulate/simulate_test.go +++ b/cmd/crossplane/simulate/simulate_test.go @@ -119,7 +119,7 @@ func TestExitStatus(t *testing.T) { if diff := cmp.Diff(tc.want, got); diff != "" { t.Errorf("\n%s\nexitStatus(...): -want exit code, +got:\n%s", tc.reason, diff) } - if bit, line := got != 1 && got&isimulate.ExitCodeFailing != 0, plan.HealthCounts(tc.args.plans).Failing > 0 && got != 1; bit != line { + if bit, line := got != 1 && got&isimulate.ExitCodeFailing != 0, plan.HealthRun(tc.args.plans).Counts.Failing > 0 && got != 1; bit != line { t.Errorf("\n%s\nexit bit 4 = %t, but the Health: line counts failing = %t", tc.reason, bit, line) } }) diff --git a/internal/plan/output.go b/internal/plan/output.go index 9e870d816..f9e2ec6eb 100644 --- a/internal/plan/output.go +++ b/internal/plan/output.go @@ -114,26 +114,6 @@ type HealthSummary struct { Paused int `json:"paused"` } -// HealthCounts returns the health counts of plans: each resource once, under -// the state its first plan reports, matched across API versions. -func HealthCounts(plans []*ResourcePlan) health.Counts { - t := &health.Tally{} - for _, p := range plans { - ns := p.Namespace - if p.LiveNamespace != "" { - ns = p.LiveNamespace - } - t.Resource(health.Key(p.APIVersion, p.Kind, ns, p.Name), p.Health) - } - return t.Counts() -} - -// Failing reports whether any plan's resource is failing, which sets exit -// bit 4. -func Failing(plans []*ResourcePlan) bool { - return slices.ContainsFunc(plans, func(p *ResourcePlan) bool { return p.Health != nil && p.Health.State == health.Failing }) -} - // HealthRun returns the run's health: plans are the resources it shows, with // no composites of its own. func HealthRun(plans []*ResourcePlan) health.Run { diff --git a/internal/plan/output_test.go b/internal/plan/output_test.go index 9129667b9..ef52a3468 100644 --- a/internal/plan/output_test.go +++ b/internal/plan/output_test.go @@ -464,8 +464,8 @@ Health: 1 resource failing (Synced=False). if diff := cmp.Diff(tc.want, buf.String()); diff != "" { t.Errorf("\n%s\nRender(plan): -want, +got:\n%s", tc.reason, diff) } - if got, line := Failing(tc.args.plans), HealthCounts(tc.args.plans).Failing > 0; got != line { - t.Errorf("\n%s\nFailing(...) = %t, but the Health: line counts failing = %t", tc.reason, got, line) + if run := HealthRun(tc.args.plans); run.Failing != (run.Counts.Failing > 0) { + t.Errorf("\n%s\nHealthRun(...).Failing = %t, but the Health: line counts failing = %t", tc.reason, run.Failing, run.Counts.Failing > 0) } }) } @@ -652,13 +652,21 @@ func TestFailing(t *testing.T) { args: args{plans: []*ResourcePlan{{Action: ActionDelete, Health: &health.Health{State: health.Failing}}}}, want: true, }, + "FailingAmongUnnamed": { + reason: "Plans with no kind and no name each get their own key, so one failing among healthy ones is counted and failing.", + args: args{plans: []*ResourcePlan{ + {Health: ht.NewHealth(health.Healthy).Build()}, + {Health: ht.NewHealth(health.Failing).Build()}, + }}, + want: true, + }, } for name, tc := range cases { t.Run(name, func(t *testing.T) { - if diff := cmp.Diff(tc.want, Failing(tc.args.plans)); diff != "" { - t.Errorf("\n%s\nFailing(...): -want, +got:\n%s", tc.reason, diff) + if diff := cmp.Diff(tc.want, HealthRun(tc.args.plans).Failing); diff != "" { + t.Errorf("\n%s\nHealthRun(...).Failing: -want, +got:\n%s", tc.reason, diff) } - if line := HealthCounts(tc.args.plans).Failing > 0; line != tc.want { + if line := HealthRun(tc.args.plans).Counts.Failing > 0; line != tc.want { t.Errorf("\n%s\nthe Health: line counts failing = %t, want %t", tc.reason, line, tc.want) } }) From 71a28c303e9e839fc01548e6655d2d2893fac7ec Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Fri, 4 Dec 2026 11:58:41 -0500 Subject: [PATCH 13/16] refactor(simulate): keep the assembler's run on Result The assembler stores the Run it resolved Unhealthy from on Result, and the diff renderers get that exact Run. The second walk over the report (xrRun, compRun) is gone; Results without a stored Run still rebuild it from Composites. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/simulate/report.go | 43 ++++---------------------------- internal/simulate/report_test.go | 5 ++-- internal/simulate/result.go | 10 +++++++- internal/simulate/result_test.go | 5 ++-- internal/simulate/run.go | 6 ++--- 5 files changed, 21 insertions(+), 48 deletions(-) diff --git a/internal/simulate/report.go b/internal/simulate/report.go index 6b1cdc7c2..30f7b6815 100644 --- a/internal/simulate/report.go +++ b/internal/simulate/report.go @@ -286,48 +286,14 @@ func (a *assembler) unhealthy(run health.Run) { // run builds the run's health from every composite, what it composed, and // the plans. func (a *assembler) run() health.Run { - return buildRun(a.composites, a.composed, a.plans) -} - -// buildRun builds a run's health from its composites, what each composed, by -// index, and its plans. -func buildRun(composites []CompositeResult, composed [][]dt.ResourceHealth, plans []*plan.ResourcePlan) health.Run { - cs := make([]health.Composite, len(composites)) - for i, c := range composites { + cs := make([]health.Composite, len(a.composites)) + for i, c := range a.composites { cs[i] = health.Composite{Key: healthKey(c.Ref), Health: c.Health} - for _, r := range composed[i] { + for _, r := range a.composed[i] { cs[i].Composed = append(cs[i].Composed, health.Item{ID: health.Key(r.APIVersion, r.Kind, r.Namespace, r.Name), Health: r.Health}) } } - return health.Build(cs, planItems(plans)) -} - -// xrRun returns the Run FromXRReport built res's health from, given the -// report r it came from: one composite per group of r, in order, as the xr -// diff renderer indexes them. -func xrRun(r *dt.XRReport, res Result) health.Run { - var composed [][]dt.ResourceHealth - if r != nil { - for _, g := range r.Groups { - composed = append(composed, g.Health.Composed) - } - } - return buildRun(res.Composites, composed, res.Plans) -} - -// compRun returns the Run FromCompReport built res's health from, given the -// report o it came from: one composite per impact of each composition of o, -// in order, as the composition diff renderer indexes them. -func compRun(o *dt.CompDiffOutput, res Result) health.Run { - var composed [][]dt.ResourceHealth - if o != nil { - for _, comp := range o.Compositions { - for _, impact := range comp.ImpactAnalysis { - composed = append(composed, impact.Health.Composed) - } - } - } - return buildRun(res.Composites, composed, res.Plans) + return health.Build(cs, planItems(a.plans)) } // addDiffs adds a plan per diff, in the structured renderer's canonical order. @@ -461,6 +427,7 @@ func (a *assembler) result(warnings []dt.OutputWarning) Result { run := a.run() a.unhealthy(run) res := NewResult(a.plans, a.composites, a.errors) + res.run = &run if a.provider == nil { res.Notes = []string{noteProviderPlanNotRun} } diff --git a/internal/simulate/report_test.go b/internal/simulate/report_test.go index 284f35401..8edf0918d 100644 --- a/internal/simulate/report_test.go +++ b/internal/simulate/report_test.go @@ -323,7 +323,7 @@ func TestFromCompReport(t *testing.T) { for name, tc := range cases { t.Run(name, func(t *testing.T) { got := FromCompReport(tc.in, nil, nil) - if diff := cmp.Diff(tc.want, got, cmpopts.IgnoreFields(plan.ResourcePlan{}, "Before", "After"), cmpopts.EquateEmpty()); diff != "" { + if diff := cmp.Diff(tc.want, got, cmpopts.IgnoreFields(plan.ResourcePlan{}, "Before", "After"), cmpopts.EquateEmpty(), cmpopts.IgnoreUnexported(Result{})); diff != "" { t.Errorf("%s\nFromCompReport(...): -want, +got:\n%s", tc.reason, diff) } }) @@ -877,8 +877,7 @@ func TestHealth(t *testing.T) { var buf bytes.Buffer opts := renderer.DefaultDiffOptions() opts.Stdout, opts.Stderr = &buf, &bytes.Buffer{} - run := xrRun(tc.args.xr, got) - opts.Health = &run + opts.Health = got.run r := AnnotateXRReport(tc.args.xr, nil) if err := renderer.NewDiffRenderer(tu.TestLogger(t, false), opts).RenderDiffs(r.Groups, r.Errors, r.Warnings); err != nil { t.Fatalf("%s\nRenderDiffs(...): unexpected error: %v", tc.reason, err) diff --git a/internal/simulate/result.go b/internal/simulate/result.go index e16cad414..e899d9288 100644 --- a/internal/simulate/result.go +++ b/internal/simulate/result.go @@ -181,6 +181,10 @@ type Result struct { // Notes are statements about how the result was produced, e.g. that the // provider plans did not run. Notes []string `json:"notes,omitempty"` + + // run is the run's health the assembler resolved Unhealthy from; nil + // for a Result it didn't build. + run *health.Run } // NewResult assembles the Result for the given plans and @@ -211,12 +215,16 @@ func (r Result) Health() plan.HealthSummary { return plan.HealthSummary{Composites: c.UnhealthyComposites, Failing: c.Failing, NotReady: c.NotReady, Paused: c.Paused} } -// healthRun builds the run's health from Composites and Plans. Each +// healthRun returns the run's health: the Run the assembler stored, else +// one built from Composites and Plans. Each // Unhealthy list is already resolved, which Build leaves as it is, so this // matches the Run the assembler built them from. A composite with no health of its own here (one not // simulated) isn't added as a composite, so it counts as a resource where its // parent lists it, if anywhere. func (r Result) healthRun() health.Run { + if r.run != nil { + return *r.run + } composites := make([]health.Composite, len(r.Composites)) for i, c := range r.Composites { composites[i] = health.Composite{Key: healthKey(c.Ref), Health: c.Health} diff --git a/internal/simulate/result_test.go b/internal/simulate/result_test.go index 7c29f5d86..8345976c3 100644 --- a/internal/simulate/result_test.go +++ b/internal/simulate/result_test.go @@ -23,6 +23,7 @@ import ( "testing" "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" corev1 "k8s.io/api/core/v1" dt "github.com/crossplane/cli/v2/internal/diff/result" @@ -208,7 +209,7 @@ func TestRenderJSONProjectFields(t *testing.T) { if err := json.Unmarshal(buf.Bytes(), &got); err != nil { t.Fatalf("Render(json): output is not valid JSON: %v", err) } - if diff := cmp.Diff(in, got); diff != "" { + if diff := cmp.Diff(in, got, cmpopts.IgnoreUnexported(Result{})); diff != "" { t.Errorf("Render(json): -want, +got:\n%s", diff) } @@ -414,7 +415,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.args.in, back); diff != "" { + if diff := cmp.Diff(tc.args.in, back, cmpopts.IgnoreUnexported(Result{})); diff != "" { t.Errorf("%s\nRender(json) round trip: -want, +got:\n%s", tc.reason, diff) } }) diff --git a/internal/simulate/run.go b/internal/simulate/run.go index 111fc0897..d084a421c 100644 --- a/internal/simulate/run.go +++ b/internal/simulate/run.go @@ -519,8 +519,7 @@ func (c *Runner) renderXRReport(k *kong.Context, logger logging.Logger, r *dt.XR res := FromXRReport(r, plans, c.keep) return c.renderReport(k, logger, runErr, res, r.HasChanges(), dt.XRDryRunWarnings(r.Groups), func(opts renderer.DiffOptions) error { // The Health: line counts the plans, as summary.health does. - run := xrRun(r, res) - opts.Health = &run + opts.Health = res.run // Annotated even without plans, so a Secret's values are redacted. r = AnnotateXRReport(r, plans) return renderer.NewDiffRenderer(logger, opts).RenderDiffs(r.Groups, r.Errors, r.Warnings) @@ -535,8 +534,7 @@ func (c *Runner) renderCompReport(k *kong.Context, logger logging.Logger, o *dt. return c.renderReport(k, logger, runErr, res, o.HasChanges(), dt.CompDryRunWarnings(o), func(opts renderer.DiffOptions) error { opts.MinimizeComposition = c.sel.MinimizeComposition // The Health: line counts the plans, as summary.health does. - run := compRun(o, res) - opts.Health = &run + opts.Health = res.run // Annotated even without plans, so a Secret's values are redacted. o = AnnotateCompReport(o, plans) return renderer.NewDefaultCompDiffRenderer(logger, renderer.NewDiffRenderer(logger, opts), opts).RenderCompDiff(o) From bcf1c9c33cd62650d342b4e3acc12f55677c582f Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Fri, 4 Dec 2026 12:00:53 -0500 Subject: [PATCH 14/16] refactor(renderer): print no health without the run's health With DiffOptions.Health nil the diff renderers print no Health: line and no unhealthy blocks, so the run's model is the only count source. The groupsRun and compRun fallbacks are deleted; the renderer tests build the run's health with health.Build. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/diff/renderer/comp_diff_renderer.go | 46 ++++----------- internal/diff/renderer/diff_formatter.go | 3 +- internal/diff/renderer/diff_renderer.go | 19 ++++-- internal/diff/renderer/health.go | 34 ++++------- internal/diff/renderer/health_test.go | 62 +++++++++++++++++++- 5 files changed, 98 insertions(+), 66 deletions(-) diff --git a/internal/diff/renderer/comp_diff_renderer.go b/internal/diff/renderer/comp_diff_renderer.go index 817fe4247..c45e3f115 100644 --- a/internal/diff/renderer/comp_diff_renderer.go +++ b/internal/diff/renderer/comp_diff_renderer.go @@ -67,7 +67,16 @@ func NewDefaultCompDiffRenderer(logger logging.Logger, diffRenderer DiffRenderer // to r.opts.Stdout. Top-level errors are not printed; see CompDiffRenderer. func (r *DefaultCompDiffRenderer) RenderCompDiff(output *dt.CompDiffOutput) error { stdout := r.opts.Stdout - run := compRun(r.opts, output.Compositions) + impacts := 0 + for _, comp := range output.Compositions { + impacts += len(comp.ImpactAnalysis) + } + + allOwned, counts, err := runHealth(r.opts, impacts) + if err != nil { + return err + } + base := 0 for i, comp := range output.Compositions { @@ -77,7 +86,7 @@ func (r *DefaultCompDiffRenderer) RenderCompDiff(output *dt.CompDiffOutput) erro } } - owned := run.Owned[base : base+len(comp.ImpactAnalysis)] + owned := allOwned[base : base+len(comp.ImpactAnalysis)] base += len(comp.ImpactAnalysis) if err := r.renderComposition(&comp, owned); err != nil { @@ -86,7 +95,7 @@ func (r *DefaultCompDiffRenderer) RenderCompDiff(output *dt.CompDiffOutput) erro } // What is not healthy before apply is summarized once for the run, as in plan output. - if line := health.SummaryLine(run.Counts); line != "" { + if line := health.SummaryLine(counts); line != "" { if _, err := fmt.Fprintf(stdout, "\n%s\n", line); err != nil { return errors.Wrap(err, "cannot write health summary") } @@ -486,37 +495,6 @@ func (r *DefaultCompDiffRenderer) renderUnhealthyBlocks(comp *dt.CompositionDiff return write(r.opts.Stdout, sb.String()) } -// compRun returns the run's health for comps: opts' when set, else one built -// from every impact of each composition in order, each a composite, which -// shows its diffs itself. -func compRun(opts DiffOptions, comps []dt.CompositionDiff) health.Run { - if opts.Health != nil { - return *opts.Health - } - - var ( - composites []health.Composite - shown []health.Item - ) - - for _, comp := range comps { - for _, impact := range comp.ImpactAnalysis { - c := health.Composite{Key: refKey(impact.ObjectReference), Health: impact.Health.XR} - for _, r := range impact.Health.Composed { - c.Composed = append(c.Composed, health.Item{ID: refKey(r.ObjectReference), Health: r.Health}) - } - - composites = append(composites, c) - - for _, d := range impact.Diffs { - shown = append(shown, health.Item{ID: diffKey(d), Health: health.Of(d.Current.Raw)}) - } - } - } - - return health.Build(composites, shown) -} - // impactTitle names an affected composite, e.g. "XNetwork/prod/net", as the // xr diff names its sections. func impactTitle(impact dt.XRImpact) string { diff --git a/internal/diff/renderer/diff_formatter.go b/internal/diff/renderer/diff_formatter.go index b199c686d..a6cb59ce3 100644 --- a/internal/diff/renderer/diff_formatter.go +++ b/internal/diff/renderer/diff_formatter.go @@ -59,7 +59,8 @@ type DiffOptions struct { // Health, when set, is the run's health: one composite per group of the // xr diff, or per impact of each composition of the composition diff, in // order. It gives which composite lists each unhealthy resource, and the - // Health: line's counts. Nil builds it from the groups or impacts. + // Health: line's counts. Nil prints no Health: line and no unhealthy + // resources blocks. Health *health.Run } diff --git a/internal/diff/renderer/diff_renderer.go b/internal/diff/renderer/diff_renderer.go index 7a603fe8b..0902b981f 100644 --- a/internal/diff/renderer/diff_renderer.go +++ b/internal/diff/renderer/diff_renderer.go @@ -294,7 +294,11 @@ func (r *DefaultDiffRenderer) renderFlat(groups, xrGroups []dt.XRDiffGroup) erro var head, block, described, healthLine string if len(xrGroups) == 1 { - run := groupsRun(r.diffOpts, groups) + owned, counts, err := runHealth(r.diffOpts, len(groups)) + if err != nil { + return err + } + i := slices.IndexFunc(groups, hasIdentity) g := groups[i] if desc := healthDescription(g.Health.XR, full); len(desc) > 0 { @@ -303,8 +307,8 @@ func (r *DefaultDiffRenderer) renderFlat(groups, xrGroups []dt.XRDiffGroup) erro described = refKey(g.XR) } - block = joinLines(ownedBlock(g.Health, run.Owned[i], g.Diffs, full)) - healthLine = joinLines([]string{health.SummaryLine(run.Counts)}) + block = joinLines(ownedBlock(g.Health, owned[i], g.Diffs, full)) + healthLine = joinLines([]string{health.SummaryLine(counts)}) } if err := write(stdout, head); err != nil { @@ -378,7 +382,10 @@ func (r *DefaultDiffRenderer) renderGrouped(groups []dt.XRDiffGroup) error { errorXR int ) - run := groupsRun(r.diffOpts, groups) + owned, healthCounts, err := runHealth(r.diffOpts, len(groups)) + if err != nil { + return err + } for i, g := range groups { // An identity-less group (should not normally be mixed in here) has no @@ -397,7 +404,7 @@ func (r *DefaultDiffRenderer) renderGrouped(groups []dt.XRDiffGroup) error { xrCount++ - counts, err := r.renderSection(g, run.Owned[i]) + counts, err := r.renderSection(g, owned[i]) if err != nil { return err } @@ -416,7 +423,7 @@ func (r *DefaultDiffRenderer) renderGrouped(groups []dt.XRDiffGroup) error { return err } - return writeHealthLine(stdout, run.Counts) + return writeHealthLine(stdout, healthCounts) } // renderSection renders one input XR's section: its header and health, then diff --git a/internal/diff/renderer/health.go b/internal/diff/renderer/health.go index eb421a90a..2d9fe6bc9 100644 --- a/internal/diff/renderer/health.go +++ b/internal/diff/renderer/health.go @@ -74,34 +74,20 @@ func blockItem(r dt.ResourceHealth) health.Item { return it } -// groupsRun returns the run's health for groups: opts' when set, else one -// built from groups, each a composite, which show their diffs themselves. An -// identity-less group is an empty composite, so it counts nothing. -func groupsRun(opts DiffOptions, groups []dt.XRDiffGroup) health.Run { - if opts.Health != nil { - return *opts.Health +// runHealth returns, for a run of n composites, which composed resources +// each lists and the Health: line's counts, from opts.Health. When it is nil +// no composite lists any and the counts are zero, so no Health: line prints. +// It returns an error when opts.Health is not for n composites. +func runHealth(opts DiffOptions, n int) ([][]int, health.Counts, error) { + if opts.Health == nil { + return make([][]int, n), health.Counts{}, nil } - composites := make([]health.Composite, len(groups)) - - var shown []health.Item - - for i, g := range groups { - if !hasIdentity(g) { - continue - } - - composites[i] = health.Composite{Key: refKey(g.XR), Health: g.Health.XR} - for _, r := range g.Health.Composed { - composites[i].Composed = append(composites[i].Composed, health.Item{ID: refKey(r.ObjectReference), Health: r.Health}) - } - - for _, d := range g.Diffs { - shown = append(shown, health.Item{ID: diffKey(d), Health: health.Of(d.Current.Raw)}) - } + if len(opts.Health.Owned) != n { + return nil, health.Counts{}, errors.Errorf("run's health has %d composites, but the report has %d", len(opts.Health.Owned), n) } - return health.Build(composites, shown) + return opts.Health.Owned, opts.Health.Counts, nil } // joinLines returns lines, each ended by a newline, or "" when there are diff --git a/internal/diff/renderer/health_test.go b/internal/diff/renderer/health_test.go index 975d15e86..abb303288 100644 --- a/internal/diff/renderer/health_test.go +++ b/internal/diff/renderer/health_test.go @@ -36,6 +36,62 @@ func equalDiffFor(kind, name string) *dt.ResourceDiff { return d } +// groupsHealth returns the run's health for groups, each a composite, which +// show their diffs themselves, as simulate builds it. An identity-less group +// is an empty composite. +func groupsHealth(groups []dt.XRDiffGroup) *health.Run { + composites := make([]health.Composite, len(groups)) + + var shown []health.Item + + for i, g := range groups { + if !hasIdentity(g) { + continue + } + + composites[i] = health.Composite{Key: refKey(g.XR), Health: g.Health.XR} + for _, r := range g.Health.Composed { + composites[i].Composed = append(composites[i].Composed, health.Item{ID: refKey(r.ObjectReference), Health: r.Health}) + } + + for _, d := range g.Diffs { + shown = append(shown, health.Item{ID: diffKey(d), Health: health.Of(d.Current.Raw)}) + } + } + + run := health.Build(composites, shown) + + return &run +} + +// compHealth returns the run's health for comps: every impact of each +// composition in order, each a composite, which shows its diffs itself. +func compHealth(comps []dt.CompositionDiff) *health.Run { + var ( + composites []health.Composite + shown []health.Item + ) + + for _, comp := range comps { + for _, impact := range comp.ImpactAnalysis { + c := health.Composite{Key: refKey(impact.ObjectReference), Health: impact.Health.XR} + for _, r := range impact.Health.Composed { + c.Composed = append(c.Composed, health.Item{ID: refKey(r.ObjectReference), Health: r.Health}) + } + + composites = append(composites, c) + + for _, d := range impact.Diffs { + shown = append(shown, health.Item{ID: diffKey(d), Health: health.Of(d.Current.Raw)}) + } + } + } + + run := health.Build(composites, shown) + + return &run +} + func TestRenderDiffsHealth(t *testing.T) { failing := &health.Health{State: health.Failing, Synced: &health.Condition{Status: "False", Reason: "ReconcileError", Message: "vpc does not exist"}} notReady := &health.Health{State: health.NotReady, Ready: &health.Condition{Status: "False", Reason: "Creating"}} @@ -368,6 +424,7 @@ Health: 1 of 1 XR unhealthy before apply; 2 resources failing (Synced=False). opts.FullMessages = tc.args.full opts.Stdout = &buf opts.Stderr = &bytes.Buffer{} + opts.Health = groupsHealth(tc.args.groups) if err := NewDiffRenderer(tu.TestLogger(t, false), opts).RenderDiffs(tc.args.groups, nil, nil); err != nil { t.Fatalf("\n%s\nRenderDiffs(...): unexpected error: %v", tc.reason, err) @@ -778,7 +835,6 @@ Health: 1 of 1 XR unhealthy before apply; 1 resource not ready. opts.UseColors = false opts.FullMessages = tc.args.full - r := NewDefaultCompDiffRenderer(tu.TestLogger(t, false), NewDiffRenderer(tu.TestLogger(t, false), opts), opts) comp := dt.CompositionDiff{ Name: "xbuckets.example.org", AffectedResources: dt.AffectedResourcesSummary{Total: 2, Unchanged: 2}, @@ -797,6 +853,10 @@ Health: 1 of 1 XR unhealthy before apply; 1 resource not ready. }) } + inner := NewDiffRenderer(tu.TestLogger(t, false), opts) + opts.Health = compHealth(comps) + r := NewDefaultCompDiffRenderer(tu.TestLogger(t, false), inner, opts) + if err := r.RenderCompDiff(&dt.CompDiffOutput{Compositions: comps}); err != nil { t.Fatalf("\n%s\nRenderCompDiff(...): unexpected error: %v", tc.reason, err) } From ecbee4b2715a5600629daa119b6a05f875c9b4ff Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Fri, 4 Dec 2026 12:03:36 -0500 Subject: [PATCH 15/16] test(simulate): render health through the run's stored model Render multi-composition and grouped xr reports through the assembler's stored Run, and pin that a Run of the wrong length is an error. The composition diff's inner renderer now gets no health, since its groups are not the run's composites. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/diff/renderer/health_test.go | 56 ++++++++ internal/simulate/health_render_test.go | 171 ++++++++++++++++++++++++ internal/simulate/run.go | 35 +++-- 3 files changed, 252 insertions(+), 10 deletions(-) create mode 100644 internal/simulate/health_render_test.go diff --git a/internal/diff/renderer/health_test.go b/internal/diff/renderer/health_test.go index abb303288..326a7f74d 100644 --- a/internal/diff/renderer/health_test.go +++ b/internal/diff/renderer/health_test.go @@ -867,3 +867,59 @@ Health: 1 of 1 XR unhealthy before apply; 1 resource not ready. }) } } + +func TestRenderHealthMismatch(t *testing.T) { + g := xrGroup("XNetwork", "net", map[string]*dt.ResourceDiff{}) + impact := dt.XRImpact{APIVersion: "example.org/v1", Kind: "XNetwork", Name: "net", Status: dt.XRStatusUnchanged} + + type args struct { + groups []dt.XRDiffGroup + comps []dt.CompositionDiff + } + cases := map[string]struct { + reason string + args args + want string + }{ + "XRDiffFlat": { + reason: "A run's health for another number of groups is an error, not a panic.", + args: args{groups: []dt.XRDiffGroup{g}}, + want: "run's health has 2 composites, but the report has 1", + }, + "XRDiffGrouped": { + reason: "A run's health for another number of groups is an error in the grouped layout too.", + args: args{groups: []dt.XRDiffGroup{g, xrGroup("XNetwork", "qa", map[string]*dt.ResourceDiff{}), xrGroup("XNetwork", "dev", map[string]*dt.ResourceDiff{})}}, + want: "run's health has 2 composites, but the report has 3", + }, + "CompDiff": { + reason: "A run's health for another number of impacts is an error, not a panic.", + args: args{comps: []dt.CompositionDiff{{Name: "net", ImpactAnalysis: []dt.XRImpact{impact}}, {Name: "other", ImpactAnalysis: []dt.XRImpact{impact, impact}}}}, + want: "run's health has 2 composites, but the report has 3", + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + opts := DefaultDiffOptions() + opts.UseColors = false + opts.Stdout, opts.Stderr = &bytes.Buffer{}, &bytes.Buffer{} + opts.Health = &health.Run{Owned: make([][]int, 2)} + + var err error + if tc.args.comps != nil { + err = NewDefaultCompDiffRenderer(tu.TestLogger(t, false), NewDiffRenderer(tu.TestLogger(t, false), opts), opts).RenderCompDiff(&dt.CompDiffOutput{Compositions: tc.args.comps}) + } else { + err = NewDiffRenderer(tu.TestLogger(t, false), opts).RenderDiffs(tc.args.groups, nil, nil) + } + + got := "" + if err != nil { + got = err.Error() + } + + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("\n%s\nRender...(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} diff --git a/internal/simulate/health_render_test.go b/internal/simulate/health_render_test.go new file mode 100644 index 000000000..f00998186 --- /dev/null +++ b/internal/simulate/health_render_test.go @@ -0,0 +1,171 @@ +/* +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 simulate + +import ( + "bytes" + "testing" + + "github.com/google/go-cmp/cmp" + corev1 "k8s.io/api/core/v1" + + "github.com/crossplane/cli/v2/internal/diff/renderer" + dt "github.com/crossplane/cli/v2/internal/diff/result" + tu "github.com/crossplane/cli/v2/internal/diff/testutils" + "github.com/crossplane/cli/v2/internal/health" + ht "github.com/crossplane/cli/v2/internal/health/healthtest" +) + +// TestRenderDiffHealth renders reports through the production path: the +// assembler, then the Run it stored, then the human diff renderer. +func TestRenderDiffHealth(t *testing.T) { + failing := ht.NewHealth(health.Failing).WithSynced(corev1.ConditionFalse, "ReconcileError", "boom").Build() + notReady := ht.NewHealth(health.NotReady).WithReady(corev1.ConditionFalse, "Creating", "").Build() + cm := func(name string) corev1.ObjectReference { + return corev1.ObjectReference{APIVersion: "v1", Kind: "ConfigMap", Name: name} + } + qaRef := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XNetwork", Name: "qa"} + child := corev1.ObjectReference{APIVersion: "example.org/v1", Kind: "XSubnet", Name: "child"} + + // Composition net reaches three nested XRs; composition other reaches the + // same top XR, and filters qa. + comp := nestedCompReport(3) + comp.Compositions = append(comp.Compositions, dt.CompositionDiff{Name: "other", ImpactAnalysis: []dt.XRImpact{ + {ObjectReference: qaRef, Status: dt.XRStatusFiltered, FilterReason: dt.FilterReasonDeleting}, + {ObjectReference: xrRef, Status: dt.XRStatusUnchanged, Health: comp.Compositions[0].ImpactAnalysis[0].Health}, + }}) + + xr := &dt.XRReport{Groups: []dt.XRDiffGroup{ + {XR: xrRef, Diffs: map[string]*dt.ResourceDiff{}, Health: dt.CompositeHealth{XR: failing, Composed: []dt.ResourceHealth{ + {ObjectReference: cm("a-cm"), Health: failing}, + {ObjectReference: child, Health: notReady}, + {ObjectReference: cm("b-cm"), Via: &child, Health: notReady}, + }}}, + {XR: qaRef, Diffs: map[string]*dt.ResourceDiff{}, Health: dt.CompositeHealth{Composed: []dt.ResourceHealth{ + {ObjectReference: cm("q-cm"), Health: notReady}, + }}}, + }} + + type args struct { + xr *dt.XRReport + comp *dt.CompDiffOutput + } + cases := map[string]struct { + reason string + args args + want string + }{ + "CompDiff": { + reason: "Each impact, nested, filtered or shared across compositions, lists the unhealthy resources the stored Run gives it, and the Health: line counts the run once.", + args: args{comp: comp}, + want: `=== Composition Changes === + +No changes detected in composition net + +=== Affected Composite Resources === + + ✓ XNetwork/prod (cluster-scoped) + ✓ XSubnet/child (cluster-scoped) ⚠ not ready (Ready=False, Creating) + ✓ XZone/grand (cluster-scoped) ⚠ failing (Synced=False, ReconcileError): boom + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XNetwork/prod + Unhealthy resources without changes: + ConfigMap/a-cm ⚠ failing (Synced=False, ReconcileError): boom + +XR: XSubnet/child + Unhealthy resources without changes: + ConfigMap/b-cm ⚠ not ready (Ready=False, Creating) + +XR: XZone/grand + Unhealthy resources without changes: + ConfigMap/c-cm ⚠ paused + +================================================================================ + +=== Composition Changes === + +No changes detected in composition other + +=== Affected Composite Resources === + + ✓ XNetwork/prod (cluster-scoped) + +=== Impact Analysis === + +All composite resources are up-to-date. No downstream resource changes detected. + +XR: XNetwork/prod + Unhealthy resources without changes: + ConfigMap/a-cm ⚠ failing (Synced=False, ReconcileError): boom + +Health: 2 of 3 XRs unhealthy before apply; 1 resource failing (Synced=False), 1 not ready, 1 paused. +`, + }, + "XRDiffGrouped": { + reason: "Each XR section lists the unhealthy resources the stored Run gives it, and the Health: line counts the run.", + args: args{xr: xr}, + want: `=== XNetwork/prod === + +⚠ failing (Synced=False, ReconcileError): boom + +No changes. + +Unhealthy resources without changes: + ConfigMap/a-cm ⚠ failing (Synced=False, ReconcileError): boom + XSubnet/child ⚠ not ready (Ready=False, Creating) + ConfigMap/b-cm ⚠ not ready (Ready=False, Creating) + +=== XNetwork/qa === + +No changes. + +Unhealthy resources without changes: + ConfigMap/q-cm ⚠ not ready (Ready=False, Creating) + +================================================================================ +Total: no changes across 2 XRs (2 unchanged) +Health: 1 of 1 XR unhealthy before apply; 1 resource failing (Synced=False), 3 not ready. +`, + }, + } + + for name, tc := range cases { + t.Run(name, func(t *testing.T) { + var buf bytes.Buffer + opts := renderer.DefaultDiffOptions() + opts.UseColors = false + opts.Stdout, opts.Stderr = &buf, &bytes.Buffer{} + + var err error + if tc.args.comp != nil { + err = renderCompDiff(tu.TestLogger(t, false), opts, tc.args.comp, nil, FromCompReport(tc.args.comp, nil, nil)) + } else { + err = renderXRDiff(tu.TestLogger(t, false), opts, tc.args.xr, nil, FromXRReport(tc.args.xr, nil, nil)) + } + if err != nil { + t.Fatalf("%s\nrender...Diff(...): unexpected error: %v", tc.reason, err) + } + if diff := cmp.Diff(tc.want, buf.String()); diff != "" { + t.Errorf("%s\nrender...Diff(...): -want, +got:\n%s", tc.reason, diff) + } + }) + } +} diff --git a/internal/simulate/run.go b/internal/simulate/run.go index d084a421c..4c7ace611 100644 --- a/internal/simulate/run.go +++ b/internal/simulate/run.go @@ -518,14 +518,20 @@ func (c *Runner) renderXRReport(k *kong.Context, logger logging.Logger, r *dt.XR plans := c.providerPlans() res := FromXRReport(r, plans, c.keep) return c.renderReport(k, logger, runErr, res, r.HasChanges(), dt.XRDryRunWarnings(r.Groups), func(opts renderer.DiffOptions) error { - // The Health: line counts the plans, as summary.health does. - opts.Health = res.run - // Annotated even without plans, so a Secret's values are redacted. - r = AnnotateXRReport(r, plans) - return renderer.NewDiffRenderer(logger, opts).RenderDiffs(r.Groups, r.Errors, r.Warnings) + return renderXRDiff(logger, opts, r, plans, res) }) } +// renderXRDiff writes r, the xr run res came from, as the human diff, with +// res's health. +func renderXRDiff(logger logging.Logger, opts renderer.DiffOptions, r *dt.XRReport, plans *ProviderPlans, res Result) error { + // The Health: line counts the plans, as summary.health does. + opts.Health = res.run + // Annotated even without plans, so a Secret's values are redacted. + r = AnnotateXRReport(r, plans) + return renderer.NewDiffRenderer(logger, opts).RenderDiffs(r.Groups, r.Errors, r.Warnings) +} + // renderCompReport writes a composition run's report in the format -o // selects, as renderReport does. func (c *Runner) renderCompReport(k *kong.Context, logger logging.Logger, o *dt.CompDiffOutput, runErr error) (outcome, error) { @@ -533,14 +539,23 @@ func (c *Runner) renderCompReport(k *kong.Context, logger logging.Logger, o *dt. res := FromCompReport(o, plans, c.keep) return c.renderReport(k, logger, runErr, res, o.HasChanges(), dt.CompDryRunWarnings(o), func(opts renderer.DiffOptions) error { opts.MinimizeComposition = c.sel.MinimizeComposition - // The Health: line counts the plans, as summary.health does. - opts.Health = res.run - // Annotated even without plans, so a Secret's values are redacted. - o = AnnotateCompReport(o, plans) - return renderer.NewDefaultCompDiffRenderer(logger, renderer.NewDiffRenderer(logger, opts), opts).RenderCompDiff(o) + return renderCompDiff(logger, opts, o, plans, res) }) } +// renderCompDiff writes o, the composition run res came from, as the human +// diff, with res's health. +func renderCompDiff(logger logging.Logger, opts renderer.DiffOptions, o *dt.CompDiffOutput, plans *ProviderPlans, res Result) error { + // The inner renderer sees only identity-less groups, whose composites + // are not the run's, so it gets no health. + inner := renderer.NewDiffRenderer(logger, opts) + // The Health: line counts the plans, as summary.health does. + opts.Health = res.run + // Annotated even without plans, so a Secret's values are redacted. + o = AnnotateCompReport(o, plans) + return renderer.NewDefaultCompDiffRenderer(logger, inner, opts).RenderCompDiff(o) +} + // renderReport writes a run's report in the format -o selects: renderDiff's // human diff for diff, and res otherwise, followed by warnings. It returns // the run's outcome: whether it changed anything, provider plans included, From 1cc964fd0335501417f9d8bc0aa91244422c71dd Mon Sep 17 00:00:00 2001 From: Jonathan Ogilvie Date: Fri, 4 Dec 2026 12:10:45 -0500 Subject: [PATCH 16/16] refactor(health): tidy health helpers after the run model Unexport tally, entry and ownedElsewhere, which only Build uses. Share composition diff's listed-impact rule through one helper, fix two doc comments, and tidy two tests' names and fields. Co-Authored-By: Claude Opus 5.5 (1M context) Signed-off-by: Jonathan Ogilvie --- internal/diff/renderer/comp_diff_renderer.go | 21 +++++++------- internal/health/format.go | 18 ++++++------ internal/health/format_test.go | 30 ++++++++++---------- internal/health/run.go | 12 ++++---- internal/plan/output_test.go | 2 +- internal/simulate/report.go | 13 +++------ internal/simulate/report_test.go | 12 ++++---- internal/simulate/result.go | 12 ++++---- 8 files changed, 57 insertions(+), 63 deletions(-) diff --git a/internal/diff/renderer/comp_diff_renderer.go b/internal/diff/renderer/comp_diff_renderer.go index c45e3f115..2052c59d3 100644 --- a/internal/diff/renderer/comp_diff_renderer.go +++ b/internal/diff/renderer/comp_diff_renderer.go @@ -369,19 +369,20 @@ func (r *DefaultCompDiffRenderer) renderMinimizedCompositionChanges(comp *dt.Com // them: the user asked about those composites by name. Default discovery reports them only through // the AffectedResources filter counters. func listedImpacts(comp *dt.CompositionDiff) []dt.XRImpact { - if comp.Scoped { - return comp.ImpactAnalysis - } - - listed := make([]dt.XRImpact, 0, len(comp.ImpactAnalysis)) + out := make([]dt.XRImpact, 0, len(comp.ImpactAnalysis)) for _, impact := range comp.ImpactAnalysis { - if impact.Status != dt.XRStatusFiltered { - listed = append(listed, impact) + if listed(comp, impact) { + out = append(out, impact) } } - return listed + return out +} + +// listed reports whether the output lists impact one by one; see listedImpacts. +func listed(comp *dt.CompositionDiff, impact dt.XRImpact) bool { + return comp.Scoped || impact.Status != dt.XRStatusFiltered } // renderAffectedResourcesList renders the affected XRs list with status indicators. @@ -472,8 +473,8 @@ func (r *DefaultCompDiffRenderer) renderUnhealthyBlocks(comp *dt.CompositionDiff var sb strings.Builder for i, impact := range comp.ImpactAnalysis { - if !comp.Scoped && impact.Status == dt.XRStatusFiltered { - continue // not listed; see listedImpacts + if !listed(comp, impact) { + continue } block := ownedBlock(impact.Health, owned[i], impact.Diffs, r.opts.FullMessages) diff --git a/internal/health/format.go b/internal/health/format.go index cea8f6fc1..277cc59db 100644 --- a/internal/health/format.go +++ b/internal/health/format.go @@ -258,11 +258,11 @@ func Key(apiVersion, kind, namespace, name string) string { return gk.String() + "/" + namespace + "/" + name } -// Tally counts a run's health: the composites it lists, and the other +// tally counts a run's health: the composites it lists, and the other // resources by state, each once. Resources are matched by Key, and the first // health a resource is added with wins. A resource that is also added as a // composite counts only as a composite, whatever the order they were added in. -type Tally struct { +type tally struct { composites map[string]bool resources map[string]State order []string @@ -272,7 +272,7 @@ type Tally struct { } // Composite adds a composite with key and health h. -func (t *Tally) Composite(key string, h *Health) { +func (t *tally) Composite(key string, h *Health) { t.failing = t.failing || (h != nil && h.State == Failing) if t.composites == nil { @@ -286,7 +286,7 @@ func (t *Tally) Composite(key string, h *Health) { // Resource adds a resource with key and health h. A resource with no health // is not counted. -func (t *Tally) Resource(key string, h *Health) { +func (t *tally) Resource(key string, h *Health) { if h == nil { return } @@ -304,7 +304,7 @@ func (t *Tally) Resource(key string, h *Health) { } // Counts returns what t counted. -func (t *Tally) Counts() Counts { +func (t *tally) Counts() Counts { c := Counts{Composites: len(t.composites)} for _, unhealthy := range t.composites { @@ -395,20 +395,20 @@ func SummaryLine(c Counts) string { return "Health: " + strings.Join(parts, "; ") + "." } -// Entry is a composite entry in a run's output, for OwnedElsewhere: its Key, +// entry is a composite entry in a run's output, for ownedElsewhere: its Key, // whether it has health of its own, and the Keys of what it composes. -type Entry struct { +type entry struct { Key string HasHealth bool Composes []string } -// OwnedElsewhere returns, for each of entries, the Keys it must not list +// ownedElsewhere returns, for each of entries, the Keys it must not list // because a nested composite entry with health of its own lists them: that // nested composite, and what it composes. So a resource is listed under the // most deeply nested composite entry that composes it, once. An entry without // health is listed by its parent, as a resource. -func OwnedElsewhere(entries []Entry) []map[string]bool { +func ownedElsewhere(entries []entry) []map[string]bool { composes := make([]map[string]bool, len(entries)) withHealth := map[string][]int{} diff --git a/internal/health/format_test.go b/internal/health/format_test.go index 8e3c2ac66..6da847908 100644 --- a/internal/health/format_test.go +++ b/internal/health/format_test.go @@ -279,7 +279,7 @@ func TestTally(t *testing.T) { notReady := &Health{State: NotReady} type args struct { - add func(*Tally) + add func(*tally) } cases := map[string]struct { reason string @@ -288,11 +288,11 @@ func TestTally(t *testing.T) { }{ "Empty": { reason: "Nothing added counts nothing.", - args: args{add: func(*Tally) {}}, + args: args{add: func(*tally) {}}, }, "EachOnce": { reason: "A resource added twice counts once, under the health it was first added with.", - args: args{add: func(t *Tally) { + args: args{add: func(t *tally) { t.Resource("a", failing) t.Resource("a", notReady) t.Resource("b", &Health{State: Paused}) @@ -302,7 +302,7 @@ func TestTally(t *testing.T) { }, "CompositesCountedAsComposites": { reason: "Composites count once each, the unhealthy ones apart, and not again as resources, whichever is added first.", - args: args{add: func(t *Tally) { + args: args{add: func(t *tally) { t.Resource("x", failing) t.Composite("x", failing) t.Composite("y", nil) @@ -316,7 +316,7 @@ func TestTally(t *testing.T) { for name, tc := range cases { t.Run(name, func(t *testing.T) { - var tl Tally + var tl tally tc.args.add(&tl) if diff := cmp.Diff(tc.want, tl.Counts()); diff != "" { t.Errorf("\n%s\nCounts(): -want, +got:\n%s", tc.reason, diff) @@ -412,7 +412,7 @@ func TestKey(t *testing.T) { func TestOwnedElsewhere(t *testing.T) { type args struct { - entries []Entry + entries []entry } cases := map[string]struct { reason string @@ -421,12 +421,12 @@ func TestOwnedElsewhere(t *testing.T) { }{ "Single": { reason: "A lone entry lists everything it composes.", - args: args{entries: []Entry{{Key: "a", HasHealth: true, Composes: []string{"r"}}}}, + args: args{entries: []entry{{Key: "a", HasHealth: true, Composes: []string{"r"}}}}, want: []map[string]bool{{}}, }, "ChildWithHealth": { reason: "A parent doesn't list a child with health, nor what the child composes.", - args: args{entries: []Entry{ + args: args{entries: []entry{ {Key: "a", HasHealth: true, Composes: []string{"b", "r1"}}, {Key: "b", HasHealth: true, Composes: []string{"r2"}}, }}, @@ -434,7 +434,7 @@ func TestOwnedElsewhere(t *testing.T) { }, "ChildWithoutHealth": { reason: "A child without health stays listed by its parent, with what it composes.", - args: args{entries: []Entry{ + args: args{entries: []entry{ {Key: "a", HasHealth: true, Composes: []string{"b"}}, {Key: "b", Composes: []string{"r"}}, }}, @@ -442,7 +442,7 @@ func TestOwnedElsewhere(t *testing.T) { }, "ThreeLevels": { reason: "Each entry drops its child and the child's direct compositions only, not the grandchild's.", - args: args{entries: []Entry{ + args: args{entries: []entry{ {Key: "a", HasHealth: true, Composes: []string{"b"}}, {Key: "b", HasHealth: true, Composes: []string{"c"}}, {Key: "c", HasHealth: true, Composes: []string{"r"}}, @@ -451,7 +451,7 @@ func TestOwnedElsewhere(t *testing.T) { }, "MiddleHasNoEntry": { reason: "With no entry for the middle level, the top lists it and the bottom entry is owned by nobody.", - args: args{entries: []Entry{ + args: args{entries: []entry{ {Key: "a", HasHealth: true, Composes: []string{"b"}}, {Key: "c", HasHealth: true, Composes: []string{"r"}}, }}, @@ -459,7 +459,7 @@ func TestOwnedElsewhere(t *testing.T) { }, "DuplicateKeys": { reason: "Entries sharing a key with health have their compositions merged.", - args: args{entries: []Entry{ + args: args{entries: []entry{ {Key: "a", HasHealth: true, Composes: []string{"b"}}, {Key: "b", HasHealth: true, Composes: []string{"r1"}}, {Key: "b", HasHealth: true, Composes: []string{"r2"}}, @@ -468,12 +468,12 @@ func TestOwnedElsewhere(t *testing.T) { }, "ComposesItself": { reason: "An entry that composes itself drops itself and everything it composes.", - args: args{entries: []Entry{{Key: "a", HasHealth: true, Composes: []string{"a", "r"}}}}, + args: args{entries: []entry{{Key: "a", HasHealth: true, Composes: []string{"a", "r"}}}}, want: []map[string]bool{{"a": true, "r": true}}, }, "OrderIndependent": { reason: "The child listed before its parent gives the same result, by position.", - args: args{entries: []Entry{ + args: args{entries: []entry{ {Key: "b", HasHealth: true, Composes: []string{"r2"}}, {Key: "a", HasHealth: true, Composes: []string{"b", "r1"}}, }}, @@ -483,7 +483,7 @@ func TestOwnedElsewhere(t *testing.T) { for name, tc := range cases { t.Run(name, func(t *testing.T) { - got := OwnedElsewhere(tc.args.entries) + got := ownedElsewhere(tc.args.entries) if diff := cmp.Diff(tc.want, got); diff != "" { t.Errorf("\n%s\nOwnedElsewhere(...): -want, +got:\n%s", tc.reason, diff) } diff --git a/internal/health/run.go b/internal/health/run.go index 00f2c1c07..e164840ea 100644 --- a/internal/health/run.go +++ b/internal/health/run.go @@ -36,7 +36,7 @@ type Composite struct { // Run is a run's health, summarized once by Build. type Run struct { // Owned holds, for each composite, the indexes into its Composed of the - // unhealthy resources it lists, ownership resolved by OwnedElsewhere, and + // unhealthy resources it lists, ownership resolved by ownedElsewhere, and // before any renderer filters out the resources it shows elsewhere. Owned [][]int // Counts are the run's health counts, for its summary line. @@ -56,25 +56,25 @@ type Run struct { // A shown resource whose ID has no kind and no name, as a plan's can, is // never taken for another, so each counts. func Build(composites []Composite, shown []Item) Run { - entries := make([]Entry, len(composites)) + entries := make([]entry, len(composites)) for i, c := range composites { - entries[i] = Entry{Key: c.Key, HasHealth: c.Health != nil} + entries[i] = entry{Key: c.Key, HasHealth: c.Health != nil} for _, it := range c.Composed { entries[i].Composes = append(entries[i].Composes, it.ID) } } - ownedElsewhere := OwnedElsewhere(entries) + owned := ownedElsewhere(entries) r := Run{Owned: make([][]int, len(composites))} for i, c := range composites { for j, it := range c.Composed { - if it.Health.Unhealthy() && !ownedElsewhere[i][it.ID] { + if it.Health.Unhealthy() && !owned[i][it.ID] { r.Owned[i] = append(r.Owned[i], j) } } } - t := &Tally{} + t := &tally{} for _, c := range composites { if c.Health != nil { t.Composite(c.Key, c.Health) diff --git a/internal/plan/output_test.go b/internal/plan/output_test.go index ef52a3468..31dd71895 100644 --- a/internal/plan/output_test.go +++ b/internal/plan/output_test.go @@ -595,7 +595,7 @@ func TestRenderYAMLHealth(t *testing.T) { } } -func TestFailing(t *testing.T) { +func TestHealthRunFailing(t *testing.T) { type args struct { plans []*ResourcePlan } diff --git a/internal/simulate/report.go b/internal/simulate/report.go index 30f7b6815..6d3482376 100644 --- a/internal/simulate/report.go +++ b/internal/simulate/report.go @@ -252,15 +252,10 @@ func (a *assembler) addComposite(c CompositeResult, h dt.CompositeHealth) { 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. -// -// 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. +// unhealthy sets each composite's Unhealthy from run.Owned, which already +// lists each unhealthy resource under the most deeply nested composite entry +// that composes it, once. It drops each resource with a plan in the run, +// matched across API versions: that resource shows its health on its plan. func (a *assembler) unhealthy(run health.Run) { planned := map[string]bool{} for _, p := range a.plans { diff --git a/internal/simulate/report_test.go b/internal/simulate/report_test.go index 8edf0918d..28829700b 100644 --- a/internal/simulate/report_test.go +++ b/internal/simulate/report_test.go @@ -659,10 +659,8 @@ func TestHealth(t *testing.T) { plans map[string]*health.Health // plan name -> health composites []CompositeResult summary plan.HealthSummary - // diffLine, when checkDiff is set, is the Health: line -o diff prints - // for args.xr. - diffLine string - checkDiff bool + // diffLine, when set, is the Health: line -o diff prints for args.xr. + diffLine *string } type args struct { xr *dt.XRReport @@ -844,7 +842,7 @@ func TestHealth(t *testing.T) { want: want{ plans: map[string]*health.Health{}, composites: []CompositeResult{{Ref: xrPlan, Status: CompositeUnchanged}}, - checkDiff: true, + diffLine: new(""), }, }, } @@ -873,7 +871,7 @@ func TestHealth(t *testing.T) { if line, want := got.HealthLine(), anyFailing(got); got.Failing() != want { t.Errorf("%s\nFailing(): want %t, got %t; HealthLine() is %q", tc.reason, want, got.Failing(), line) } - if tc.want.checkDiff { + if tc.want.diffLine != nil { var buf bytes.Buffer opts := renderer.DefaultDiffOptions() opts.Stdout, opts.Stderr = &buf, &bytes.Buffer{} @@ -888,7 +886,7 @@ func TestHealth(t *testing.T) { line = strings.TrimSpace(l) } } - if diff := cmp.Diff(tc.want.diffLine, line); diff != "" { + if diff := cmp.Diff(*tc.want.diffLine, line); diff != "" { t.Errorf("%s\n-o diff Health: line: -want, +got:\n%s", tc.reason, diff) } } diff --git a/internal/simulate/result.go b/internal/simulate/result.go index e899d9288..45ae49fb9 100644 --- a/internal/simulate/result.go +++ b/internal/simulate/result.go @@ -215,12 +215,12 @@ func (r Result) Health() plan.HealthSummary { return plan.HealthSummary{Composites: c.UnhealthyComposites, Failing: c.Failing, NotReady: c.NotReady, Paused: c.Paused} } -// healthRun returns the run's health: the Run the assembler stored, else -// one built from Composites and Plans. Each -// Unhealthy list is already resolved, which Build leaves as it is, so this -// matches the Run the assembler built them from. A composite with no health of its own here (one not -// simulated) isn't added as a composite, so it counts as a resource where its -// parent lists it, if anywhere. +// healthRun returns the run's health: the Run the assembler stored, else one +// built from Composites and Plans. Each Unhealthy list is already resolved, +// which Build leaves as it is, so this matches the Run the assembler built +// them from. A composite with no health of its own here (one not simulated) +// isn't added as a composite, so it counts as a resource where its parent +// lists it, if anywhere. func (r Result) healthRun() health.Run { if r.run != nil { return *r.run