From df749306a1c40fb1d6d248f83fed5d54159bdb91 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 09:18:26 +0100 Subject: [PATCH 1/9] fix(organization): reconcile the agent chart source on every reconcile The organization's agent chart OCIRepository was created once and never updated, so a changed agent chart URL, semver range or filter never reached existing organizations: new agents there installed the old chart. Every reconcile now brings spec.url, spec.interval and spec.ref back to the configured chart source, keeping every other field and label, and writes nothing when they already match. An object of that name the operator did not write is still left alone. The operator's ClusterRole gets update on ocirepositories. --- README.md | 2 +- helm/agent-platform-operator/README.md | 2 +- .../templates/rbac.yaml | 4 +- .../values.schema.json | 2 +- helm/agent-platform-operator/values.yaml | 4 +- internal/controller/chartsource_test.go | 169 ++++++++++++++++++ internal/controller/objects.go | 72 ++++++-- internal/controller/organization.go | 5 +- .../controller/organization_envtest_test.go | 42 +++++ 9 files changed, 281 insertions(+), 21 deletions(-) create mode 100644 internal/controller/chartsource_test.go diff --git a/README.md b/README.md index 1fb54dd..79850ef 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ The operator finds the namespace by the `organization-uid` label, never by its n In the namespace the operator keeps, from the first reconcile on: - the network policies `networkPolicy.names`, copied from `platformNamespace`; -- the agent chart's OCIRepository (`agentChart.*`), named after the chart (`agent`); +- the agent chart's OCIRepository (`agentChart.*`), named after the chart (`agent`). Every reconcile brings its `spec.url`, `spec.interval` and `spec.ref` back to `agentChart.*`, so a changed chart URL, range or filter reaches existing organizations too; its other fields and labels stay. Organizations do not pin their own chart version; - the Helm ServiceAccount `helmReleaseServiceAccount`, which the organization's HelmReleases run as, with a RoleBinding to the ClusterRole `agent-platform-tenant-flux`; - a mirror of each admin binding in the parent namespace: the same name, the roleRef `agent-platform:organizations-admin`, and the `User` and `Group` subjects only. The operator skips ServiceAccount subjects and subjects whose name starts with `system:`. A subject that leaves the parent binding leaves the mirror, and the mirror goes when the parent binding goes or its deletion starts (a finalizer may hold it). These parent bindings are mirrored: - every RoleBinding to the ClusterRole `agent-platform:organizations-admin`; diff --git a/helm/agent-platform-operator/README.md b/helm/agent-platform-operator/README.md index 2cb89f5..3aa5aa1 100644 --- a/helm/agent-platform-operator/README.md +++ b/helm/agent-platform-operator/README.md @@ -18,7 +18,7 @@ Reconciles each AgentPlatformOrganization (agent-platform.giantswarm.io) into it | platformNamespace | string | `"kagent"` | The platform namespace (kagent's) the network policies are copied from. | | networkPolicy.flavor | string | `""` | Kind of the network policies copied into every organization namespace: `kubernetes` (NetworkPolicy) or `cilium` (CiliumNetworkPolicy). Empty copies none. | | networkPolicy.names | list | `[]` | Names of the network policies in `platformNamespace` copied into every organization namespace (the platform's worker policy, `substrate-workers` with Cilium, `substrate-workers-ingress` with Kubernetes network policies). | -| agentChart.ociUrl | string | `"oci://gsoci.azurecr.io/charts/giantswarm/agent"` | OCI URL of the agent chart. The OCIRepository kept in every organization namespace is named after its last segment (`agent`); the organization's HelmReleases reference it by that name. Empty keeps none. | +| agentChart.ociUrl | string | `"oci://gsoci.azurecr.io/charts/giantswarm/agent"` | OCI URL of the agent chart. The OCIRepository kept in every organization namespace is named after its last segment (`agent`); the organization's HelmReleases reference it by that name. The operator brings its url, interval and ref back to these values on every reconcile, also in existing organizations. Empty keeps none. | | agentChart.semver | string | `"2.x"` | Semver range the OCIRepository tracks. | | agentChart.semverFilter | string | `""` | Regular expression the chart's tags must match before the range is evaluated (the OCIRepository's `ref.semverFilter`); empty filters nothing. | | agentChart.interval | string | `"30m"` | OCIRepository.spec.interval. | diff --git a/helm/agent-platform-operator/templates/rbac.yaml b/helm/agent-platform-operator/templates/rbac.yaml index d1f2c11..53d8ee2 100644 --- a/helm/agent-platform-operator/templates/rbac.yaml +++ b/helm/agent-platform-operator/templates/rbac.yaml @@ -80,9 +80,11 @@ rules: resources: ["serviceaccounts"] verbs: ["update"] {{- end }} + # The agent chart's OCIRepository: created, and brought back to + # agentChart.* on every reconcile. - apiGroups: ["source.toolkit.fluxcd.io"] resources: ["ocirepositories"] - verbs: ["get", "create"] + verbs: ["get", "create", "update"] # The organization's Flux Kustomization: kept in commit mode, deleted by # the erasure; the installation's is read for the Orphaned condition. The # erasure deletes the HelmReleases and the Agents of its namespace too. diff --git a/helm/agent-platform-operator/values.schema.json b/helm/agent-platform-operator/values.schema.json index 96618f1..ac57f49 100644 --- a/helm/agent-platform-operator/values.schema.json +++ b/helm/agent-platform-operator/values.schema.json @@ -17,7 +17,7 @@ }, "ociUrl": { "type": "string", - "description": "OCI URL of the agent chart. The OCIRepository kept in every organization namespace is named after its last segment (`agent`); the organization's HelmReleases reference it by that name. Empty keeps none." + "description": "OCI URL of the agent chart. The OCIRepository kept in every organization namespace is named after its last segment (`agent`); the organization's HelmReleases reference it by that name. The operator brings its url, interval and ref back to these values on every reconcile, also in existing organizations. Empty keeps none." }, "semver": { "type": "string", diff --git a/helm/agent-platform-operator/values.yaml b/helm/agent-platform-operator/values.yaml index 74e05a2..1b223ab 100644 --- a/helm/agent-platform-operator/values.yaml +++ b/helm/agent-platform-operator/values.yaml @@ -31,7 +31,9 @@ networkPolicy: agentChart: # -- OCI URL of the agent chart. The OCIRepository kept in every # organization namespace is named after its last segment (`agent`); the - # organization's HelmReleases reference it by that name. Empty keeps none. + # organization's HelmReleases reference it by that name. The operator brings + # its url, interval and ref back to these values on every reconcile, also in + # existing organizations. Empty keeps none. ociUrl: oci://gsoci.azurecr.io/charts/giantswarm/agent # -- Semver range the OCIRepository tracks. semver: "2.x" diff --git a/internal/controller/chartsource_test.go b/internal/controller/chartsource_test.go new file mode 100644 index 0000000..014dce3 --- /dev/null +++ b/internal/controller/chartsource_test.go @@ -0,0 +1,169 @@ +package controller + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/fake" + "sigs.k8s.io/controller-runtime/pkg/client/interceptor" +) + +const ( + chartNS = "agents-payments-abcde" + chartRange = "2.7.x" + chartInterval = "30m" + fieldProvider = "provider" + fieldTimeout = "timeout" + providerValue = "generic" +) + +// chart is the operator's configured agent chart source: what the platform +// release moved it to. +var chart = ChartSource{ + URL: "oci://registry.example.com/charts/giantswarm/agent", + Semver: chartRange, + SemverFilter: "", + Interval: chartInterval, + APIVersion: "source.toolkit.fluxcd.io/v1", +} + +// chartCopy is an OCIRepository named after the chart in chartNS with labels +// and spec. +func chartCopy(labels map[string]string, spec map[string]any) *unstructured.Unstructured { + u := &unstructured.Unstructured{Object: map[string]any{"spec": spec}} + u.SetGroupVersionKind(schema.FromAPIVersionAndKind(chart.APIVersion, "OCIRepository")) + u.SetNamespace(chartNS) + u.SetName(chart.Name()) + u.SetLabels(labels) + return u +} + +// chartSpec is the spec chart derives, with the fields of other. +func chartSpec(other map[string]any) map[string]any { + spec := map[string]any{fieldInterval: chartInterval, fieldURL: chart.URL, fieldRef: map[string]any{fieldSemver: chartRange}} + for k, v := range other { + spec[k] = v + } + return spec +} + +// oldSpec is the spec an older operator release wrote: another registry, +// range and filter, plus fields the operator does not derive (another +// writer's, or the API server's defaults). +func oldSpec() map[string]any { + return map[string]any{ + fieldInterval: "10m", + fieldURL: "oci://gsoci.azurecr.io/charts/giantswarm/agent", + fieldRef: map[string]any{fieldSemver: "2.6.x", "semverFilter": "-dev", "tag": "2.6.0"}, + "insecure": true, + fieldProvider: providerValue, + } +} + +// The chart source of an organization follows the operator's configuration +// on every reconcile: the fields it derives (url, interval, ref) are written, +// every other field and label stays, an unchanged copy is not written again, +// and an object of that name the operator did not write is left alone. +func TestEnsureChartSource(t *testing.T) { + own := ownLabels(ScopeNamespace) + defaulted := map[string]any{fieldProvider: providerValue, fieldTimeout: "60s"} + withNote := map[string]string{ObjectLabel: ScopeNamespace, managedByLabel: managedByValue, "example.com/note": "kept"} + tests := []struct { + name string + existing *unstructured.Unstructured + // want is the spec after the reconcile; wantLabels its labels. + want map[string]any + wantLabels map[string]string + // writes is how many creates and updates the reconcile makes. + writes int + }{ + { + name: "a missing source is created", + want: chartSpec(nil), + wantLabels: own, + writes: 1, + }, + { + name: "an older source moves to the configured url, range and interval, keeping the fields and labels it does not derive", + existing: chartCopy(withNote, oldSpec()), + want: chartSpec(map[string]any{"insecure": true, fieldProvider: providerValue}), + wantLabels: withNote, + writes: 1, + }, + { + name: "a source at the configured spec, with defaulted fields, is not written", + existing: chartCopy(own, chartSpec(defaulted)), + want: chartSpec(defaulted), + // Unchanged: no write, no hot loop. + wantLabels: own, + writes: 0, + }, + { + name: "a source of that name the operator did not write is left alone", + existing: chartCopy(map[string]string{"app.kubernetes.io/managed-by": "someone-else"}, oldSpec()), + want: oldSpec(), + wantLabels: map[string]string{"app.kubernetes.io/managed-by": "someone-else"}, + writes: 0, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + b := fake.NewClientBuilder().WithScheme(runtime.NewScheme()) + if tc.existing != nil { + b = b.WithObjects(tc.existing) + } + writes := 0 + c := b.WithInterceptorFuncs(interceptor.Funcs{ + Create: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.CreateOption) error { + writes++ + return c.Create(ctx, obj, opts...) + }, + Update: func(ctx context.Context, c client.WithWatch, obj client.Object, opts ...client.UpdateOption) error { + writes++ + return c.Update(ctx, obj, opts...) + }, + }).Build() + r := &OrganizationReconciler{Client: c, Config: Config{Chart: chart}} + + require.NoError(t, r.ensureChartSource(t.Context(), chartNS)) + assert.Equal(t, tc.writes, writes) + + got := chartCopy(nil, nil) + require.NoError(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), got)) + assert.Equal(t, tc.want, got.Object["spec"]) + assert.Equal(t, tc.wantLabels, got.GetLabels()) + + // A second reconcile of what the first left writes nothing. + writes = 0 + require.NoError(t, r.ensureChartSource(t.Context(), chartNS)) + assert.Zero(t, writes, "the second reconcile wrote the source again") + }) + } +} + +// A configured semverFilter is written into ref, and dropped again once the +// configuration has none. +func TestEnsureChartSourceSemverFilter(t *testing.T) { + c := fake.NewClientBuilder().WithScheme(runtime.NewScheme()).WithObjects(chartCopy(ownLabels(ScopeNamespace), oldSpec())).Build() + filtered := chart + filtered.SemverFilter = ".*-rc.*" + r := &OrganizationReconciler{Client: c, Config: Config{Chart: filtered}} + require.NoError(t, r.ensureChartSource(t.Context(), chartNS)) + + got := chartCopy(nil, nil) + require.NoError(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), got)) + ref, _, _ := unstructured.NestedMap(got.Object, "spec", fieldRef) + assert.Equal(t, map[string]any{fieldSemver: chartRange, "semverFilter": ".*-rc.*"}, ref) + + r.Config.Chart = chart + require.NoError(t, r.ensureChartSource(t.Context(), chartNS)) + require.NoError(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), got)) + ref, _, _ = unstructured.NestedMap(got.Object, "spec", fieldRef) + assert.Equal(t, map[string]any{fieldSemver: chartRange}, ref) +} diff --git a/internal/controller/objects.go b/internal/controller/objects.go index dbf9379..89c6187 100644 --- a/internal/controller/objects.go +++ b/internal/controller/objects.go @@ -33,11 +33,19 @@ type ChartSource struct { APIVersion string } +// The OCIRepository fields ChartSource derives. +const ( + fieldURL = "url" + fieldInterval = "interval" + fieldRef = "ref" + fieldSemver = "semver" +) + // Name is the OCIRepository's name: the chart's. func (c ChartSource) Name() string { return path.Base(c.URL) } func (c ChartSource) object(ns string) *unstructured.Unstructured { - ref := map[string]any{"semver": c.Semver} + ref := map[string]any{fieldSemver: c.Semver} if c.SemverFilter != "" { ref["semverFilter"] = c.SemverFilter } @@ -46,9 +54,9 @@ func (c ChartSource) object(ns string) *unstructured.Unstructured { fieldKind: "OCIRepository", "metadata": map[string]any{fieldName: c.Name(), fieldNamespace: ns}, "spec": map[string]any{ - "interval": c.Interval, - "url": c.URL, - "ref": ref, + fieldInterval: c.Interval, + fieldURL: c.URL, + fieldRef: ref, }, }} } @@ -180,19 +188,55 @@ func (r *OrganizationReconciler) ensureScoped(ctx context.Context, ns, scope str return nil } -// ensureExists creates obj when nothing of its name exists and never changes -// it after: the agent chart's source moves to another range only through a -// migration, as in agent-manager. -func (r *OrganizationReconciler) ensureExists(ctx context.Context, ns string, obj *unstructured.Unstructured) error { - stamp(obj, ns, ScopeNamespace, "") - err := r.Client.Get(ctx, client.ObjectKeyFromObject(obj), object(obj.GroupVersionKind())) - if err == nil { +// ensureChartSource keeps the agent chart's OCIRepository in ns at +// Config.Chart. It creates it, and on every reconcile brings the fields the +// operator derives (spec.url, spec.interval and the whole spec.ref) back to +// the configured ones, so a platform release that moves the chart (another +// registry, range or filter) reaches every organization, not only new ones. +// Every other spec field, label and annotation stays as it is, and a source +// at the configured spec is not written. An object of that name the operator +// did not write is left alone. No organization pins its own chart: the +// AgentPlatformOrganization has no such field, and only the operator writes +// the source. +func (r *OrganizationReconciler) ensureChartSource(ctx context.Context, ns string) error { + want := r.Config.Chart.object(ns) + wantLabels := stamp(want, ns, ScopeNamespace, "") + kind := want.GetKind() + existing := object(want.GroupVersionKind()) + err := r.Client.Get(ctx, client.ObjectKeyFromObject(want), existing) + switch { + case apierrors.IsNotFound(err): + return r.create(ctx, want, kind) + case err != nil: + return fmt.Errorf("get %s %s/%s: %w", kind, ns, want.GetName(), err) + } + if existing.GetLabels()[ObjectLabel] != ScopeNamespace { + logf.FromContext(ctx).V(1).Info("leaving an object the reconciler did not write", "namespace", ns, "kind", kind, "name", want.GetName()) return nil } - if !apierrors.IsNotFound(err) { - return fmt.Errorf("get %s %s/%s: %w", obj.GetKind(), ns, obj.GetName(), err) + spec, _ := existing.Object["spec"].(map[string]any) + if spec == nil { + spec = map[string]any{} } - return r.create(ctx, obj, obj.GetKind()) + wantSpec, _ := want.Object["spec"].(map[string]any) + labels := copiedLabels(existing.GetLabels(), wantLabels, false) + same := maps.Equal(labels, existing.GetLabels()) + for k, v := range wantSpec { + same = same && reflect.DeepEqual(spec[k], v) + } + if same { + return nil + } + from := map[string]any{fieldURL: spec[fieldURL], fieldRef: spec[fieldRef], fieldInterval: spec[fieldInterval]} + maps.Copy(spec, wantSpec) + existing.Object["spec"] = spec + existing.SetLabels(labels) + if err := r.Client.Update(ctx, existing, client.FieldOwner(fieldManager)); err != nil { + return fmt.Errorf("update %s %s/%s: %w", kind, ns, want.GetName(), err) + } + logf.FromContext(ctx).Info("organization chart source updated", "namespace", ns, "kind", kind, "name", want.GetName(), + "from", from, "to", wantSpec) + return nil } // contains reports whether every field of want is in have with the same diff --git a/internal/controller/organization.go b/internal/controller/organization.go index 520c5c3..facab96 100644 --- a/internal/controller/organization.go +++ b/internal/controller/organization.go @@ -12,7 +12,8 @@ // In the namespace the reconciler keeps, from the first reconcile on: // // - the network policies copied from the platform namespace; -// - the agent chart's OCIRepository; +// - the agent chart's OCIRepository, whose url, interval and ref follow +// Config.Chart (ensureChartSource); // - the Helm ServiceAccount the organization's HelmReleases run as, with its // RoleBinding to the ClusterRole Config.HelmClusterRole // (agent-platform-tenant-flux by default); @@ -412,7 +413,7 @@ func (r *OrganizationReconciler) reconcile(ctx context.Context, org *v1alpha1.Ag } var errs []error if r.Config.Chart.URL != "" { - errs = append(errs, r.ensureExists(ctx, ns.Name, r.Config.Chart.object(ns.Name))) + errs = append(errs, r.ensureChartSource(ctx, ns.Name)) } if sa := r.Config.HelmServiceAccount; sa != "" { errs = append(errs, r.ensureServiceAccount(ctx, ns.Name, sa, ScopeNamespace), r.ensureHelmRoleBinding(ctx, ns.Name)) diff --git a/internal/controller/organization_envtest_test.go b/internal/controller/organization_envtest_test.go index 9757e2e..379685e 100644 --- a/internal/controller/organization_envtest_test.go +++ b/internal/controller/organization_envtest_test.go @@ -77,6 +77,48 @@ func TestOrganizationEnvtest(t *testing.T) { assert.Equal(t, []rbacv1.Subject{{Kind: rbacv1.ServiceAccountKind, Name: helmSA, Namespace: ns.Name}}, rb.Subjects) }) + t.Run("the chart source follows the operator's configuration", func(t *testing.T) { + org := c.organization(t, "org-chart", "chart") + ns := c.readyNamespace(t, org) + + // The copy an older operator release wrote: another registry and + // range, plus a field and a label the operator does not derive. + oci := c.read(t, ociGVK, ns.Name, agentChart) + require.NoError(t, unstructured.SetNestedField(oci.Object, "oci://old.example.com/charts/agent", "spec", "url")) + require.NoError(t, unstructured.SetNestedMap(oci.Object, map[string]any{"semver": "1.x", "semverFilter": "-dev"}, "spec", "ref")) + require.NoError(t, unstructured.SetNestedField(oci.Object, "5m", "spec", "interval")) + require.NoError(t, unstructured.SetNestedField(oci.Object, true, "spec", "insecure")) + labels := oci.GetLabels() + labels["example.com/note"] = "kept" + oci.SetLabels(labels) + require.NoError(t, c.admin.Update(t.Context(), oci)) + + c.poke(t, org) + oci = c.eventually(t, ociGVK, ns.Name, agentChart, func(ct *assert.CollectT, u *unstructured.Unstructured) { + url, _, _ := unstructured.NestedString(u.Object, "spec", "url") + ref, _, _ := unstructured.NestedMap(u.Object, "spec", "ref") + interval, _, _ := unstructured.NestedString(u.Object, "spec", "interval") + assert.Equal(ct, c.config.Chart.URL, url) + assert.Equal(ct, map[string]any{"semver": c.config.Chart.Semver}, ref) + assert.Equal(ct, c.config.Chart.Interval, interval) + }) + insecure, _, _ := unstructured.NestedBool(oci.Object, "spec", "insecure") + assert.True(t, insecure, "a field the operator does not derive was dropped") + assert.Equal(t, "kept", oci.GetLabels()["example.com/note"]) + + // A reconcile of a source at the configured spec writes nothing. + c.poke(t, org) + rv := oci.GetResourceVersion() + require.Never(t, func() bool { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(ociGVK) + if err := c.admin.Get(t.Context(), client.ObjectKey{Namespace: ns.Name, Name: agentChart}, u); err != nil { + return true + } + return u.GetResourceVersion() != rv + }, 2*time.Second, tick, "the chart source was written again with nothing to change") + }) + t.Run("another writer's annotation on the Helm RoleBinding stays", func(t *testing.T) { org := c.organization(t, "org-notes", "notes") ns := c.readyNamespace(t, org) From 636bf4a6dce9af9cf324885762ca4c8f2300fb3a Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 13:59:51 +0100 Subject: [PATCH 2/9] fix(organization): hold an organization's chart source at its major until migrate marks it ready, and scope source updates to the chart's name A move of an existing organization's agent chart OCIRepository to a higher major now waits per organization for agent-manager's migrate: until its report ConfigMap there (agentChart.migrationReport) carries agent-platform.giantswarm.io/agent-chart-ready-major with the new major, the source keeps its ref while url and interval follow, the organization is not Ready (ChartSourceHeld) and is reconciled again every agentChart.migrationPoll. An organization with no HelmRelease on the source moves at once. Ranges are read as migrate and the platform chart read them, every alternative of a || range included. The ClusterRole updates OCIRepositories only by the chart's name and reads migrate's report ConfigMap only. A write the API server stores nothing of is logged at V(1), not as an update. --- README.md | 2 +- go.mod | 1 + helm/agent-platform-operator/README.md | 2 + .../templates/deployment.yaml | 2 + .../templates/rbac.yaml | 24 ++- .../values.schema.json | 8 + helm/agent-platform-operator/values.yaml | 11 ++ internal/controller/chartmajor.go | 182 ++++++++++++++++++ internal/controller/chartsource_test.go | 147 ++++++++++++++ internal/controller/envtest_test.go | 12 +- internal/controller/objects.go | 47 ++++- internal/controller/organization.go | 27 ++- .../controller/organization_envtest_test.go | 59 +++++- .../controller/references_envtest_test.go | 2 +- main.go | 2 + 15 files changed, 512 insertions(+), 16 deletions(-) create mode 100644 internal/controller/chartmajor.go diff --git a/README.md b/README.md index 79850ef..486be17 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ The operator finds the namespace by the `organization-uid` label, never by its n In the namespace the operator keeps, from the first reconcile on: - the network policies `networkPolicy.names`, copied from `platformNamespace`; -- the agent chart's OCIRepository (`agentChart.*`), named after the chart (`agent`). Every reconcile brings its `spec.url`, `spec.interval` and `spec.ref` back to `agentChart.*`, so a changed chart URL, range or filter reaches existing organizations too; its other fields and labels stay. Organizations do not pin their own chart version; +- the agent chart's OCIRepository (`agentChart.*`), named after the chart (`agent`). Every reconcile brings its `spec.url`, `spec.interval` and `spec.ref` back to `agentChart.*`, so a changed chart URL, range or filter reaches existing organizations too; its other fields and labels stay. A move of `spec.ref` to a higher major (`2.x` to `3.x`) waits per organization until agent-manager's migrate annotates its report ConfigMap there (`agentChart.migrationReport`) with `agent-platform.giantswarm.io/agent-chart-ready-major` set to the new major, that is, until every release there is on that major's values; an organization with no HelmRelease on the source moves at once. While it waits, the source keeps its range, the organization is not Ready (reason `ChartSourceHeld`) and it looks again every `agentChart.migrationPoll`. Organizations do not pin their own chart version; - the Helm ServiceAccount `helmReleaseServiceAccount`, which the organization's HelmReleases run as, with a RoleBinding to the ClusterRole `agent-platform-tenant-flux`; - a mirror of each admin binding in the parent namespace: the same name, the roleRef `agent-platform:organizations-admin`, and the `User` and `Group` subjects only. The operator skips ServiceAccount subjects and subjects whose name starts with `system:`. A subject that leaves the parent binding leaves the mirror, and the mirror goes when the parent binding goes or its deletion starts (a finalizer may hold it). These parent bindings are mirrored: - every RoleBinding to the ClusterRole `agent-platform:organizations-admin`; diff --git a/go.mod b/go.mod index 23fbe05..1e87dc5 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/giantswarm/agent-platform-operator go 1.26.0 require ( + github.com/Masterminds/semver/v3 v3.4.0 github.com/aws/aws-sdk-go-v2 v1.48.0 github.com/aws/aws-sdk-go-v2/config v1.33.21 github.com/aws/aws-sdk-go-v2/service/s3 v1.116.0 diff --git a/helm/agent-platform-operator/README.md b/helm/agent-platform-operator/README.md index 3aa5aa1..ae2f0d7 100644 --- a/helm/agent-platform-operator/README.md +++ b/helm/agent-platform-operator/README.md @@ -23,6 +23,8 @@ Reconciles each AgentPlatformOrganization (agent-platform.giantswarm.io) into it | agentChart.semverFilter | string | `""` | Regular expression the chart's tags must match before the range is evaluated (the OCIRepository's `ref.semverFilter`); empty filters nothing. | | agentChart.interval | string | `"30m"` | OCIRepository.spec.interval. | | agentChart.ociRepositoryApiVersion | string | `"source.toolkit.fluxcd.io/v1"` | source.toolkit.fluxcd.io API version of the OCIRepository. | +| agentChart.migrationReport | string | `"agent-manager-migrate-report"` | agent-manager migrate's report ConfigMap in an organization namespace. A move of an existing organization's OCIRepository to a higher major (`2.x` to `3.x`) waits until migrate annotates it `agent-platform.giantswarm.io/agent-chart-ready-major` with the new major (every release there on that major's values), or no HelmRelease there uses the source; meanwhile the organization is not Ready (`ChartSourceHeld`). The operator may read this one ConfigMap name only. | +| agentChart.migrationPoll | string | `"1m"` | How often an organization whose chart source waits at its major looks for migrate's annotation again. | | helmReleaseServiceAccount | string | `"kagent-flux"` | The ServiceAccount the organization's HelmReleases run as (`spec.serviceAccountName`, which helm-controller impersonates), kept in every organization namespace and bound there to the ClusterRole `agent-platform-tenant-flux`. The same name as agent-manager's `flux.helmReleaseServiceAccount`. Empty keeps none. | | serviceAccountBindings | list | `[]` | ClusterRoles bound to a ServiceAccount of another namespace in every organization namespace, such as Substrate's credential providers' Secret readers, which read the Secret an actor's credential names there. Each ClusterRole is bound by a RoleBinding named after it (listed once, not the Helm or Flux binding's name), and the operator gets `bind` on it; a ClusterRole removed from the list loses its bindings. The agent-platform chart's admission policy holds which ServiceAccounts the operator binds there. | | snapshots.bucket | string | `""` | Bucket of the organizations' worker snapshots: an organization's `status.snapshotPrefix` is `s3:///`. Empty leaves it empty. | diff --git a/helm/agent-platform-operator/templates/deployment.yaml b/helm/agent-platform-operator/templates/deployment.yaml index 8ce38cc..201e827 100644 --- a/helm/agent-platform-operator/templates/deployment.yaml +++ b/helm/agent-platform-operator/templates/deployment.yaml @@ -35,6 +35,8 @@ spec: {{- end }} - --ocirepository-interval={{ .Values.agentChart.interval }} - --flux-ocirepository-api-version={{ .Values.agentChart.ociRepositoryApiVersion }} + - --agent-chart-migration-report={{ .Values.agentChart.migrationReport }} + - --agent-chart-migration-poll={{ .Values.agentChart.migrationPoll }} - --helmrelease-service-account={{ .Values.helmReleaseServiceAccount }} {{- with .Values.serviceAccountBindings }} - {{ printf "--service-account-bindings=%s" (include "serviceAccountBindings" $) | quote }} diff --git a/helm/agent-platform-operator/templates/rbac.yaml b/helm/agent-platform-operator/templates/rbac.yaml index 53d8ee2..465e778 100644 --- a/helm/agent-platform-operator/templates/rbac.yaml +++ b/helm/agent-platform-operator/templates/rbac.yaml @@ -3,7 +3,8 @@ The operator's own permissions. RBAC cannot select namespaces by label, so the ClusterRole lets the ServiceAccount create namespaces and write RoleBindings, ServiceAccounts, -OCIRepositories, network policies and ResourceQuotas in every namespace, and +OCIRepositories (updates only of the agent chart's name), network policies +and ResourceQuotas in every namespace, and with curated.enabled write and delete Agents, AgentTemplates, Harnesses, RemoteMCPServers and WorkerPools in every namespace, the platform namespace's curated sources included. The erasure of a deleted organization deletes @@ -80,11 +81,26 @@ rules: resources: ["serviceaccounts"] verbs: ["update"] {{- end }} + {{- with .Values.agentChart.ociUrl }} # The agent chart's OCIRepository: created, and brought back to - # agentChart.* on every reconcile. + # agentChart.* on every reconcile. RBAC cannot name the object of a create; + # an update is held to the chart's name (the last segment of + # agentChart.ociUrl), so without the platform chart's scope policy a leaked + # token still cannot repoint another Flux source. - apiGroups: ["source.toolkit.fluxcd.io"] resources: ["ocirepositories"] - verbs: ["get", "create", "update"] + verbs: ["get", "create"] + - apiGroups: ["source.toolkit.fluxcd.io"] + resources: ["ocirepositories"] + resourceNames: [{{ base . | quote }}] + verbs: ["update"] + # agent-manager migrate's report, read before the source moves to a higher + # agent chart major (agentChart.migrationReport); no other ConfigMap. + - apiGroups: [""] + resources: ["configmaps"] + resourceNames: [{{ $.Values.agentChart.migrationReport | quote }}] + verbs: ["get"] + {{- end }} # The organization's Flux Kustomization: kept in commit mode, deleted by # the erasure; the installation's is read for the Orphaned condition. The # erasure deletes the HelmReleases and the Agents of its namespace too. @@ -102,6 +118,8 @@ rules: - "create" - "update" {{- end }} + # The HelmReleases are listed too before a move of the chart source to a + # higher major: one with no release on it moves without migrate's mark. - apiGroups: ["helm.toolkit.fluxcd.io"] resources: ["helmreleases"] verbs: ["list", "delete"] diff --git a/helm/agent-platform-operator/values.schema.json b/helm/agent-platform-operator/values.schema.json index ac57f49..784a1d7 100644 --- a/helm/agent-platform-operator/values.schema.json +++ b/helm/agent-platform-operator/values.schema.json @@ -11,6 +11,14 @@ "type": "string", "description": "OCIRepository.spec.interval." }, + "migrationPoll": { + "type": "string", + "description": "How often an organization whose chart source waits at its major looks for migrate's annotation again." + }, + "migrationReport": { + "type": "string", + "description": "agent-manager migrate's report ConfigMap in an organization namespace. A move of an existing organization's OCIRepository to a higher major (`2.x` to `3.x`) waits until migrate annotates it `agent-platform.giantswarm.io/agent-chart-ready-major` with the new major (every release there on that major's values), or no HelmRelease there uses the source; meanwhile the organization is not Ready (`ChartSourceHeld`). The operator may read this one ConfigMap name only." + }, "ociRepositoryApiVersion": { "type": "string", "description": "source.toolkit.fluxcd.io API version of the OCIRepository." diff --git a/helm/agent-platform-operator/values.yaml b/helm/agent-platform-operator/values.yaml index 1b223ab..1078001 100644 --- a/helm/agent-platform-operator/values.yaml +++ b/helm/agent-platform-operator/values.yaml @@ -44,6 +44,17 @@ agentChart: interval: 30m # -- source.toolkit.fluxcd.io API version of the OCIRepository. ociRepositoryApiVersion: source.toolkit.fluxcd.io/v1 + # -- agent-manager migrate's report ConfigMap in an organization namespace. + # A move of an existing organization's OCIRepository to a higher major + # (`2.x` to `3.x`) waits until migrate annotates it + # `agent-platform.giantswarm.io/agent-chart-ready-major` with the new major + # (every release there on that major's values), or no HelmRelease there uses + # the source; meanwhile the organization is not Ready (`ChartSourceHeld`). + # The operator may read this one ConfigMap name only. + migrationReport: agent-manager-migrate-report + # -- How often an organization whose chart source waits at its major looks + # for migrate's annotation again. + migrationPoll: 1m # -- The ServiceAccount the organization's HelmReleases run as # (`spec.serviceAccountName`, which helm-controller impersonates), kept in diff --git a/internal/controller/chartmajor.go b/internal/controller/chartmajor.go new file mode 100644 index 0000000..b04f612 --- /dev/null +++ b/internal/controller/chartmajor.go @@ -0,0 +1,182 @@ +package controller + +import ( + "context" + "fmt" + "regexp" + "slices" + "strconv" + "time" + + "github.com/Masterminds/semver/v3" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// MigrationReadyAnnotation is what agent-manager's migrate sets on its report +// ConfigMap in an organization namespace (ChartSource.MigrationReport) to the +// agent chart major every release there is on the values of (agent-manager's +// migrate.OrganizationReadyAnnotation: the two constants are one contract). +// The operator moves the namespace's chart source across a major only while +// it names the new major. +const MigrationReadyAnnotation = "agent-platform.giantswarm.io/agent-chart-ready-major" + +// DefaultMigrationReport is agent-manager migrate's report ConfigMap. +const DefaultMigrationReport = "agent-manager-migrate-report" + +// DefaultMigrationPoll is how often an organization whose chart source is +// held at its major looks for migrate's mark again. +const DefaultMigrationPoll = time.Minute + +const reasonChartSourceHeld = "ChartSourceHeld" + +// majorMove is the major a move of an existing chart source from ref to the +// configured range crosses into: the configured range's highest major when it +// is above every major the source's range admits, else 0 (within a major, or +// back down, nothing waits). A source range that admits no release version, +// or has none (a tag or digest the operator never writes), is read as below +// any major, so the move waits too. +func (c ChartSource) majorMove(ref map[string]any) uint64 { + to := rangeMajors(c.Semver) + if len(to) == 0 { + return 0 + } + target := to[len(to)-1] + from, _ := ref[fieldSemver].(string) + if have := rangeMajors(from); len(have) > 0 && have[len(have)-1] >= target { + return 0 + } + return target +} + +// chartSourceHeld is the cause of Ready=False while a chart source waits at +// its major; it reconciles the organization again after poll. +func chartSourceHeld(ns, name string, major uint64, why string, poll time.Duration) *notReadyError { + return ¬ReadyError{reason: reasonChartSourceHeld, requeueAfter: poll, message: fmt.Sprintf( + "the agent chart source %s/%s stays on its range until agent-manager's migrate marks the namespace ready for chart %d.x (%s): %s", ns, name, major, MigrationReadyAnnotation, why)} +} + +// migrationReady reports whether the chart source name in ns may move to +// major: migrate's report there carries MigrationReadyAnnotation with that +// major, or no HelmRelease of the namespace renders from the source (nothing +// whose values could still be the old major's). why says what holds it. +func (r *OrganizationReconciler) migrationReady(ctx context.Context, ns, name string, major uint64) (ready bool, why string, err error) { + reader := r.APIReader + if reader == nil { + reader = r.Client + } + report := r.Config.Chart.MigrationReport + if report == "" { + report = DefaultMigrationReport + } + cm := &corev1.ConfigMap{} + switch err := reader.Get(ctx, client.ObjectKey{Namespace: ns, Name: report}, cm); { + case err == nil: + if got := cm.Annotations[MigrationReadyAnnotation]; got == strconv.FormatUint(major, 10) { + return true, "", nil + } else if got != "" { + why = fmt.Sprintf("its report %s marks it ready for %s.x only", report, got) + } else { + why = fmt.Sprintf("its report %s names releases not on %d.x values yet", report, major) + } + case apierrors.IsNotFound(err): + why = fmt.Sprintf("no migrate run has written its report %s there yet", report) + default: + return false, "", fmt.Errorf("get the migrate report %s/%s: %w", ns, report, err) + } + gvk := r.Config.Erasure.HelmRelease + if gvk.Empty() { + return false, why, nil + } + list := &unstructured.UnstructuredList{} + list.SetGroupVersionKind(gvk.GroupVersion().WithKind(gvk.Kind + "List")) + if err := reader.List(ctx, list, client.InNamespace(ns)); err != nil { + if meta.IsNoMatchError(err) || apierrors.IsNotFound(err) { + return true, "", nil // Flux's HelmRelease is not served: no release to wait for + } + return false, "", fmt.Errorf("list the HelmReleases of %s: %w", ns, err) + } + var using []string + for i := range list.Items { + ref, _, _ := unstructured.NestedStringMap(list.Items[i].Object, "spec", "chartRef") + if ref["kind"] == "OCIRepository" && ref[fieldName] == name && (ref[fieldNamespace] == "" || ref[fieldNamespace] == ns) { + using = append(using, list.Items[i].GetName()) + } + } + if len(using) == 0 { + return true, "", nil + } + slices.Sort(using) + return false, fmt.Sprintf("%s; HelmReleases on it: %v", why, using), nil +} + +// versionLiteral is a version a range names (2, 2.6, 2.6.1, v3.0.0-rc.1). +var versionLiteral = regexp.MustCompile(`v?([0-9]+)(?:\.([0-9]+))?(?:\.([0-9]+))?`) + +// rangeMajors are the release majors a semver range admits, sorted; none when +// it does not parse. Read as agent-manager's migrate reads a target range +// (internal/migrate majorsOf) and the agent-platform chart's guard +// (agent-platform.agentChart.majors): every version the range names, with the +// next patch and minor, and per major 0-99 the first and a late version of +// every minor below 200 and a late minor, each counting only when the range +// admits it, so every alternative of a `||` range counts. +func rangeMajors(rng string) []uint64 { + c, err := semver.NewConstraint(rng) + if err != nil { + return nil + } + var majors []uint64 + add := func(m uint64) { + if !slices.Contains(majors, m) { + majors = append(majors, m) + } + } + for _, lit := range versionLiteral.FindAllStringSubmatch(rng, -1) { + parts := make([]uint64, 3) + ok := true + for i, s := range lit[1:] { + if s == "" { + continue + } + n, err := strconv.ParseUint(s, 10, 64) + if err != nil { + ok = false + break + } + parts[i] = n + } + if !ok { + continue + } + for _, v := range []*semver.Version{ + semver.New(parts[0], parts[1], parts[2], "", ""), + semver.New(parts[0], parts[1], parts[2]+1, "", ""), + semver.New(parts[0], parts[1]+1, 0, "", ""), + } { + if c.Check(v) { + add(parts[0]) + } + } + } + const late = 999999 + for m := range uint64(100) { + if slices.Contains(majors, m) { + continue + } + if c.Check(semver.New(m, late, late, "", "")) { + add(m) + continue + } + for n := range uint64(200) { + if c.Check(semver.New(m, n, 0, "", "")) || c.Check(semver.New(m, n, late, "", "")) { + add(m) + break + } + } + } + slices.Sort(majors) + return majors +} diff --git a/internal/controller/chartsource_test.go b/internal/controller/chartsource_test.go index 014dce3..f6a0c62 100644 --- a/internal/controller/chartsource_test.go +++ b/internal/controller/chartsource_test.go @@ -2,10 +2,14 @@ package controller import ( "context" + "errors" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" @@ -15,6 +19,7 @@ import ( ) const ( + v2Line = "2.x" chartNS = "agents-payments-abcde" chartRange = "2.7.x" chartInterval = "30m" @@ -104,6 +109,20 @@ func TestEnsureChartSource(t *testing.T) { wantLabels: own, writes: 0, }, + { + name: "an interval that alone differs is written", + existing: chartCopy(own, chartSpec(map[string]any{fieldInterval: "5m"})), + want: chartSpec(nil), + wantLabels: own, + writes: 1, + }, + { + name: "a missing own label alone is written, the other labels kept", + existing: chartCopy(map[string]string{ObjectLabel: ScopeNamespace, "example.com/note": "kept"}, chartSpec(nil)), + want: chartSpec(nil), + wantLabels: withNote, + writes: 1, + }, { name: "a source of that name the operator did not write is left alone", existing: chartCopy(map[string]string{"app.kubernetes.io/managed-by": "someone-else"}, oldSpec()), @@ -167,3 +186,131 @@ func TestEnsureChartSourceSemverFilter(t *testing.T) { ref, _, _ = unstructured.NestedMap(got.Object, "spec", fieldRef) assert.Equal(t, map[string]any{fieldSemver: chartRange}, ref) } + +var testHelmReleaseGVK = schema.GroupVersionKind{Group: "helm.toolkit.fluxcd.io", Version: "v2", Kind: "HelmRelease"} + +// chartRelease is a HelmRelease in chartNS whose chart is the OCIRepository +// source. +func chartRelease(name, source string) *unstructured.Unstructured { + u := &unstructured.Unstructured{Object: map[string]any{"spec": map[string]any{ + "chartRef": map[string]any{"kind": "OCIRepository", fieldName: source}, + }}} + u.SetGroupVersionKind(testHelmReleaseGVK) + u.SetNamespace(chartNS) + u.SetName(name) + return u +} + +// migrateReport is agent-manager migrate's report in chartNS, marked ready +// for major when it is not empty. +func migrateReport(major string) *corev1.ConfigMap { + cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: chartNS, Name: DefaultMigrationReport}} + if major != "" { + cm.Annotations = map[string]string{MigrationReadyAnnotation: major} + } + return cm +} + +// A move of an organization's chart source to a higher major waits for +// agent-manager migrate's mark on its report in the namespace, unless no +// HelmRelease there uses the source (D-GO-03). Held, the source keeps its +// ref while url and interval still follow, and the organization is not Ready +// (ChartSourceHeld) with a requeue after MigrationPoll. +func TestEnsureChartSourceWaitsForMigrateAcrossAMajor(t *testing.T) { + const v3 = ">=3.0.0 <4.0.0" + v2Ref := map[string]any{fieldSemver: v2Line} + tests := []struct { + name string + semver string + from map[string]any + objects []client.Object + moved bool + mentions string + }{ + {name: "a release on the source and no report: held", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease("triage", chart.Name())}, mentions: "no migrate run has written its report"}, + {name: "a report without the mark: held", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease("triage", chart.Name()), migrateReport("")}, mentions: "names releases not on 3.x values yet"}, + {name: "a report marked for the old major: held", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease("triage", chart.Name()), migrateReport("2")}, mentions: "ready for 2.x only"}, + {name: "a report marked for the new major: moved", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease("triage", chart.Name()), migrateReport("3")}, moved: true}, + {name: "no release on the source: moved without a report", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease("dashboards", "dashboards")}, moved: true}, + {name: "a move within a major never waits", semver: chartRange, from: map[string]any{fieldSemver: "2.6.x"}, + objects: []client.Object{chartRelease("triage", chart.Name())}, moved: true}, + {name: "a move back down never waits", semver: v2Line, from: map[string]any{fieldSemver: v3}, + objects: []client.Object{chartRelease("triage", chart.Name())}, moved: true}, + {name: "an alternative of the old range on the new major: no move across", semver: v3, from: map[string]any{fieldSemver: "2.6.0 || 3.0.1"}, + objects: []client.Object{chartRelease("triage", chart.Name())}, moved: true}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + scheme := runtime.NewScheme() + require.NoError(t, corev1.AddToScheme(scheme)) + scheme.AddKnownTypeWithName(testHelmReleaseGVK, &unstructured.Unstructured{}) + scheme.AddKnownTypeWithName(testHelmReleaseGVK.GroupVersion().WithKind("HelmReleaseList"), &unstructured.UnstructuredList{}) + spec := chartSpec(map[string]any{fieldURL: "oci://old.example.com/charts/giantswarm/agent", fieldRef: tc.from}) + c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(append(tc.objects, chartCopy(ownLabels(ScopeNamespace), spec))...).Build() + cfg := chart + cfg.Semver = tc.semver + cfg.MigrationPoll = 7 * time.Second + r := &OrganizationReconciler{Client: c, Config: Config{Chart: cfg, Erasure: ErasureConfig{HelmRelease: testHelmReleaseGVK}}} + + err := r.ensureChartSource(t.Context(), chartNS) + got := chartCopy(nil, nil) + require.NoError(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), got)) + url, _, _ := unstructured.NestedString(got.Object, "spec", fieldURL) + assert.Equal(t, chart.URL, url, "the url follows either way") + ref, _, _ := unstructured.NestedMap(got.Object, "spec", fieldRef) + if tc.moved { + require.NoError(t, err) + assert.Equal(t, map[string]any{fieldSemver: tc.semver}, ref) + return + } + assert.Equal(t, tc.from, ref, "the ref stays on the old major") + var nr *notReadyError + require.ErrorAs(t, err, &nr) + assert.Equal(t, reasonChartSourceHeld, nr.reason) + assert.Contains(t, nr.message, tc.mentions) + assert.Contains(t, nr.message, MigrationReadyAnnotation) + assert.Equal(t, 7*time.Second, requeueAfter(errors.Join(errors.New("another failure"), err))) + ready, retry := readyCondition(err, 1) + assert.NoError(t, retry, "a held source is no failure to retry") + assert.Equal(t, reasonChartSourceHeld, ready.Reason) + + // A second reconcile writes nothing more. + rv := got.GetResourceVersion() + require.Error(t, r.ensureChartSource(t.Context(), chartNS)) + require.NoError(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), got)) + assert.Equal(t, rv, got.GetResourceVersion()) + }) + } +} + +// The majors a range admits, read as agent-manager's migrate and the +// agent-platform chart read them (D-GO-08). +func TestRangeMajors(t *testing.T) { + for rng, want := range map[string][]uint64{ + "2.x": {2}, + ">=3.0.0 <4.0.0": {3}, + "3.0.1 || 2.6.0": {2, 3}, + ">=2.6.1 <2.6.9": {2}, + "= 2.6.1": {2}, + "~2.250": {2}, + "3.0.0-rc.6": nil, + "not a range": nil, + ">=2.6.0 <=3.0.0-rc.1": {2}, + "2.6.0 || >=3.0.1 <3.0.5": {2, 3}, + } { + assert.Equal(t, want, rangeMajors(rng), rng) + } +} + +// requeueAfter is the shortest a cause of Ready=False asks for; a failure or +// a cause without one asks for none. +func TestRequeueAfter(t *testing.T) { + assert.Zero(t, requeueAfter(nil)) + assert.Zero(t, requeueAfter(errors.Join(errors.New("failed"), ¬ReadyError{reason: reasonNameTaken}))) + assert.Equal(t, time.Second, requeueAfter(errors.Join(¬ReadyError{requeueAfter: time.Minute}, ¬ReadyError{requeueAfter: time.Second}))) +} diff --git a/internal/controller/envtest_test.go b/internal/controller/envtest_test.go index 115df69..0967b5f 100644 --- a/internal/controller/envtest_test.go +++ b/internal/controller/envtest_test.go @@ -125,6 +125,8 @@ type cluster struct { rest *rest.Config // config is the reconciler's Config. config controller.Config + // operator is the operator's user, as the chart's RBAC binds it. + operator string // log records, in order, what the erasure did through the fakes of // kagent's session API, Substrate's actors and the snapshot bucket, and // what the erasure observers saw it delete. @@ -231,13 +233,14 @@ func startEnvtest(t *testing.T) *cluster { sessions := &fakeSessions{log: log, byID: map[string]*fakeSession{}, pkg: pkgV1alpha1} actors := &fakeActors{log: log, sessions: sessions, linger: map[string]int{}} bucket := &fakeBucket{log: log, objects: map[string]int{}, fail: map[string]error{}} - c := &cluster{admin: admin, rest: cfg, log: log, sessions: sessions, actors: actors, bucket: bucket, config: controller.Config{ + c := &cluster{admin: admin, rest: cfg, operator: operator, log: log, sessions: sessions, actors: actors, bucket: bucket, config: controller.Config{ PlatformNamespace: platformNS, NetworkPolicies: []string{workerPolicy}, NetworkPolicyGVK: npGVK, Chart: controller.ChartSource{ URL: "oci://gsoci.azurecr.io/charts/giantswarm/agent", Semver: "2.x", - Interval: "30m", APIVersion: ociGVK.GroupVersion().String(), + Interval: chartInterval, APIVersion: ociGVK.GroupVersion().String(), + MigrationPoll: 200 * time.Millisecond, }, HelmServiceAccount: helmSA, HelmClusterRole: helmClusterRole, @@ -317,7 +320,7 @@ func curatedSources() []*unstructured.Unstructured { obj(agentGVK, curatedAgent, curatedLabels, agentSpec(agentPrompt, map[string]any{"modelConfig": nameRef(platformModel), toolsField: tools})), obj(agentGVK, platformAgent, nil, agentSpec("Platform only.", nil)), obj(templateGVK, curatedTemplate, curatedLabels, templateSpec("Triage.", map[string]any{"modelConfig": nameRef(platformModel), toolsField: tools})), - obj(serverGVK, musterServer, curatedWith(map[string]string{discoveryLabel: "disabled", "app.kubernetes.io/name": "agent"}), map[string]any{"url": "https://muster.example.com/mcp", descriptionField: "muster"}), + obj(serverGVK, musterServer, curatedWith(map[string]string{discoveryLabel: "disabled", "app.kubernetes.io/name": "agent"}), map[string]any{urlField: "https://muster.example.com/mcp", descriptionField: "muster"}), } } @@ -371,6 +374,9 @@ func nameRef(name string) map[string]any { return map[string]any{nameField: name // an agent template. const ( kindField = "kind" + urlField = "url" + semverField = "semver" + chartInterval = "30m" nameField = "name" intervalField = "interval" harnessRefField = "harnessRef" diff --git a/internal/controller/objects.go b/internal/controller/objects.go index 89c6187..78fd0b6 100644 --- a/internal/controller/objects.go +++ b/internal/controller/objects.go @@ -8,6 +8,7 @@ import ( "path" "reflect" "strings" + "time" corev1 "k8s.io/api/core/v1" rbacv1 "k8s.io/api/rbac/v1" @@ -31,6 +32,13 @@ type ChartSource struct { SemverFilter string Interval string APIVersion string + // MigrationReport is agent-manager migrate's report ConfigMap in an + // organization namespace (DefaultMigrationReport when empty): an + // existing source moves across a major only while it carries + // MigrationReadyAnnotation with the new major. MigrationPoll is how often + // a held organization looks again (DefaultMigrationPoll when zero). + MigrationReport string + MigrationPoll time.Duration } // The OCIRepository fields ChartSource derives. @@ -198,6 +206,15 @@ func (r *OrganizationReconciler) ensureScoped(ctx context.Context, ns, scope str // did not write is left alone. No organization pins its own chart: the // AgentPlatformOrganization has no such field, and only the operator writes // the source. +// +// A move of spec.ref to a higher major waits, per organization, for +// agent-manager's migrate (migrationReady): until its report in the +// namespace marks every release there as on the new major's values, the +// source keeps its ref (url and interval still follow), the organization is +// not Ready (reason ChartSourceHeld) and looks again after MigrationPoll. A +// release still on the old major's values would otherwise fail every upgrade +// on the new chart (agent chart 3.0 refuses muster.requireApproval) and stay +// on its old revision until edited by hand. func (r *OrganizationReconciler) ensureChartSource(ctx context.Context, ns string) error { want := r.Config.Chart.object(ns) wantLabels := stamp(want, ns, ScopeNamespace, "") @@ -219,24 +236,50 @@ func (r *OrganizationReconciler) ensureChartSource(ctx context.Context, ns strin spec = map[string]any{} } wantSpec, _ := want.Object["spec"].(map[string]any) + var held error + if !reflect.DeepEqual(spec[fieldRef], wantSpec[fieldRef]) { + have, _ := spec[fieldRef].(map[string]any) + if major := r.Config.Chart.majorMove(have); major > 0 { + ready, why, err := r.migrationReady(ctx, ns, want.GetName(), major) + if err != nil { + return err + } + if !ready { + poll := r.Config.Chart.MigrationPoll + if poll <= 0 { + poll = DefaultMigrationPoll + } + held = chartSourceHeld(ns, want.GetName(), major, why, poll) + wantSpec = maps.Clone(wantSpec) + wantSpec[fieldRef] = spec[fieldRef] + } + } + } labels := copiedLabels(existing.GetLabels(), wantLabels, false) same := maps.Equal(labels, existing.GetLabels()) for k, v := range wantSpec { same = same && reflect.DeepEqual(spec[k], v) } if same { - return nil + return held } from := map[string]any{fieldURL: spec[fieldURL], fieldRef: spec[fieldRef], fieldInterval: spec[fieldInterval]} maps.Copy(spec, wantSpec) existing.Object["spec"] = spec existing.SetLabels(labels) + before := existing.GetResourceVersion() if err := r.Client.Update(ctx, existing, client.FieldOwner(fieldManager)); err != nil { return fmt.Errorf("update %s %s/%s: %w", kind, ns, want.GetName(), err) } + if existing.GetResourceVersion() == before { + // The API server stored nothing: a field its CRD prunes or a value + // it normalises differs from what the operator derives. Not a change. + logf.FromContext(ctx).V(1).Info("organization chart source written, nothing stored", "namespace", ns, "kind", kind, "name", want.GetName()) + return held + } logf.FromContext(ctx).Info("organization chart source updated", "namespace", ns, "kind", kind, "name", want.GetName(), "from", from, "to", wantSpec) - return nil + return held } // contains reports whether every field of want is in have with the same diff --git a/internal/controller/organization.go b/internal/controller/organization.go index facab96..3d89adf 100644 --- a/internal/controller/organization.go +++ b/internal/controller/organization.go @@ -389,7 +389,8 @@ func (r *OrganizationReconciler) Reconcile(ctx context.Context, req reconcile.Re // First: the worker replica rule reads it. orphanedErr := r.setOrphaned(ctx, org, status) - ready, err := readyCondition(errors.Join(orphanedErr, r.reconcile(ctx, org, status)), org.Generation) + reconcileErr := errors.Join(orphanedErr, r.reconcile(ctx, org, status)) + ready, err := readyCondition(reconcileErr, org.Generation) meta.SetStatusCondition(&status.Conditions, ready) if !equality.Semantic.DeepEqual(&org.Status, status) { org.Status = *status @@ -397,7 +398,20 @@ func (r *OrganizationReconciler) Reconcile(ctx context.Context, req reconcile.Re return reconcile.Result{}, errors.Join(err, fmt.Errorf("update status: %w", uerr)) } } - return reconcile.Result{}, err + return reconcile.Result{RequeueAfter: requeueAfter(reconcileErr)}, err +} + +// requeueAfter is the shortest requeueAfter of the causes of Ready=False in +// err; zero when none asks for one. +func requeueAfter(err error) time.Duration { + _, notReady := split(err) + var after time.Duration + for _, nr := range notReady { + if nr.requeueAfter > 0 && (after == 0 || nr.requeueAfter < after) { + after = nr.requeueAfter + } + } + return after } // reconcile finds or creates the organization namespace, records it in @@ -438,8 +452,13 @@ func (r *OrganizationReconciler) reconcile(ctx context.Context, org *v1alpha1.Ag } // notReadyError is a cause of Ready=False that a retry does not change: the -// reconcile has done what it can. -type notReadyError struct{ reason, message string } +// reconcile has done what it can. With requeueAfter the organization is +// reconciled again after that long, for a cause no watched event ends (the +// chart source held for migrate, chartSourceHeld). +type notReadyError struct { + reason, message string + requeueAfter time.Duration +} func (e *notReadyError) Error() string { return e.message } diff --git a/internal/controller/organization_envtest_test.go b/internal/controller/organization_envtest_test.go index 379685e..11872ab 100644 --- a/internal/controller/organization_envtest_test.go +++ b/internal/controller/organization_envtest_test.go @@ -24,6 +24,8 @@ import ( ) const ( + // oldLine is an agent chart range of an older major than the operator's. + oldLine = "1.x" timeout = 30 * time.Second tick = 100 * time.Millisecond mirrorParent = "org-mirror" @@ -85,7 +87,7 @@ func TestOrganizationEnvtest(t *testing.T) { // range, plus a field and a label the operator does not derive. oci := c.read(t, ociGVK, ns.Name, agentChart) require.NoError(t, unstructured.SetNestedField(oci.Object, "oci://old.example.com/charts/agent", "spec", "url")) - require.NoError(t, unstructured.SetNestedMap(oci.Object, map[string]any{"semver": "1.x", "semverFilter": "-dev"}, "spec", "ref")) + require.NoError(t, unstructured.SetNestedMap(oci.Object, map[string]any{semverField: oldLine, "semverFilter": "-dev"}, "spec", "ref")) require.NoError(t, unstructured.SetNestedField(oci.Object, "5m", "spec", "interval")) require.NoError(t, unstructured.SetNestedField(oci.Object, true, "spec", "insecure")) labels := oci.GetLabels() @@ -99,7 +101,7 @@ func TestOrganizationEnvtest(t *testing.T) { ref, _, _ := unstructured.NestedMap(u.Object, "spec", "ref") interval, _, _ := unstructured.NestedString(u.Object, "spec", "interval") assert.Equal(ct, c.config.Chart.URL, url) - assert.Equal(ct, map[string]any{"semver": c.config.Chart.Semver}, ref) + assert.Equal(ct, map[string]any{semverField: c.config.Chart.Semver}, ref) assert.Equal(ct, c.config.Chart.Interval, interval) }) insecure, _, _ := unstructured.NestedBool(oci.Object, "spec", "insecure") @@ -119,6 +121,59 @@ func TestOrganizationEnvtest(t *testing.T) { }, 2*time.Second, tick, "the chart source was written again with nothing to change") }) + t.Run("a move of the chart source to a higher major waits for migrate's mark", func(t *testing.T) { + org := c.organization(t, "org-major", "major") + ns := c.readyNamespace(t, org) + oci := c.read(t, ociGVK, ns.Name, agentChart) + require.NoError(t, unstructured.SetNestedMap(oci.Object, map[string]any{semverField: oldLine}, "spec", "ref")) + require.NoError(t, c.admin.Update(t.Context(), oci)) + hr := newObject(helmReleaseGVK, ns.Name, "triage", nil, helmReleaseSpec) + require.NoError(t, c.admin.Create(t.Context(), hr)) + + c.poke(t, org) + require.EventuallyWithT(t, func(ct *assert.CollectT) { + ready := meta.FindStatusCondition(c.get(ct, org).Status.Conditions, v1alpha1.ConditionReady) + if assert.NotNil(ct, ready) { + assert.Equal(ct, metav1.ConditionFalse, ready.Status) + assert.Equal(ct, "ChartSourceHeld", ready.Reason) + assert.Contains(ct, ready.Message, controller.MigrationReadyAnnotation) + } + }, timeout, tick) + ref, _, _ := unstructured.NestedMap(c.read(t, ociGVK, ns.Name, agentChart).Object, "spec", "ref") + assert.Equal(t, map[string]any{semverField: oldLine}, ref, "the source stays on its major") + + // migrate's mark for the new major: the held organization looks + // again on its own (MigrationPoll) and moves. + require.NoError(t, c.admin.Create(t.Context(), &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{ + Namespace: ns.Name, Name: controller.DefaultMigrationReport, + Annotations: map[string]string{controller.MigrationReadyAnnotation: "2"}, + }})) + c.eventually(t, ociGVK, ns.Name, agentChart, func(ct *assert.CollectT, u *unstructured.Unstructured) { + ref, _, _ := unstructured.NestedMap(u.Object, "spec", "ref") + assert.Equal(ct, map[string]any{semverField: c.config.Chart.Semver}, ref) + }) + c.readyAt(t, org, org.Generation) + }) + + t.Run("the operator updates no OCIRepository but the chart's and reads no ConfigMap but migrate's report", func(t *testing.T) { + org := c.organization(t, "org-rbac", "rbac") + ns := c.readyNamespace(t, org) + other := newObject(ociGVK, ns.Name, "dashboards", nil, map[string]any{intervalField: chartInterval, urlField: "oci://example.com/charts/dashboards"}) + require.NoError(t, c.admin.Create(t.Context(), other)) + other = c.read(t, ociGVK, ns.Name, "dashboards") + require.NoError(t, unstructured.SetNestedField(other.Object, "oci://attacker.example.com/charts/dashboards", "spec", urlField)) + operator := c.as(t, c.operator) + err := operator.Update(t.Context(), other) + require.True(t, apierrors.IsForbidden(err), "update of another source: %v", err) + + own := c.read(t, ociGVK, ns.Name, agentChart) + require.NoError(t, operator.Update(t.Context(), own), "the chart's own source stays writable") + + require.NoError(t, c.admin.Create(t.Context(), &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: ns.Name, Name: "settings"}})) + err = operator.Get(t.Context(), client.ObjectKey{Namespace: ns.Name, Name: "settings"}, &corev1.ConfigMap{}) + require.True(t, apierrors.IsForbidden(err), "get of another ConfigMap: %v", err) + }) + t.Run("another writer's annotation on the Helm RoleBinding stays", func(t *testing.T) { org := c.organization(t, "org-notes", "notes") ns := c.readyNamespace(t, org) diff --git a/internal/controller/references_envtest_test.go b/internal/controller/references_envtest_test.go index 1320ef8..36faa93 100644 --- a/internal/controller/references_envtest_test.go +++ b/internal/controller/references_envtest_test.go @@ -83,7 +83,7 @@ func referenceCases(t *testing.T, c *cluster) { { desc: "the RemoteMCPServer of a tool", agent: agentSpec("With a server.", map[string]any{toolsField: []any{map[string]any{"mcp": map[string]any{"server": server}}}}), - gvk: serverGVK, ref: "ref-server", spec: map[string]any{"url": "https://tools.example.com/mcp", descriptionField: "tools"}, + gvk: serverGVK, ref: "ref-server", spec: map[string]any{urlField: "https://tools.example.com/mcp", descriptionField: "tools"}, }, } { t.Run(tc.desc, func(t *testing.T) { diff --git a/main.go b/main.go index b7ffa70..2197c31 100644 --- a/main.go +++ b/main.go @@ -71,6 +71,8 @@ func run() error { flag.StringVar(&cfg.Chart.SemverFilter, "agent-chart-semver-filter", "", "Regular expression the agent chart's tags must match before the range is evaluated, as the OCIRepository's ref.semverFilter; empty filters nothing") flag.StringVar(&cfg.Chart.Interval, "ocirepository-interval", "30m", "OCIRepository.spec.interval of the agent chart's source") flag.StringVar(&cfg.Chart.APIVersion, "flux-ocirepository-api-version", "source.toolkit.fluxcd.io/v1", "source.toolkit.fluxcd.io API version of the OCIRepository") + flag.StringVar(&cfg.Chart.MigrationReport, "agent-chart-migration-report", controller.DefaultMigrationReport, "agent-manager migrate's report ConfigMap in an organization namespace: an existing OCIRepository moves to a higher agent chart major only while it carries "+controller.MigrationReadyAnnotation+" with that major, or no HelmRelease there uses it") + flag.DurationVar(&cfg.Chart.MigrationPoll, "agent-chart-migration-poll", controller.DefaultMigrationPoll, "How often an organization whose chart source waits at its major looks for migrate's annotation again") flag.StringVar(&cfg.HelmServiceAccount, "helmrelease-service-account", "kagent-flux", "The ServiceAccount the organization's HelmReleases run as, kept in every organization namespace; empty keeps none") flag.StringVar(&cfg.HelmClusterRole, "helm-cluster-role", "agent-platform-tenant-flux", "ClusterRole bound to --helmrelease-service-account in every organization namespace") flag.StringVar(&serviceAccountBindings, "service-account-bindings", "", `JSON list of {"clusterRole": ..., "serviceAccount": {"namespace": ..., "name": ...}}: each ClusterRole is bound to that ServiceAccount of another namespace in every organization namespace, by a RoleBinding named after the ClusterRole, so it holds the ClusterRole there and nowhere it is not bound (Substrate's credential providers); a ClusterRole removed from the list loses its bindings; empty binds none`) From 7a514c423e6ea62fe32e97d764a9ba4b76d1df8b Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 14:39:12 +0100 Subject: [PATCH 3/9] fix(organization): hold a recreated chart source and refuse a range of no or several majors A missing chart source whose namespace has a HelmRelease that last deployed a lower major is created only once agent-manager's migrate marks the namespace ready, as a move of the source would wait. A configured range that admits no release version (a pre-release pin) or several majors (>=2.6.0) creates and moves no source and sets Ready=False with reason ChartRangeInvalid instead of waiting for a mark migrate never writes. The mark must also name every HelmRelease on the source (agent-platform.giantswarm.io/agent-chart-ready-releases): a release created after migrate's run holds the move, and the condition says to run migrate again. --- README.md | 2 +- internal/controller/chartmajor.go | 175 +++++++++++++----- internal/controller/chartsource_test.go | 111 ++++++++++- internal/controller/objects.go | 41 +++- .../controller/organization_envtest_test.go | 2 +- 5 files changed, 260 insertions(+), 71 deletions(-) diff --git a/README.md b/README.md index 486be17..81c8f54 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ The operator finds the namespace by the `organization-uid` label, never by its n In the namespace the operator keeps, from the first reconcile on: - the network policies `networkPolicy.names`, copied from `platformNamespace`; -- the agent chart's OCIRepository (`agentChart.*`), named after the chart (`agent`). Every reconcile brings its `spec.url`, `spec.interval` and `spec.ref` back to `agentChart.*`, so a changed chart URL, range or filter reaches existing organizations too; its other fields and labels stay. A move of `spec.ref` to a higher major (`2.x` to `3.x`) waits per organization until agent-manager's migrate annotates its report ConfigMap there (`agentChart.migrationReport`) with `agent-platform.giantswarm.io/agent-chart-ready-major` set to the new major, that is, until every release there is on that major's values; an organization with no HelmRelease on the source moves at once. While it waits, the source keeps its range, the organization is not Ready (reason `ChartSourceHeld`) and it looks again every `agentChart.migrationPoll`. Organizations do not pin their own chart version; +- the agent chart's OCIRepository (`agentChart.*`), named after the chart (`agent`). Every reconcile brings its `spec.url`, `spec.interval` and `spec.ref` back to `agentChart.*`, so a changed chart URL, range or filter reaches existing organizations too; its other fields and labels stay. A move of `spec.ref` to a higher major (`2.x` to `3.x`) waits per organization until agent-manager's migrate annotates its report ConfigMap there (`agentChart.migrationReport`) with `agent-platform.giantswarm.io/agent-chart-ready-major` set to the new major, that is, until every release there is on that major's values, and the annotation `agent-platform.giantswarm.io/agent-chart-ready-releases` names every HelmRelease on the source (one created after migrate's run holds the move until migrate runs again); an organization with no HelmRelease on the source moves at once. A missing source is created only on the same terms when a release there last deployed a lower major. While it waits, the source keeps its range, the organization is not Ready (reason `ChartSourceHeld`, naming the releases and the re-run) and it looks again every `agentChart.migrationPoll`. A configured range of no release major (a pre-release alone) or of several (`>=2.6.0`) creates and moves no source: reason `ChartRangeInvalid`. Organizations do not pin their own chart version; - the Helm ServiceAccount `helmReleaseServiceAccount`, which the organization's HelmReleases run as, with a RoleBinding to the ClusterRole `agent-platform-tenant-flux`; - a mirror of each admin binding in the parent namespace: the same name, the roleRef `agent-platform:organizations-admin`, and the `User` and `Group` subjects only. The operator skips ServiceAccount subjects and subjects whose name starts with `system:`. A subject that leaves the parent binding leaves the mirror, and the mirror goes when the parent binding goes or its deletion starts (a finalizer may hold it). These parent bindings are mirrored: - every RoleBinding to the ClusterRole `agent-platform:organizations-admin`; diff --git a/internal/controller/chartmajor.go b/internal/controller/chartmajor.go index b04f612..e4223ee 100644 --- a/internal/controller/chartmajor.go +++ b/internal/controller/chartmajor.go @@ -6,6 +6,7 @@ import ( "regexp" "slices" "strconv" + "strings" "time" "github.com/Masterminds/semver/v3" @@ -27,47 +28,127 @@ const MigrationReadyAnnotation = "agent-platform.giantswarm.io/agent-chart-ready // DefaultMigrationReport is agent-manager migrate's report ConfigMap. const DefaultMigrationReport = "agent-manager-migrate-report" +// MigrationReadyReleasesAnnotation is set beside MigrationReadyAnnotation to +// the comma-separated names of the HelmReleases the run found on target +// values (agent-manager's migrate.OrganizationReadyReleasesAnnotation). A +// release on the source that it does not name was created after the run read +// the namespace: the mark does not cover it, and migrate must run again. +const MigrationReadyReleasesAnnotation = "agent-platform.giantswarm.io/agent-chart-ready-releases" + // DefaultMigrationPoll is how often an organization whose chart source is // held at its major looks for migrate's mark again. const DefaultMigrationPoll = time.Minute -const reasonChartSourceHeld = "ChartSourceHeld" +const ( + reasonChartSourceHeld = "ChartSourceHeld" + reasonChartRangeInvalid = "ChartRangeInvalid" +) -// majorMove is the major a move of an existing chart source from ref to the -// configured range crosses into: the configured range's highest major when it -// is above every major the source's range admits, else 0 (within a major, or -// back down, nothing waits). A source range that admits no release version, -// or has none (a tag or digest the operator never writes), is read as below -// any major, so the move waits too. -func (c ChartSource) majorMove(ref map[string]any) uint64 { - to := rangeMajors(c.Semver) - if len(to) == 0 { - return 0 - } - target := to[len(to)-1] - from, _ := ref[fieldSemver].(string) - if have := rangeMajors(from); len(have) > 0 && have[len(have)-1] >= target { - return 0 +// targetMajor is the one release major the configured range admits; a range +// of none (only pre-releases, or not a range) or of several (an open range +// such as >=2.6.0) is refused: the operator could not tell which major's +// values the organization's releases need, and migrate marks one major only. +func (c ChartSource) targetMajor(ns string) (uint64, *notReadyError) { + switch to := rangeMajors(c.Semver); len(to) { + case 1: + return to[0], nil + case 0: + return 0, ¬ReadyError{reason: reasonChartRangeInvalid, message: fmt.Sprintf( + "the agent chart range %q admits no release version, so the chart source in %s is neither created nor moved: configure a range of one major (agentChart.semver, e.g. \">=3.0.0 <4.0.0\")", c.Semver, ns)} + default: + return 0, ¬ReadyError{reason: reasonChartRangeInvalid, message: fmt.Sprintf( + "the agent chart range %q admits majors %v, so the chart source in %s is neither created nor moved: agent-manager's migrate readies an organization for one major; bound the range below the next major (agentChart.semver, e.g. \">=3.0.0 <4.0.0\")", c.Semver, to, ns)} } - return target +} + +// crossesMajor reports whether a source on ref moving to target crosses into +// a higher major: every major ref's range admits is below target. A range +// that admits no release version, or none (a tag or digest the operator never +// writes), is read as below any major, so the move waits too. +func crossesMajor(ref map[string]any, target uint64) bool { + from, _ := ref[fieldSemver].(string) + have := rangeMajors(from) + return len(have) == 0 || have[len(have)-1] < target } // chartSourceHeld is the cause of Ready=False while a chart source waits at -// its major; it reconciles the organization again after poll. +// its major (or, missing, waits to be created); it reconciles the +// organization again after poll. func chartSourceHeld(ns, name string, major uint64, why string, poll time.Duration) *notReadyError { return ¬ReadyError{reason: reasonChartSourceHeld, requeueAfter: poll, message: fmt.Sprintf( - "the agent chart source %s/%s stays on its range until agent-manager's migrate marks the namespace ready for chart %d.x (%s): %s", ns, name, major, MigrationReadyAnnotation, why)} + "the agent chart source %s/%s is not moved to chart %d.x until agent-manager's migrate marks the namespace ready for it (%s): %s; run migrate again once its report's releases are fixed (kubectl create job --from=cronjob/-agent-manager-migrate)", ns, name, major, MigrationReadyAnnotation, why)} } -// migrationReady reports whether the chart source name in ns may move to -// major: migrate's report there carries MigrationReadyAnnotation with that -// major, or no HelmRelease of the namespace renders from the source (nothing -// whose values could still be the old major's). why says what holds it. -func (r *OrganizationReconciler) migrationReady(ctx context.Context, ns, name string, major uint64) (ready bool, why string, err error) { +// releasesOn are the HelmReleases of ns whose chart is the OCIRepository +// name; served is false when the cluster serves no HelmRelease (or none is +// configured). +func (r *OrganizationReconciler) releasesOn(ctx context.Context, reader client.Reader, ns, name string) (rels []unstructured.Unstructured, served bool, err error) { + gvk := r.Config.Erasure.HelmRelease + if gvk.Empty() { + return nil, false, nil + } + list := &unstructured.UnstructuredList{} + list.SetGroupVersionKind(gvk.GroupVersion().WithKind(gvk.Kind + "List")) + if err := reader.List(ctx, list, client.InNamespace(ns)); err != nil { + if meta.IsNoMatchError(err) || apierrors.IsNotFound(err) { + return nil, false, nil + } + return nil, false, fmt.Errorf("list the HelmReleases of %s: %w", ns, err) + } + for i := range list.Items { + ref, _, _ := unstructured.NestedStringMap(list.Items[i].Object, "spec", "chartRef") + if ref["kind"] == "OCIRepository" && ref[fieldName] == name && (ref[fieldNamespace] == "" || ref[fieldNamespace] == ns) { + rels = append(rels, list.Items[i]) + } + } + return rels, true, nil +} + +// deployedMajor is the chart major a HelmRelease last deployed +// (status.history[0].chartVersion); ok is false when it never deployed one. +func deployedMajor(hr unstructured.Unstructured) (uint64, bool) { + history, _, _ := unstructured.NestedSlice(hr.Object, "status", "history") + if len(history) == 0 { + return 0, false + } + entry, _ := history[0].(map[string]any) + version, _ := entry["chartVersion"].(string) + v, err := semver.NewVersion(version) + if err != nil { + return 0, false + } + return v.Major(), true +} + +// migrationReady reports whether the chart source name in ns may move to (or, +// missing, be created on) major: no HelmRelease of the namespace renders from +// the source, or migrate's report there carries MigrationReadyAnnotation with +// that major and names every such release in MigrationReadyReleasesAnnotation. +// For a missing source (recreated) only releases whose deployed chart is of a +// lower major count: within a major nothing waits. why says what holds it. +func (r *OrganizationReconciler) migrationReady(ctx context.Context, ns, name string, major uint64, creating bool) (ready bool, why string, err error) { reader := r.APIReader if reader == nil { reader = r.Client } + rels, served, err := r.releasesOn(ctx, reader, ns, name) + if err != nil { + return false, "", err + } + var using []string + for _, hr := range rels { + if m, ok := deployedMajor(hr); creating && (!ok || m >= major) { + continue + } + using = append(using, hr.GetName()) + } + slices.Sort(using) + if served && len(using) == 0 { + return true, "", nil + } + if creating && !served { + return true, "", nil // nothing to tell a recreated source's releases by + } report := r.Config.Chart.MigrationReport if report == "" { report = DefaultMigrationReport @@ -75,11 +156,23 @@ func (r *OrganizationReconciler) migrationReady(ctx context.Context, ns, name st cm := &corev1.ConfigMap{} switch err := reader.Get(ctx, client.ObjectKey{Namespace: ns, Name: report}, cm); { case err == nil: - if got := cm.Annotations[MigrationReadyAnnotation]; got == strconv.FormatUint(major, 10) { - return true, "", nil - } else if got != "" { + got := cm.Annotations[MigrationReadyAnnotation] + switch { + case got == strconv.FormatUint(major, 10): + marked := strings.Split(cm.Annotations[MigrationReadyReleasesAnnotation], ",") + var after []string + for _, name := range using { + if !slices.Contains(marked, name) { + after = append(after, name) + } + } + if len(after) == 0 { + return true, "", nil + } + why = fmt.Sprintf("its report %s marks it ready, but HelmReleases %v on the source were created after that run", report, after) + case got != "": why = fmt.Sprintf("its report %s marks it ready for %s.x only", report, got) - } else { + default: why = fmt.Sprintf("its report %s names releases not on %d.x values yet", report, major) } case apierrors.IsNotFound(err): @@ -87,30 +180,10 @@ func (r *OrganizationReconciler) migrationReady(ctx context.Context, ns, name st default: return false, "", fmt.Errorf("get the migrate report %s/%s: %w", ns, report, err) } - gvk := r.Config.Erasure.HelmRelease - if gvk.Empty() { - return false, why, nil - } - list := &unstructured.UnstructuredList{} - list.SetGroupVersionKind(gvk.GroupVersion().WithKind(gvk.Kind + "List")) - if err := reader.List(ctx, list, client.InNamespace(ns)); err != nil { - if meta.IsNoMatchError(err) || apierrors.IsNotFound(err) { - return true, "", nil // Flux's HelmRelease is not served: no release to wait for - } - return false, "", fmt.Errorf("list the HelmReleases of %s: %w", ns, err) - } - var using []string - for i := range list.Items { - ref, _, _ := unstructured.NestedStringMap(list.Items[i].Object, "spec", "chartRef") - if ref["kind"] == "OCIRepository" && ref[fieldName] == name && (ref[fieldNamespace] == "" || ref[fieldNamespace] == ns) { - using = append(using, list.Items[i].GetName()) - } + if len(using) > 0 { + why = fmt.Sprintf("%s; HelmReleases on it: %v", why, using) } - if len(using) == 0 { - return true, "", nil - } - slices.Sort(using) - return false, fmt.Sprintf("%s; HelmReleases on it: %v", why, using), nil + return false, why, nil } // versionLiteral is a version a range names (2, 2.6, 2.6.1, v3.0.0-rc.1). diff --git a/internal/controller/chartsource_test.go b/internal/controller/chartsource_test.go index f6a0c62..84f0a03 100644 --- a/internal/controller/chartsource_test.go +++ b/internal/controller/chartsource_test.go @@ -3,6 +3,7 @@ package controller import ( "context" "errors" + "strings" "testing" "time" @@ -201,16 +202,32 @@ func chartRelease(name, source string) *unstructured.Unstructured { return u } +// deployed is a release that last deployed chart version. +func deployed(hr *unstructured.Unstructured, version string) *unstructured.Unstructured { + _ = unstructured.SetNestedSlice(hr.Object, []any{map[string]any{"chartVersion": version, "status": "deployed"}}, "status", "history") + return hr +} + // migrateReport is agent-manager migrate's report in chartNS, marked ready -// for major when it is not empty. -func migrateReport(major string) *corev1.ConfigMap { +// for major, naming releases, when major is not empty. +func migrateReport(major string, releases ...string) *corev1.ConfigMap { cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: chartNS, Name: DefaultMigrationReport}} if major != "" { - cm.Annotations = map[string]string{MigrationReadyAnnotation: major} + cm.Annotations = map[string]string{MigrationReadyAnnotation: major, MigrationReadyReleasesAnnotation: strings.Join(releases, ",")} } return cm } +// gateScheme knows ConfigMaps and the HelmRelease as unstructured. +func gateScheme(t *testing.T) *runtime.Scheme { + t.Helper() + scheme := runtime.NewScheme() + require.NoError(t, corev1.AddToScheme(scheme)) + scheme.AddKnownTypeWithName(testHelmReleaseGVK, &unstructured.Unstructured{}) + scheme.AddKnownTypeWithName(testHelmReleaseGVK.GroupVersion().WithKind("HelmReleaseList"), &unstructured.UnstructuredList{}) + return scheme +} + // A move of an organization's chart source to a higher major waits for // agent-manager migrate's mark on its report in the namespace, unless no // HelmRelease there uses the source (D-GO-03). Held, the source keeps its @@ -234,7 +251,16 @@ func TestEnsureChartSourceWaitsForMigrateAcrossAMajor(t *testing.T) { {name: "a report marked for the old major: held", semver: v3, from: v2Ref, objects: []client.Object{chartRelease("triage", chart.Name()), migrateReport("2")}, mentions: "ready for 2.x only"}, {name: "a report marked for the new major: moved", semver: v3, from: v2Ref, - objects: []client.Object{chartRelease("triage", chart.Name()), migrateReport("3")}, moved: true}, + objects: []client.Object{chartRelease("triage", chart.Name()), migrateReport("3", "triage")}, moved: true}, + {name: "a release created after migrate's run: held", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease("triage", chart.Name()), chartRelease("late", chart.Name()), migrateReport("3", "triage")}, + mentions: "HelmReleases [late] on the source were created after that run"}, + {name: "a release of another kind with the source's name does not count", semver: v3, from: v2Ref, + objects: []client.Object{func() client.Object { + hr := chartRelease("chart", chart.Name()) + _ = unstructured.SetNestedField(hr.Object, "HelmChart", "spec", "chartRef", "kind") + return hr + }()}, moved: true}, {name: "no release on the source: moved without a report", semver: v3, from: v2Ref, objects: []client.Object{chartRelease("dashboards", "dashboards")}, moved: true}, {name: "a move within a major never waits", semver: chartRange, from: map[string]any{fieldSemver: "2.6.x"}, @@ -246,10 +272,7 @@ func TestEnsureChartSourceWaitsForMigrateAcrossAMajor(t *testing.T) { } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - scheme := runtime.NewScheme() - require.NoError(t, corev1.AddToScheme(scheme)) - scheme.AddKnownTypeWithName(testHelmReleaseGVK, &unstructured.Unstructured{}) - scheme.AddKnownTypeWithName(testHelmReleaseGVK.GroupVersion().WithKind("HelmReleaseList"), &unstructured.UnstructuredList{}) + scheme := gateScheme(t) spec := chartSpec(map[string]any{fieldURL: "oci://old.example.com/charts/giantswarm/agent", fieldRef: tc.from}) c := fake.NewClientBuilder().WithScheme(scheme).WithObjects(append(tc.objects, chartCopy(ownLabels(ScopeNamespace), spec))...).Build() cfg := chart @@ -314,3 +337,75 @@ func TestRequeueAfter(t *testing.T) { assert.Zero(t, requeueAfter(errors.Join(errors.New("failed"), ¬ReadyError{reason: reasonNameTaken}))) assert.Equal(t, time.Second, requeueAfter(errors.Join(¬ReadyError{requeueAfter: time.Minute}, ¬ReadyError{requeueAfter: time.Second}))) } + +// A configured range of no release major or of several creates and moves +// nothing and says so (ChartRangeInvalid), never waiting silently for a mark +// migrate cannot write (D-GO-29). +func TestEnsureChartSourceRefusesARangeOfNoneOrSeveralMajors(t *testing.T) { + for rng, mentions := range map[string]string{ + "3.0.0-rc.1": "admits no release version", + "not a range": "admits no release version", + ">=2.6.0": "admits majors [2 3 4", + "2.6.0 || 3.0.1": "admits majors [2 3]", + } { + t.Run(rng, func(t *testing.T) { + from := map[string]any{fieldSemver: v2Line} + c := fake.NewClientBuilder().WithScheme(gateScheme(t)).WithObjects(chartCopy(ownLabels(ScopeNamespace), chartSpec(map[string]any{fieldRef: from}))).Build() + cfg := chart + cfg.Semver = rng + r := &OrganizationReconciler{Client: c, Config: Config{Chart: cfg, Erasure: ErasureConfig{HelmRelease: testHelmReleaseGVK}}} + err := r.ensureChartSource(t.Context(), chartNS) + var nr *notReadyError + require.ErrorAs(t, err, &nr) + assert.Equal(t, reasonChartRangeInvalid, nr.reason) + assert.Contains(t, nr.message, mentions) + got := chartCopy(nil, nil) + require.NoError(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), got)) + ref, _, _ := unstructured.NestedMap(got.Object, "spec", fieldRef) + assert.Equal(t, from, ref, "the ref stays") + + // Missing, it is not created on such a range. + c = fake.NewClientBuilder().WithScheme(gateScheme(t)).Build() + r.Client = c + require.ErrorAs(t, r.ensureChartSource(t.Context(), chartNS), &nr) + assert.Equal(t, reasonChartRangeInvalid, nr.reason) + assert.Error(t, c.Get(t.Context(), client.ObjectKeyFromObject(got), chartCopy(nil, nil))) + }) + } +} + +// A recreated source (missing while releases use it) waits for migrate's +// mark when a release there last deployed a lower major (D-GO-29). +func TestEnsureChartSourceRecreatedWaitsForMigrate(t *testing.T) { + const v3 = ">=3.0.0 <4.0.0" + for name, tc := range map[string]struct { + semver string + objects []client.Object + created bool + }{ + "a release on 2.x, no mark: not created": {v3, []client.Object{deployed(chartRelease("triage", chart.Name()), "2.6.1")}, false}, + "a release on 2.x, marked: created": {v3, []client.Object{deployed(chartRelease("triage", chart.Name()), "2.6.1"), migrateReport("3", "triage")}, true}, + "a release already on 3.x: created": {v3, []client.Object{deployed(chartRelease("triage", chart.Name()), "3.0.0")}, true}, + "a release never deployed: created": {v3, []client.Object{chartRelease("triage", chart.Name())}, true}, + "within a major nothing waits": {chartRange, []client.Object{deployed(chartRelease("triage", chart.Name()), "2.6.1")}, true}, + } { + t.Run(name, func(t *testing.T) { + c := fake.NewClientBuilder().WithScheme(gateScheme(t)).WithObjects(tc.objects...).Build() + cfg := chart + cfg.Semver = tc.semver + r := &OrganizationReconciler{Client: c, Config: Config{Chart: cfg, Erasure: ErasureConfig{HelmRelease: testHelmReleaseGVK}}} + err := r.ensureChartSource(t.Context(), chartNS) + getErr := c.Get(t.Context(), client.ObjectKeyFromObject(chartCopy(nil, nil)), chartCopy(nil, nil)) + if tc.created { + require.NoError(t, err) + require.NoError(t, getErr) + return + } + var nr *notReadyError + require.ErrorAs(t, err, &nr) + assert.Equal(t, reasonChartSourceHeld, nr.reason) + assert.Contains(t, nr.message, "HelmReleases on it: [triage]") + assert.Error(t, getErr, "not created") + }) + } +} diff --git a/internal/controller/objects.go b/internal/controller/objects.go index 78fd0b6..3323546 100644 --- a/internal/controller/objects.go +++ b/internal/controller/objects.go @@ -214,15 +214,35 @@ func (r *OrganizationReconciler) ensureScoped(ctx context.Context, ns, scope str // not Ready (reason ChartSourceHeld) and looks again after MigrationPoll. A // release still on the old major's values would otherwise fail every upgrade // on the new chart (agent chart 3.0 refuses muster.requireApproval) and stay -// on its old revision until edited by hand. +// on its old revision until edited by hand. A missing source whose +// namespace has releases deployed from a lower major is not created until +// the same mark. A configured range of no or several majors creates and +// moves nothing (reason ChartRangeInvalid). func (r *OrganizationReconciler) ensureChartSource(ctx context.Context, ns string) error { want := r.Config.Chart.object(ns) wantLabels := stamp(want, ns, ScopeNamespace, "") kind := want.GetKind() + poll := r.Config.Chart.MigrationPoll + if poll <= 0 { + poll = DefaultMigrationPoll + } + target, invalid := r.Config.Chart.targetMajor(ns) existing := object(want.GroupVersionKind()) err := r.Client.Get(ctx, client.ObjectKeyFromObject(want), existing) switch { case apierrors.IsNotFound(err): + if invalid != nil { + return invalid + } + // A recreated source: releases deployed from a lower major still + // wait for migrate's mark, as a move of the source would. + ready, why, err := r.migrationReady(ctx, ns, want.GetName(), target, true) + if err != nil { + return err + } + if !ready { + return chartSourceHeld(ns, want.GetName(), target, why, poll) + } return r.create(ctx, want, kind) case err != nil: return fmt.Errorf("get %s %s/%s: %w", kind, ns, want.GetName(), err) @@ -239,21 +259,22 @@ func (r *OrganizationReconciler) ensureChartSource(ctx context.Context, ns strin var held error if !reflect.DeepEqual(spec[fieldRef], wantSpec[fieldRef]) { have, _ := spec[fieldRef].(map[string]any) - if major := r.Config.Chart.majorMove(have); major > 0 { - ready, why, err := r.migrationReady(ctx, ns, want.GetName(), major) + switch { + case invalid != nil: + held = invalid + case crossesMajor(have, target): + ready, why, err := r.migrationReady(ctx, ns, want.GetName(), target, false) if err != nil { return err } if !ready { - poll := r.Config.Chart.MigrationPoll - if poll <= 0 { - poll = DefaultMigrationPoll - } - held = chartSourceHeld(ns, want.GetName(), major, why, poll) - wantSpec = maps.Clone(wantSpec) - wantSpec[fieldRef] = spec[fieldRef] + held = chartSourceHeld(ns, want.GetName(), target, why, poll) } } + if held != nil { + wantSpec = maps.Clone(wantSpec) + wantSpec[fieldRef] = spec[fieldRef] + } } labels := copiedLabels(existing.GetLabels(), wantLabels, false) same := maps.Equal(labels, existing.GetLabels()) diff --git a/internal/controller/organization_envtest_test.go b/internal/controller/organization_envtest_test.go index 11872ab..7f00b96 100644 --- a/internal/controller/organization_envtest_test.go +++ b/internal/controller/organization_envtest_test.go @@ -146,7 +146,7 @@ func TestOrganizationEnvtest(t *testing.T) { // again on its own (MigrationPoll) and moves. require.NoError(t, c.admin.Create(t.Context(), &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{ Namespace: ns.Name, Name: controller.DefaultMigrationReport, - Annotations: map[string]string{controller.MigrationReadyAnnotation: "2"}, + Annotations: map[string]string{controller.MigrationReadyAnnotation: "2", controller.MigrationReadyReleasesAnnotation: "triage"}, }})) c.eventually(t, ociGVK, ns.Name, agentChart, func(ct *assert.CollectT, u *unstructured.Unstructured) { ref, _, _ := unstructured.NestedMap(u.Object, "spec", "ref") From 701ccedd2fd302b1f29f80a209dccd99b677762b Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 15:32:20 +0100 Subject: [PATCH 4/9] fix(controller): report ChartRangeInvalid when the source already carries the range An invalid range (several majors or none) was reported only when the chart source was missing or its ref differed. A source that already carried it (>=2.6.0) stayed Ready and Flux would move it to a major migrate never marked. Also pin the ref that names no major and the newest-first history order. --- internal/controller/chartsource_test.go | 30 +++++++++--- internal/controller/envtest_test.go | 6 ++- internal/controller/objects.go | 6 ++- .../controller/organization_envtest_test.go | 48 +++++++++++++++++++ 4 files changed, 82 insertions(+), 8 deletions(-) diff --git a/internal/controller/chartsource_test.go b/internal/controller/chartsource_test.go index 84f0a03..6c1e345 100644 --- a/internal/controller/chartsource_test.go +++ b/internal/controller/chartsource_test.go @@ -20,6 +20,7 @@ import ( ) const ( + noReport = "no migrate run has written its report" v2Line = "2.x" chartNS = "agents-payments-abcde" chartRange = "2.7.x" @@ -208,6 +209,17 @@ func deployed(hr *unstructured.Unstructured, version string) *unstructured.Unstr return hr } +// deployedHistory is a release whose Helm history lists versions newest +// first, as Flux writes it (status.history[0] is the last deployed). +func deployedHistory(hr *unstructured.Unstructured, versions ...string) *unstructured.Unstructured { + var history []any + for _, v := range versions { + history = append(history, map[string]any{"chartVersion": v, "status": "deployed"}) + } + _ = unstructured.SetNestedSlice(hr.Object, history, "status", "history") + return hr +} + // migrateReport is agent-manager migrate's report in chartNS, marked ready // for major, naming releases, when major is not empty. func migrateReport(major string, releases ...string) *corev1.ConfigMap { @@ -245,7 +257,7 @@ func TestEnsureChartSourceWaitsForMigrateAcrossAMajor(t *testing.T) { mentions string }{ {name: "a release on the source and no report: held", semver: v3, from: v2Ref, - objects: []client.Object{chartRelease("triage", chart.Name())}, mentions: "no migrate run has written its report"}, + objects: []client.Object{chartRelease("triage", chart.Name())}, mentions: noReport}, {name: "a report without the mark: held", semver: v3, from: v2Ref, objects: []client.Object{chartRelease("triage", chart.Name()), migrateReport("")}, mentions: "names releases not on 3.x values yet"}, {name: "a report marked for the old major: held", semver: v3, from: v2Ref, @@ -255,6 +267,10 @@ func TestEnsureChartSourceWaitsForMigrateAcrossAMajor(t *testing.T) { {name: "a release created after migrate's run: held", semver: v3, from: v2Ref, objects: []client.Object{chartRelease("triage", chart.Name()), chartRelease("late", chart.Name()), migrateReport("3", "triage")}, mentions: "HelmReleases [late] on the source were created after that run"}, + {name: "a source on a tag names no major: held", semver: v3, from: map[string]any{"tag": "latest"}, + objects: []client.Object{chartRelease("triage", chart.Name())}, mentions: noReport}, + {name: "a source on a digest names no major: held", semver: v3, from: map[string]any{"digest": "sha256:0000000000000000000000000000000000000000000000000000000000000000"}, + objects: []client.Object{chartRelease("triage", chart.Name())}, mentions: noReport}, {name: "a release of another kind with the source's name does not count", semver: v3, from: v2Ref, objects: []client.Object{func() client.Object { hr := chartRelease("chart", chart.Name()) @@ -383,11 +399,13 @@ func TestEnsureChartSourceRecreatedWaitsForMigrate(t *testing.T) { objects []client.Object created bool }{ - "a release on 2.x, no mark: not created": {v3, []client.Object{deployed(chartRelease("triage", chart.Name()), "2.6.1")}, false}, - "a release on 2.x, marked: created": {v3, []client.Object{deployed(chartRelease("triage", chart.Name()), "2.6.1"), migrateReport("3", "triage")}, true}, - "a release already on 3.x: created": {v3, []client.Object{deployed(chartRelease("triage", chart.Name()), "3.0.0")}, true}, - "a release never deployed: created": {v3, []client.Object{chartRelease("triage", chart.Name())}, true}, - "within a major nothing waits": {chartRange, []client.Object{deployed(chartRelease("triage", chart.Name()), "2.6.1")}, true}, + "a release on 2.x, no mark: not created": {v3, []client.Object{deployed(chartRelease("triage", chart.Name()), "2.6.1")}, false}, + "a release on 2.x, marked: created": {v3, []client.Object{deployed(chartRelease("triage", chart.Name()), "2.6.1"), migrateReport("3", "triage")}, true}, + "a release already on 3.x: created": {v3, []client.Object{deployed(chartRelease("triage", chart.Name()), "3.0.0")}, true}, + "a release never deployed: created": {v3, []client.Object{chartRelease("triage", chart.Name())}, true}, + "a release deployed 2.x once, now on 3.x (newest history first): created": {v3, []client.Object{deployedHistory(chartRelease("triage", chart.Name()), "3.0.0", "2.6.1")}, true}, + "a release now on 2.x after 3.x (newest history first): not created": {v3, []client.Object{deployedHistory(chartRelease("triage", chart.Name()), "2.6.1", "3.0.0")}, false}, + "within a major nothing waits": {chartRange, []client.Object{deployed(chartRelease("triage", chart.Name()), "2.6.1")}, true}, } { t.Run(name, func(t *testing.T) { c := fake.NewClientBuilder().WithScheme(gateScheme(t)).WithObjects(tc.objects...).Build() diff --git a/internal/controller/envtest_test.go b/internal/controller/envtest_test.go index 0967b5f..0aa599f 100644 --- a/internal/controller/envtest_test.go +++ b/internal/controller/envtest_test.go @@ -143,7 +143,7 @@ type cluster struct { // commit mode, as the chart's ServiceAccount. Skipped without envtest binaries: run via // `make test-envtest`, which resolves KUBEBUILDER_ASSETS with setup-envtest // (and needs helm). -func startEnvtest(t *testing.T) *cluster { +func startEnvtest(t *testing.T, options ...func(*controller.Config)) *cluster { t.Helper() if os.Getenv("KUBEBUILDER_ASSETS") == "" { t.Skip("KUBEBUILDER_ASSETS not set; run via `make test-envtest`") @@ -265,6 +265,10 @@ func startEnvtest(t *testing.T) *cluster { }, }} + for _, option := range options { + option(&c.config) + } + asOperator := rest.CopyConfig(cfg) asOperator.Impersonate = rest.ImpersonationConfig{UserName: operator} mgr, err := ctrl.NewManager(asOperator, ctrl.Options{ diff --git a/internal/controller/objects.go b/internal/controller/objects.go index 3323546..59cea04 100644 --- a/internal/controller/objects.go +++ b/internal/controller/objects.go @@ -257,11 +257,15 @@ func (r *OrganizationReconciler) ensureChartSource(ctx context.Context, ns strin } wantSpec, _ := want.Object["spec"].(map[string]any) var held error + if invalid != nil { + // An invalid range is reported also when the source already carries + // it: Flux would move it to a major migrate never marked (D-GO-37). + held = invalid + } if !reflect.DeepEqual(spec[fieldRef], wantSpec[fieldRef]) { have, _ := spec[fieldRef].(map[string]any) switch { case invalid != nil: - held = invalid case crossesMajor(have, target): ready, why, err := r.migrationReady(ctx, ns, want.GetName(), target, false) if err != nil { diff --git a/internal/controller/organization_envtest_test.go b/internal/controller/organization_envtest_test.go index 7f00b96..593e645 100644 --- a/internal/controller/organization_envtest_test.go +++ b/internal/controller/organization_envtest_test.go @@ -500,3 +500,51 @@ func (c *cluster) namespacesOf(t *testing.T, org *v1alpha1.AgentPlatformOrganiza require.NoError(t, c.admin.List(t.Context(), list, client.MatchingLabels{v1alpha1.OrganizationUIDLabel: string(org.UID)})) return list.Items } + +// A configured range of several majors is reported (ChartRangeInvalid) also +// when the chart source already carries it: Flux would otherwise move the +// source to a major migrate never marked, with Ready staying true (D-GO-37). +func TestChartRangeInvalidEnvtest(t *testing.T) { + const open = ">=2.6.0" + c := startEnvtest(t, func(cfg *controller.Config) { cfg.Chart.Semver = open }) + + invalid := func(ct *assert.CollectT, org *v1alpha1.AgentPlatformOrganization) { + ready := meta.FindStatusCondition(c.get(ct, org).Status.Conditions, v1alpha1.ConditionReady) + if assert.NotNil(ct, ready) { + assert.Equal(ct, metav1.ConditionFalse, ready.Status) + assert.Equal(ct, "ChartRangeInvalid", ready.Reason) + assert.Contains(ct, ready.Message, open) + } + } + + t.Run("a missing source is not created", func(t *testing.T) { + org := c.organization(t, "org-open-missing", "open-missing") + require.EventuallyWithT(t, func(ct *assert.CollectT) { invalid(ct, org) }, timeout, tick) + c.absent(t, ociGVK, c.get(t, org).Status.Namespace, agentChart) + }) + + t.Run("a source that carries the range already stays not Ready", func(t *testing.T) { + org := c.organization(t, "org-open-carried", "open-carried") + var ns string + require.EventuallyWithT(t, func(ct *assert.CollectT) { + ns = c.get(ct, org).Status.Namespace + assert.NotEmpty(ct, ns) + }, timeout, tick) + require.EventuallyWithT(t, func(ct *assert.CollectT) { invalid(ct, org) }, timeout, tick) + + // The copy an older operator wrote: the open range, the operator's + // own labels, the operator's url and interval. + src := newObject(ociGVK, ns, agentChart, map[string]string{controller.ObjectLabel: controller.ScopeNamespace}, + map[string]any{urlField: c.config.Chart.URL, intervalField: c.config.Chart.Interval, "ref": map[string]any{semverField: open}}) + require.NoError(t, c.admin.Create(t.Context(), src)) + + c.poke(t, org) + require.Never(t, func() bool { + ready := meta.FindStatusCondition(c.get(t, org).Status.Conditions, v1alpha1.ConditionReady) + return ready == nil || ready.Status == metav1.ConditionTrue + }, 3*time.Second, tick, "an organization whose source carries an invalid range is Ready") + require.EventuallyWithT(t, func(ct *assert.CollectT) { invalid(ct, org) }, timeout, tick) + ref, _, _ := unstructured.NestedMap(c.read(t, ociGVK, ns, agentChart).Object, "spec", "ref") + assert.Equal(t, map[string]any{semverField: open}, ref, "the operator leaves the ref as it is") + }) +} From 596c498fc2d81cb4df4a6bdb9220814c68018bcb Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 17:20:56 +0100 Subject: [PATCH 5/9] test(controller): skip controller name validation so each envtest starts its own manager --- internal/controller/envtest_test.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/internal/controller/envtest_test.go b/internal/controller/envtest_test.go index 0aa599f..3986aa8 100644 --- a/internal/controller/envtest_test.go +++ b/internal/controller/envtest_test.go @@ -30,6 +30,7 @@ import ( ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/envtest" + ctrlconfig "sigs.k8s.io/controller-runtime/pkg/config" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" "github.com/giantswarm/agent-platform-operator/api/v1alpha1" @@ -271,8 +272,12 @@ func startEnvtest(t *testing.T, options ...func(*controller.Config)) *cluster { asOperator := rest.CopyConfig(cfg) asOperator.Impersonate = rest.ImpersonationConfig{UserName: operator} + // Every test starts its own manager in this process, and controller names + // are unique per process unless the validation is skipped. + skipNameValidation := true mgr, err := ctrl.NewManager(asOperator, ctrl.Options{ Scheme: scheme, + Controller: ctrlconfig.Controller{SkipNameValidation: &skipNameValidation}, Cache: controller.CacheOptions(c.config, time.Hour), Metrics: metricsserver.Options{BindAddress: "0"}, HealthProbeBindAddress: "0", From caf891e80a67d90d9ffc105f671c996818f3d1f1 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Thu, 26 Nov 2026 17:21:09 +0100 Subject: [PATCH 6/9] style(controller): gofmt envtest imports --- internal/controller/envtest_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/controller/envtest_test.go b/internal/controller/envtest_test.go index 3986aa8..0f0fd87 100644 --- a/internal/controller/envtest_test.go +++ b/internal/controller/envtest_test.go @@ -29,8 +29,8 @@ import ( "k8s.io/client-go/rest" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" - "sigs.k8s.io/controller-runtime/pkg/envtest" ctrlconfig "sigs.k8s.io/controller-runtime/pkg/config" + "sigs.k8s.io/controller-runtime/pkg/envtest" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" "github.com/giantswarm/agent-platform-operator/api/v1alpha1" From 86f31d0ed5f1e9720523dd55e3f09d841683b864 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Fri, 27 Nov 2026 00:13:42 +0100 Subject: [PATCH 7/9] docs: condense tool approval docs --- README.md | 2 +- helm/agent-platform-operator/README.md | 6 +++--- helm/agent-platform-operator/values.schema.json | 6 +++--- helm/agent-platform-operator/values.yaml | 16 ++++++---------- 4 files changed, 13 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index 81c8f54..826a3cd 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ The operator finds the namespace by the `organization-uid` label, never by its n In the namespace the operator keeps, from the first reconcile on: - the network policies `networkPolicy.names`, copied from `platformNamespace`; -- the agent chart's OCIRepository (`agentChart.*`), named after the chart (`agent`). Every reconcile brings its `spec.url`, `spec.interval` and `spec.ref` back to `agentChart.*`, so a changed chart URL, range or filter reaches existing organizations too; its other fields and labels stay. A move of `spec.ref` to a higher major (`2.x` to `3.x`) waits per organization until agent-manager's migrate annotates its report ConfigMap there (`agentChart.migrationReport`) with `agent-platform.giantswarm.io/agent-chart-ready-major` set to the new major, that is, until every release there is on that major's values, and the annotation `agent-platform.giantswarm.io/agent-chart-ready-releases` names every HelmRelease on the source (one created after migrate's run holds the move until migrate runs again); an organization with no HelmRelease on the source moves at once. A missing source is created only on the same terms when a release there last deployed a lower major. While it waits, the source keeps its range, the organization is not Ready (reason `ChartSourceHeld`, naming the releases and the re-run) and it looks again every `agentChart.migrationPoll`. A configured range of no release major (a pre-release alone) or of several (`>=2.6.0`) creates and moves no source: reason `ChartRangeInvalid`. Organizations do not pin their own chart version; +- the agent chart's OCIRepository (`agentChart.*`), named after the chart (`agent`). Every reconcile resets its `spec.url`, `spec.interval` and `spec.ref` to `agentChart.*` (other fields and labels stay). A move of `spec.ref` to a higher major (`2.x` to `3.x`) waits per organization until agent-manager's migrate sets `agent-platform.giantswarm.io/agent-chart-ready-major` to the new major on the report ConfigMap (`agentChart.migrationReport`), with `agent-platform.giantswarm.io/agent-chart-ready-releases` naming every HelmRelease on the source; an organization with no HelmRelease on the source moves at once. While it waits the organization is not Ready (`ChartSourceHeld`) and is rechecked every `agentChart.migrationPoll`. A range of no release major (a pre-release alone) or of several (`>=2.6.0`) creates and moves no source: `ChartRangeInvalid`. Organizations do not pin their own chart version; - the Helm ServiceAccount `helmReleaseServiceAccount`, which the organization's HelmReleases run as, with a RoleBinding to the ClusterRole `agent-platform-tenant-flux`; - a mirror of each admin binding in the parent namespace: the same name, the roleRef `agent-platform:organizations-admin`, and the `User` and `Group` subjects only. The operator skips ServiceAccount subjects and subjects whose name starts with `system:`. A subject that leaves the parent binding leaves the mirror, and the mirror goes when the parent binding goes or its deletion starts (a finalizer may hold it). These parent bindings are mirrored: - every RoleBinding to the ClusterRole `agent-platform:organizations-admin`; diff --git a/helm/agent-platform-operator/README.md b/helm/agent-platform-operator/README.md index ae2f0d7..f644fe9 100644 --- a/helm/agent-platform-operator/README.md +++ b/helm/agent-platform-operator/README.md @@ -18,13 +18,13 @@ Reconciles each AgentPlatformOrganization (agent-platform.giantswarm.io) into it | platformNamespace | string | `"kagent"` | The platform namespace (kagent's) the network policies are copied from. | | networkPolicy.flavor | string | `""` | Kind of the network policies copied into every organization namespace: `kubernetes` (NetworkPolicy) or `cilium` (CiliumNetworkPolicy). Empty copies none. | | networkPolicy.names | list | `[]` | Names of the network policies in `platformNamespace` copied into every organization namespace (the platform's worker policy, `substrate-workers` with Cilium, `substrate-workers-ingress` with Kubernetes network policies). | -| agentChart.ociUrl | string | `"oci://gsoci.azurecr.io/charts/giantswarm/agent"` | OCI URL of the agent chart. The OCIRepository kept in every organization namespace is named after its last segment (`agent`); the organization's HelmReleases reference it by that name. The operator brings its url, interval and ref back to these values on every reconcile, also in existing organizations. Empty keeps none. | +| agentChart.ociUrl | string | `"oci://gsoci.azurecr.io/charts/giantswarm/agent"` | OCI URL of the agent chart. The OCIRepository kept in every organization namespace is named after its last segment (`agent`); the organization's HelmReleases reference it by that name. Every reconcile resets its url, interval and ref to these values. Empty keeps none. | | agentChart.semver | string | `"2.x"` | Semver range the OCIRepository tracks. | | agentChart.semverFilter | string | `""` | Regular expression the chart's tags must match before the range is evaluated (the OCIRepository's `ref.semverFilter`); empty filters nothing. | | agentChart.interval | string | `"30m"` | OCIRepository.spec.interval. | | agentChart.ociRepositoryApiVersion | string | `"source.toolkit.fluxcd.io/v1"` | source.toolkit.fluxcd.io API version of the OCIRepository. | -| agentChart.migrationReport | string | `"agent-manager-migrate-report"` | agent-manager migrate's report ConfigMap in an organization namespace. A move of an existing organization's OCIRepository to a higher major (`2.x` to `3.x`) waits until migrate annotates it `agent-platform.giantswarm.io/agent-chart-ready-major` with the new major (every release there on that major's values), or no HelmRelease there uses the source; meanwhile the organization is not Ready (`ChartSourceHeld`). The operator may read this one ConfigMap name only. | -| agentChart.migrationPoll | string | `"1m"` | How often an organization whose chart source waits at its major looks for migrate's annotation again. | +| agentChart.migrationReport | string | `"agent-manager-migrate-report"` | agent-manager migrate's report ConfigMap in an organization namespace. A move to a higher major (`2.x` to `3.x`) waits until migrate annotates it `agent-platform.giantswarm.io/agent-chart-ready-major` with the new major (organization not Ready, `ChartSourceHeld`, meanwhile). The operator reads this one ConfigMap name only. | +| agentChart.migrationPoll | string | `"1m"` | How often a waiting organization looks for migrate's annotation again. | | helmReleaseServiceAccount | string | `"kagent-flux"` | The ServiceAccount the organization's HelmReleases run as (`spec.serviceAccountName`, which helm-controller impersonates), kept in every organization namespace and bound there to the ClusterRole `agent-platform-tenant-flux`. The same name as agent-manager's `flux.helmReleaseServiceAccount`. Empty keeps none. | | serviceAccountBindings | list | `[]` | ClusterRoles bound to a ServiceAccount of another namespace in every organization namespace, such as Substrate's credential providers' Secret readers, which read the Secret an actor's credential names there. Each ClusterRole is bound by a RoleBinding named after it (listed once, not the Helm or Flux binding's name), and the operator gets `bind` on it; a ClusterRole removed from the list loses its bindings. The agent-platform chart's admission policy holds which ServiceAccounts the operator binds there. | | snapshots.bucket | string | `""` | Bucket of the organizations' worker snapshots: an organization's `status.snapshotPrefix` is `s3:///`. Empty leaves it empty. | diff --git a/helm/agent-platform-operator/values.schema.json b/helm/agent-platform-operator/values.schema.json index 784a1d7..aaeb216 100644 --- a/helm/agent-platform-operator/values.schema.json +++ b/helm/agent-platform-operator/values.schema.json @@ -13,11 +13,11 @@ }, "migrationPoll": { "type": "string", - "description": "How often an organization whose chart source waits at its major looks for migrate's annotation again." + "description": "How often a waiting organization looks for migrate's annotation again." }, "migrationReport": { "type": "string", - "description": "agent-manager migrate's report ConfigMap in an organization namespace. A move of an existing organization's OCIRepository to a higher major (`2.x` to `3.x`) waits until migrate annotates it `agent-platform.giantswarm.io/agent-chart-ready-major` with the new major (every release there on that major's values), or no HelmRelease there uses the source; meanwhile the organization is not Ready (`ChartSourceHeld`). The operator may read this one ConfigMap name only." + "description": "agent-manager migrate's report ConfigMap in an organization namespace. A move to a higher major (`2.x` to `3.x`) waits until migrate annotates it `agent-platform.giantswarm.io/agent-chart-ready-major` with the new major (organization not Ready, `ChartSourceHeld`, meanwhile). The operator reads this one ConfigMap name only." }, "ociRepositoryApiVersion": { "type": "string", @@ -25,7 +25,7 @@ }, "ociUrl": { "type": "string", - "description": "OCI URL of the agent chart. The OCIRepository kept in every organization namespace is named after its last segment (`agent`); the organization's HelmReleases reference it by that name. The operator brings its url, interval and ref back to these values on every reconcile, also in existing organizations. Empty keeps none." + "description": "OCI URL of the agent chart. The OCIRepository kept in every organization namespace is named after its last segment (`agent`); the organization's HelmReleases reference it by that name. Every reconcile resets its url, interval and ref to these values. Empty keeps none." }, "semver": { "type": "string", diff --git a/helm/agent-platform-operator/values.yaml b/helm/agent-platform-operator/values.yaml index 1078001..1a6fc89 100644 --- a/helm/agent-platform-operator/values.yaml +++ b/helm/agent-platform-operator/values.yaml @@ -31,9 +31,8 @@ networkPolicy: agentChart: # -- OCI URL of the agent chart. The OCIRepository kept in every # organization namespace is named after its last segment (`agent`); the - # organization's HelmReleases reference it by that name. The operator brings - # its url, interval and ref back to these values on every reconcile, also in - # existing organizations. Empty keeps none. + # organization's HelmReleases reference it by that name. Every reconcile + # resets its url, interval and ref to these values. Empty keeps none. ociUrl: oci://gsoci.azurecr.io/charts/giantswarm/agent # -- Semver range the OCIRepository tracks. semver: "2.x" @@ -45,15 +44,12 @@ agentChart: # -- source.toolkit.fluxcd.io API version of the OCIRepository. ociRepositoryApiVersion: source.toolkit.fluxcd.io/v1 # -- agent-manager migrate's report ConfigMap in an organization namespace. - # A move of an existing organization's OCIRepository to a higher major - # (`2.x` to `3.x`) waits until migrate annotates it + # A move to a higher major (`2.x` to `3.x`) waits until migrate annotates it # `agent-platform.giantswarm.io/agent-chart-ready-major` with the new major - # (every release there on that major's values), or no HelmRelease there uses - # the source; meanwhile the organization is not Ready (`ChartSourceHeld`). - # The operator may read this one ConfigMap name only. + # (organization not Ready, `ChartSourceHeld`, meanwhile). The operator reads + # this one ConfigMap name only. migrationReport: agent-manager-migrate-report - # -- How often an organization whose chart source waits at its major looks - # for migrate's annotation again. + # -- How often a waiting organization looks for migrate's annotation again. migrationPoll: 1m # -- The ServiceAccount the organization's HelmReleases run as From ad0943c614ffa7398b254b569a7a1e798a5d97e0 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Sat, 28 Nov 2026 14:42:55 +0100 Subject: [PATCH 8/9] fix: refuse agent chart ranges that admit a major past 99 Document the range grammar the chart-major classifier reads and refuse a range that admits a chart major of 100 or more as unsupported, as agent-manager's migrate and the agent-platform chart do. --- internal/controller/chartmajor.go | 61 +++++++++++++++++++++++-- internal/controller/chartsource_test.go | 18 ++++++++ 2 files changed, 76 insertions(+), 3 deletions(-) diff --git a/internal/controller/chartmajor.go b/internal/controller/chartmajor.go index e4223ee..5ce6711 100644 --- a/internal/controller/chartmajor.go +++ b/internal/controller/chartmajor.go @@ -49,7 +49,12 @@ const ( // such as >=2.6.0) is refused: the operator could not tell which major's // values the organization's releases need, and migrate marks one major only. func (c ChartSource) targetMajor(ns string) (uint64, *notReadyError) { - switch to := rangeMajors(c.Semver); len(to) { + to := rangeMajors(c.Semver) + if len(to) <= 1 && beyondProbes(c.Semver) { + return 0, ¬ReadyError{reason: reasonChartRangeInvalid, message: fmt.Sprintf( + "the agent chart range %q admits a chart major of %d or more, which the operator does not read, so the chart source in %s is neither created nor moved: configure a range of one major below %d (agentChart.semver, e.g. \">=3.0.0 <4.0.0\")", c.Semver, maxProbedMajor+1, ns, maxProbedMajor+1)} + } + switch len(to) { case 1: return to[0], nil case 0: @@ -68,7 +73,7 @@ func (c ChartSource) targetMajor(ns string) (uint64, *notReadyError) { func crossesMajor(ref map[string]any, target uint64) bool { from, _ := ref[fieldSemver].(string) have := rangeMajors(from) - return len(have) == 0 || have[len(have)-1] < target + return len(have) == 0 || have[len(have)-1] < target || (len(have) == 1 && beyondProbes(from)) } // chartSourceHeld is the cause of Ready=False while a chart source waits at @@ -189,6 +194,50 @@ func (r *OrganizationReconciler) migrationReady(ctx context.Context, ns, name st // versionLiteral is a version a range names (2, 2.6, 2.6.1, v3.0.0-rc.1). var versionLiteral = regexp.MustCompile(`v?([0-9]+)(?:\.([0-9]+))?(?:\.([0-9]+))?`) +// maxProbedMajor is the last major rangeMajors probes. +const maxProbedMajor = 99 + +// beyondProbes reports a range that admits a version of a major above +// maxProbedMajor (one it names, or any of major 100): rangeMajors would read its majors short, so +// it is refused as unsupported (as agent-manager's migrate and the +// agent-platform chart refuse it). +func beyondProbes(rng string) bool { + c, err := semver.NewConstraint(rng) + if err != nil { + return false + } + for _, lit := range versionLiteral.FindAllStringSubmatch(rng, -1) { + maj, err := strconv.ParseUint(lit[1], 10, 64) + if err != nil { + return true + } + if maj <= maxProbedMajor { + continue + } + minor, err2 := strconv.ParseUint("0"+lit[2], 10, 64) + patch, err3 := strconv.ParseUint("0"+lit[3], 10, 64) + if err2 != nil || err3 != nil { + return true + } + for _, v := range []*semver.Version{semver.New(maj, minor, patch, "", ""), semver.New(maj, minor, patch+1, "", ""), semver.New(maj, minor+1, 0, "", "")} { + if c.Check(v) { + return true + } + } + } + const late = 999999 + m := uint64(maxProbedMajor + 1) + if c.Check(semver.New(m, late, late, "", "")) { + return true + } + for n := range uint64(200) { + if c.Check(semver.New(m, n, 0, "", "")) || c.Check(semver.New(m, n, late, "", "")) { + return true + } + } + return false +} + // rangeMajors are the release majors a semver range admits, sorted; none when // it does not parse. Read as agent-manager's migrate reads a target range // (internal/migrate majorsOf) and the agent-platform chart's guard @@ -196,6 +245,12 @@ var versionLiteral = regexp.MustCompile(`v?([0-9]+)(?:\.([0-9]+))?(?:\.([0-9]+)) // next patch and minor, and per major 0-99 the first and a late version of // every minor below 200 and a late minor, each counting only when the range // admits it, so every alternative of a `||` range counts. +// +// Supported grammar, the same in all three: a Masterminds semver range as +// Flux reads it (x-ranges, carets, tildes, comparisons, hyphen ranges, `||` +// alternatives) over release majors 0-99. A range that admits a version of +// major 100 or more is unsupported (beyondProbes) and refused by +// targetMajor. These are finite probes, not a general semver intersection. func rangeMajors(rng string) []uint64 { c, err := semver.NewConstraint(rng) if err != nil { @@ -235,7 +290,7 @@ func rangeMajors(rng string) []uint64 { } } const late = 999999 - for m := range uint64(100) { + for m := range uint64(maxProbedMajor + 1) { if slices.Contains(majors, m) { continue } diff --git a/internal/controller/chartsource_test.go b/internal/controller/chartsource_test.go index 6c1e345..e29ddc7 100644 --- a/internal/controller/chartsource_test.go +++ b/internal/controller/chartsource_test.go @@ -346,6 +346,24 @@ func TestRangeMajors(t *testing.T) { } } +// QB-07: a range past the probed majors is refused as unsupported, as +// agent-manager's migrate and the agent-platform chart refuse it, never read +// as the majors below 100 it shows. +func TestTargetMajorRefusesRangesPastMajor99(t *testing.T) { + for _, rng := range []string{">=100.0.0 <102.0.0", "100.x", ">=99.5.0", "^2.0.0 || 150.0.0"} { + _, nr := ChartSource{Semver: rng}.targetMajor("org-a") + require.NotNil(t, nr, rng) + assert.Equal(t, reasonChartRangeInvalid, nr.reason, rng) + } + for _, rng := range []string{">=100.0.0 <102.0.0", ">=99.5.0"} { + _, nr := ChartSource{Semver: rng}.targetMajor("org-a") + assert.Contains(t, nr.message, "chart major of 100 or more", rng) + } + got, nr := ChartSource{Semver: ">=99.0.0 <100.0.0"}.targetMajor("org-a") + require.Nil(t, nr) + assert.Equal(t, uint64(99), got) +} + // requeueAfter is the shortest a cause of Ready=False asks for; a failure or // a cause without one asks for none. func TestRequeueAfter(t *testing.T) { From 754e6123eff93aa917dea799b579f552505b7669 Mon Sep 17 00:00:00 2001 From: Dominik Schmidle Date: Sat, 28 Nov 2026 15:28:01 +0100 Subject: [PATCH 9/9] feat: bind the chart source move to the release versions migrate recorded A HelmRelease recreated under the same name or whose spec changed after agent-manager's migrate run now holds the organization's chart source move, with a ChartSourceHeld condition naming it, until migrate runs again. A mark without the release versions holds too. --- README.md | 2 +- internal/controller/chartmajor.go | 62 ++++++++++-- internal/controller/chartsource_test.go | 72 ++++++++++---- .../controller/organization_envtest_test.go | 94 +++++++++++++++++-- 4 files changed, 197 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 0e1a85d..b85a950 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,7 @@ The right to manage `Organization` objects is bound by the installation: it bind In the namespace the operator keeps, from the first reconcile on: - the network policies `networkPolicy.names`, copied from `platformNamespace`; -- the agent chart's OCIRepository (`agentChart.*`), named after the chart (`agent`). Every reconcile resets its `spec.url`, `spec.interval` and `spec.ref` to `agentChart.*` (other fields and labels stay). A move of `spec.ref` to a higher major (`2.x` to `3.x`) waits per organization until agent-manager's migrate sets `agent-platform.giantswarm.io/agent-chart-ready-major` to the new major on the report ConfigMap (`agentChart.migrationReport`), with `agent-platform.giantswarm.io/agent-chart-ready-releases` naming every HelmRelease on the source; an organization with no HelmRelease on the source moves at once. While it waits the organization is not Ready (`ChartSourceHeld`) and is rechecked every `agentChart.migrationPoll`. A range of no release major (a pre-release alone) or of several (`>=2.6.0`) creates and moves no source: `ChartRangeInvalid`. Organizations do not pin their own chart version; +- the agent chart's OCIRepository (`agentChart.*`), named after the chart (`agent`). Every reconcile resets its `spec.url`, `spec.interval` and `spec.ref` to `agentChart.*` (other fields and labels stay). A move of `spec.ref` to a higher major (`2.x` to `3.x`) waits per organization until agent-manager's migrate sets `agent-platform.giantswarm.io/agent-chart-ready-major` to the new major on the report ConfigMap (`agentChart.migrationReport`), with `agent-platform.giantswarm.io/agent-chart-ready-releases` naming every HelmRelease on the source and `agent-platform.giantswarm.io/agent-chart-ready-release-versions` recording each one's UID and `metadata.generation` as the run left it. A release recreated under the same name or whose spec changed after the run (or a mark without the versions) holds the move, naming the release, until migrate runs again; an organization with no HelmRelease on the source moves at once. While it waits the organization is not Ready (`ChartSourceHeld`) and is rechecked every `agentChart.migrationPoll`. A range of no release major (a pre-release alone) or of several (`>=2.6.0`) creates and moves no source: `ChartRangeInvalid`. Organizations do not pin their own chart version; - the Helm ServiceAccount `helmReleaseServiceAccount`, which the organization's HelmReleases run as, with a RoleBinding to the ClusterRole `agent-platform-tenant-flux`; - the RoleBinding `organization-admins`, which binds the ClusterRole `agent-platform:admin` to the Users and Groups of the organization's `spec.admins`, in their order. It follows the list while the Agent Platform is on, and an edit of it is reverted. With no admins the operator empties its binding and deletes it (emptied first, so a finalizer that holds the binding keeps no access), the organization has no such binding, and that is no error: the platform team manages the organization. A RoleBinding `organization-admins` that the operator did not write is left as it is, and the organization is `AgentPlatformReady=False NameTaken` while it has admins. The operator writes no binding in other namespaces from the list (no `cluster-admin`); - the ResourceQuota `agent-platform-organization-objects` on object counts (`objectQuota`), so one organization cannot flood the API server with objects; diff --git a/internal/controller/chartmajor.go b/internal/controller/chartmajor.go index 5ce6711..6de1e92 100644 --- a/internal/controller/chartmajor.go +++ b/internal/controller/chartmajor.go @@ -2,6 +2,7 @@ package controller import ( "context" + "encoding/json" "fmt" "regexp" "slices" @@ -35,6 +36,23 @@ const DefaultMigrationReport = "agent-manager-migrate-report" // the namespace: the mark does not cover it, and migrate must run again. const MigrationReadyReleasesAnnotation = "agent-platform.giantswarm.io/agent-chart-ready-releases" +// MigrationReadyVersionsAnnotation is set beside MigrationReadyReleasesAnnotation +// to a JSON object of each release the run found on target values, by name, +// to the UID and metadata.generation the run left it at +// ({"hand":{"uid":"…","generation":4}}; agent-manager's +// migrate.OrganizationReadyVersionsAnnotation). The mark covers a HelmRelease +// on the source only while both match: a release recreated under the same +// name (another UID) or whose spec changed after the run (another +// generation) holds the move until migrate runs again. A mark without it (an +// older agent-manager) covers no release. +const MigrationReadyVersionsAnnotation = "agent-platform.giantswarm.io/agent-chart-ready-release-versions" + +// releaseVersion is one entry of MigrationReadyVersionsAnnotation. +type releaseVersion struct { + UID string `json:"uid"` + Generation int64 `json:"generation"` +} + // DefaultMigrationPoll is how often an organization whose chart source is // held at its major looks for migrate's mark again. const DefaultMigrationPoll = time.Minute @@ -128,7 +146,8 @@ func deployedMajor(hr unstructured.Unstructured) (uint64, bool) { // migrationReady reports whether the chart source name in ns may move to (or, // missing, be created on) major: no HelmRelease of the namespace renders from // the source, or migrate's report there carries MigrationReadyAnnotation with -// that major and names every such release in MigrationReadyReleasesAnnotation. +// that major and records every such release at its current UID and generation +// in MigrationReadyVersionsAnnotation. // For a missing source (recreated) only releases whose deployed chart is of a // lower major count: within a major nothing waits. why says what holds it. func (r *OrganizationReconciler) migrationReady(ctx context.Context, ns, name string, major uint64, creating bool) (ready bool, why string, err error) { @@ -164,17 +183,44 @@ func (r *OrganizationReconciler) migrationReady(ctx context.Context, ns, name st got := cm.Annotations[MigrationReadyAnnotation] switch { case got == strconv.FormatUint(major, 10): - marked := strings.Split(cm.Annotations[MigrationReadyReleasesAnnotation], ",") - var after []string - for _, name := range using { - if !slices.Contains(marked, name) { - after = append(after, name) + versions := map[string]releaseVersion{} + if raw, ok := cm.Annotations[MigrationReadyVersionsAnnotation]; ok { + if err := json.Unmarshal([]byte(raw), &versions); err != nil { + versions = nil + } + } else { + versions = nil + } + if versions == nil { + why = fmt.Sprintf("its report %s marks it ready without the release versions (%s) the move is bound to", report, MigrationReadyVersionsAnnotation) + break + } + var after, changed []string + for _, hr := range rels { + if !slices.Contains(using, hr.GetName()) { + continue + } + v, ok := versions[hr.GetName()] + switch { + case !ok: + after = append(after, hr.GetName()) + case v.UID != string(hr.GetUID()) || v.Generation != hr.GetGeneration(): + changed = append(changed, hr.GetName()) } } - if len(after) == 0 { + slices.Sort(after) + slices.Sort(changed) + if len(after) == 0 && len(changed) == 0 { return true, "", nil } - why = fmt.Sprintf("its report %s marks it ready, but HelmReleases %v on the source were created after that run", report, after) + var parts []string + if len(after) > 0 { + parts = append(parts, fmt.Sprintf("HelmReleases %v on the source were created after that run", after)) + } + if len(changed) > 0 { + parts = append(parts, fmt.Sprintf("HelmReleases %v were recreated or changed since that run", changed)) + } + why = fmt.Sprintf("its report %s marks it ready, but %s", report, strings.Join(parts, "; ")) case got != "": why = fmt.Sprintf("its report %s marks it ready for %s.x only", report, got) default: diff --git a/internal/controller/chartsource_test.go b/internal/controller/chartsource_test.go index e29ddc7..8b920ed 100644 --- a/internal/controller/chartsource_test.go +++ b/internal/controller/chartsource_test.go @@ -2,6 +2,7 @@ package controller import ( "context" + "encoding/json" "errors" "strings" "testing" @@ -14,6 +15,7 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" "sigs.k8s.io/controller-runtime/pkg/client/interceptor" @@ -189,6 +191,9 @@ func TestEnsureChartSourceSemverFilter(t *testing.T) { assert.Equal(t, map[string]any{fieldSemver: chartRange}, ref) } +// triageRelease is the HelmRelease the chart-source tests put on the source. +const triageRelease = "triage" + var testHelmReleaseGVK = schema.GroupVersionKind{Group: "helm.toolkit.fluxcd.io", Version: "v2", Kind: "HelmRelease"} // chartRelease is a HelmRelease in chartNS whose chart is the OCIRepository @@ -200,6 +205,8 @@ func chartRelease(name, source string) *unstructured.Unstructured { u.SetGroupVersionKind(testHelmReleaseGVK) u.SetNamespace(chartNS) u.SetName(name) + u.SetUID(types.UID("uid-" + name)) + u.SetGeneration(1) return u } @@ -221,11 +228,26 @@ func deployedHistory(hr *unstructured.Unstructured, versions ...string) *unstruc } // migrateReport is agent-manager migrate's report in chartNS, marked ready -// for major, naming releases, when major is not empty. +// for major, naming releases at the UID and generation chartRelease gives +// them, when major is not empty. func migrateReport(major string, releases ...string) *corev1.ConfigMap { + versions := map[string]releaseVersion{} + for _, name := range releases { + versions[name] = releaseVersion{UID: "uid-" + name, Generation: 1} + } + return migrateReportWith(major, releases, versions) +} + +// migrateReportWith is migrateReport with the versions it records; nil +// versions leave the annotation out (an older agent-manager's mark). +func migrateReportWith(major string, releases []string, versions map[string]releaseVersion) *corev1.ConfigMap { cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: chartNS, Name: DefaultMigrationReport}} if major != "" { cm.Annotations = map[string]string{MigrationReadyAnnotation: major, MigrationReadyReleasesAnnotation: strings.Join(releases, ",")} + if versions != nil { + raw, _ := json.Marshal(versions) + cm.Annotations[MigrationReadyVersionsAnnotation] = string(raw) + } } return cm } @@ -257,20 +279,34 @@ func TestEnsureChartSourceWaitsForMigrateAcrossAMajor(t *testing.T) { mentions string }{ {name: "a release on the source and no report: held", semver: v3, from: v2Ref, - objects: []client.Object{chartRelease("triage", chart.Name())}, mentions: noReport}, + objects: []client.Object{chartRelease(triageRelease, chart.Name())}, mentions: noReport}, {name: "a report without the mark: held", semver: v3, from: v2Ref, - objects: []client.Object{chartRelease("triage", chart.Name()), migrateReport("")}, mentions: "names releases not on 3.x values yet"}, + objects: []client.Object{chartRelease(triageRelease, chart.Name()), migrateReport("")}, mentions: "names releases not on 3.x values yet"}, {name: "a report marked for the old major: held", semver: v3, from: v2Ref, - objects: []client.Object{chartRelease("triage", chart.Name()), migrateReport("2")}, mentions: "ready for 2.x only"}, + objects: []client.Object{chartRelease(triageRelease, chart.Name()), migrateReport("2")}, mentions: "ready for 2.x only"}, {name: "a report marked for the new major: moved", semver: v3, from: v2Ref, - objects: []client.Object{chartRelease("triage", chart.Name()), migrateReport("3", "triage")}, moved: true}, + objects: []client.Object{chartRelease(triageRelease, chart.Name()), migrateReport("3", triageRelease)}, moved: true}, {name: "a release created after migrate's run: held", semver: v3, from: v2Ref, - objects: []client.Object{chartRelease("triage", chart.Name()), chartRelease("late", chart.Name()), migrateReport("3", "triage")}, + objects: []client.Object{chartRelease(triageRelease, chart.Name()), chartRelease("late", chart.Name()), migrateReport("3", triageRelease)}, mentions: "HelmReleases [late] on the source were created after that run"}, + {name: "a release recreated under the same name after migrate's run: held", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease(triageRelease, chart.Name()), + migrateReportWith("3", []string{triageRelease}, map[string]releaseVersion{triageRelease: {UID: "uid-before", Generation: 1}})}, + mentions: "HelmReleases [triage] were recreated or changed since that run"}, + {name: "a release whose spec changed after migrate's run: held", semver: v3, from: v2Ref, + objects: []client.Object{func() client.Object { + hr := chartRelease(triageRelease, chart.Name()) + hr.SetGeneration(2) + return hr + }(), migrateReport("3", triageRelease)}, + mentions: "HelmReleases [triage] were recreated or changed since that run"}, + {name: "a mark without release versions: held", semver: v3, from: v2Ref, + objects: []client.Object{chartRelease(triageRelease, chart.Name()), migrateReportWith("3", []string{triageRelease}, nil)}, + mentions: "without the release versions"}, {name: "a source on a tag names no major: held", semver: v3, from: map[string]any{"tag": "latest"}, - objects: []client.Object{chartRelease("triage", chart.Name())}, mentions: noReport}, + objects: []client.Object{chartRelease(triageRelease, chart.Name())}, mentions: noReport}, {name: "a source on a digest names no major: held", semver: v3, from: map[string]any{"digest": "sha256:0000000000000000000000000000000000000000000000000000000000000000"}, - objects: []client.Object{chartRelease("triage", chart.Name())}, mentions: noReport}, + objects: []client.Object{chartRelease(triageRelease, chart.Name())}, mentions: noReport}, {name: "a release of another kind with the source's name does not count", semver: v3, from: v2Ref, objects: []client.Object{func() client.Object { hr := chartRelease("chart", chart.Name()) @@ -280,11 +316,11 @@ func TestEnsureChartSourceWaitsForMigrateAcrossAMajor(t *testing.T) { {name: "no release on the source: moved without a report", semver: v3, from: v2Ref, objects: []client.Object{chartRelease("dashboards", "dashboards")}, moved: true}, {name: "a move within a major never waits", semver: chartRange, from: map[string]any{fieldSemver: "2.6.x"}, - objects: []client.Object{chartRelease("triage", chart.Name())}, moved: true}, + objects: []client.Object{chartRelease(triageRelease, chart.Name())}, moved: true}, {name: "a move back down never waits", semver: v2Line, from: map[string]any{fieldSemver: v3}, - objects: []client.Object{chartRelease("triage", chart.Name())}, moved: true}, + objects: []client.Object{chartRelease(triageRelease, chart.Name())}, moved: true}, {name: "an alternative of the old range on the new major: no move across", semver: v3, from: map[string]any{fieldSemver: "2.6.0 || 3.0.1"}, - objects: []client.Object{chartRelease("triage", chart.Name())}, moved: true}, + objects: []client.Object{chartRelease(triageRelease, chart.Name())}, moved: true}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { @@ -417,13 +453,13 @@ func TestEnsureChartSourceRecreatedWaitsForMigrate(t *testing.T) { objects []client.Object created bool }{ - "a release on 2.x, no mark: not created": {v3, []client.Object{deployed(chartRelease("triage", chart.Name()), "2.6.1")}, false}, - "a release on 2.x, marked: created": {v3, []client.Object{deployed(chartRelease("triage", chart.Name()), "2.6.1"), migrateReport("3", "triage")}, true}, - "a release already on 3.x: created": {v3, []client.Object{deployed(chartRelease("triage", chart.Name()), "3.0.0")}, true}, - "a release never deployed: created": {v3, []client.Object{chartRelease("triage", chart.Name())}, true}, - "a release deployed 2.x once, now on 3.x (newest history first): created": {v3, []client.Object{deployedHistory(chartRelease("triage", chart.Name()), "3.0.0", "2.6.1")}, true}, - "a release now on 2.x after 3.x (newest history first): not created": {v3, []client.Object{deployedHistory(chartRelease("triage", chart.Name()), "2.6.1", "3.0.0")}, false}, - "within a major nothing waits": {chartRange, []client.Object{deployed(chartRelease("triage", chart.Name()), "2.6.1")}, true}, + "a release on 2.x, no mark: not created": {v3, []client.Object{deployed(chartRelease(triageRelease, chart.Name()), "2.6.1")}, false}, + "a release on 2.x, marked: created": {v3, []client.Object{deployed(chartRelease(triageRelease, chart.Name()), "2.6.1"), migrateReport("3", triageRelease)}, true}, + "a release already on 3.x: created": {v3, []client.Object{deployed(chartRelease(triageRelease, chart.Name()), "3.0.0")}, true}, + "a release never deployed: created": {v3, []client.Object{chartRelease(triageRelease, chart.Name())}, true}, + "a release deployed 2.x once, now on 3.x (newest history first): created": {v3, []client.Object{deployedHistory(chartRelease(triageRelease, chart.Name()), "3.0.0", "2.6.1")}, true}, + "a release now on 2.x after 3.x (newest history first): not created": {v3, []client.Object{deployedHistory(chartRelease(triageRelease, chart.Name()), "2.6.1", "3.0.0")}, false}, + "within a major nothing waits": {chartRange, []client.Object{deployed(chartRelease(triageRelease, chart.Name()), "2.6.1")}, true}, } { t.Run(name, func(t *testing.T) { c := fake.NewClientBuilder().WithScheme(gateScheme(t)).WithObjects(tc.objects...).Build() diff --git a/internal/controller/organization_envtest_test.go b/internal/controller/organization_envtest_test.go index 5d05c76..5b73287 100644 --- a/internal/controller/organization_envtest_test.go +++ b/internal/controller/organization_envtest_test.go @@ -135,12 +135,10 @@ func TestOrganizationEnvtest(t *testing.T) { ref, _, _ := unstructured.NestedMap(c.read(t, ociGVK, ns.Name, agentChart).Object, "spec", "ref") assert.Equal(t, map[string]any{semverField: oldLine}, ref, "the source stays on its major") - // migrate's mark for the new major: the held organization looks - // again on its own (MigrationPoll) and moves. - require.NoError(t, c.admin.Create(t.Context(), &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{ - Namespace: ns.Name, Name: controller.DefaultMigrationReport, - Annotations: map[string]string{controller.MigrationReadyAnnotation: "2", controller.MigrationReadyReleasesAnnotation: "triage"}, - }})) + // migrate's mark for the new major, recording the release as it is: + // the held organization looks again on its own (MigrationPoll) and + // moves. + require.NoError(t, c.admin.Create(t.Context(), migrateMark(t, ns.Name, c.read(t, helmReleaseGVK, ns.Name, "triage")))) c.eventually(t, ociGVK, ns.Name, agentChart, func(ct *assert.CollectT, u *unstructured.Unstructured) { ref, _, _ := unstructured.NestedMap(u.Object, "spec", "ref") assert.Equal(ct, map[string]any{semverField: c.config.Chart.Semver}, ref) @@ -148,6 +146,68 @@ func TestOrganizationEnvtest(t *testing.T) { c.readyAt(t, org, org.Generation) }) + // The mark covers the releases as migrate's run left them: one recreated + // under the same name, or whose spec changed after the run, holds the + // move with a condition naming it until migrate runs again. + for _, tc := range []struct { + name string + change func(t *testing.T, ns string) + }{ + {name: "recreated", change: func(t *testing.T, ns string) { + require.NoError(t, c.admin.Delete(t.Context(), c.read(t, helmReleaseGVK, ns, "triage"))) + require.Eventually(t, func() bool { + u := &unstructured.Unstructured{} + u.SetGroupVersionKind(helmReleaseGVK) + return apierrors.IsNotFound(c.admin.Get(t.Context(), client.ObjectKey{Namespace: ns, Name: "triage"}, u)) + }, timeout, tick) + require.NoError(t, c.admin.Create(t.Context(), newObject(helmReleaseGVK, ns, "triage", nil, helmReleaseSpec))) + }}, + {name: "edited", change: func(t *testing.T, ns string) { + hr := c.read(t, helmReleaseGVK, ns, "triage") + require.NoError(t, unstructured.SetNestedField(hr.Object, "45m", "spec", intervalField)) + require.NoError(t, c.admin.Update(t.Context(), hr)) + }}, + } { + t.Run("a release "+tc.name+" after migrate's run holds the move until migrate runs again", func(t *testing.T) { + org := c.organization(t, "major-"+tc.name) + ns := c.readyNamespace(t, org) + oci := c.read(t, ociGVK, ns.Name, agentChart) + require.NoError(t, unstructured.SetNestedMap(oci.Object, map[string]any{semverField: oldLine}, "spec", "ref")) + require.NoError(t, c.admin.Update(t.Context(), oci)) + require.NoError(t, c.admin.Create(t.Context(), newObject(helmReleaseGVK, ns.Name, "triage", nil, helmReleaseSpec))) + // What migrate's run recorded, then the change after it. + mark := migrateMark(t, ns.Name, c.read(t, helmReleaseGVK, ns.Name, "triage")) + tc.change(t, ns.Name) + require.NoError(t, c.admin.Create(t.Context(), mark)) + + c.poke(t, org) + require.EventuallyWithT(t, func(ct *assert.CollectT) { + ready := meta.FindStatusCondition(c.get(ct, org).Status.Conditions, orgv1.AgentPlatformReady) + if assert.NotNil(ct, ready) { + assert.Equal(ct, metav1.ConditionFalse, ready.Status) + assert.Equal(ct, "ChartSourceHeld", ready.Reason) + assert.Contains(ct, ready.Message, "HelmReleases [triage] were recreated or changed since that run") + } + }, timeout, tick) + require.Never(t, func() bool { + ref, _, _ := unstructured.NestedMap(c.read(t, ociGVK, ns.Name, agentChart).Object, "spec", "ref") + return ref[semverField] != oldLine + }, 2*time.Second, tick, "the source stays on its major") + + // migrate runs again and records the release as it is now. + again := migrateMark(t, ns.Name, c.read(t, helmReleaseGVK, ns.Name, "triage")) + cm := &corev1.ConfigMap{} + require.NoError(t, c.admin.Get(t.Context(), client.ObjectKeyFromObject(again), cm)) + cm.Annotations = again.Annotations + require.NoError(t, c.admin.Update(t.Context(), cm)) + c.eventually(t, ociGVK, ns.Name, agentChart, func(ct *assert.CollectT, u *unstructured.Unstructured) { + ref, _, _ := unstructured.NestedMap(u.Object, "spec", "ref") + assert.Equal(ct, map[string]any{semverField: c.config.Chart.Semver}, ref) + }) + c.readyAt(t, org, org.Generation) + }) + } + t.Run("the operator updates no OCIRepository but the chart's and reads no ConfigMap but migrate's report", func(t *testing.T) { org := c.organization(t, "rbac") ns := c.readyNamespace(t, org) @@ -535,3 +595,25 @@ func TestChartRangeInvalidEnvtest(t *testing.T) { assert.Equal(t, map[string]any{semverField: open}, ref, "the operator leaves the ref as it is") }) } + +// migrateMark is agent-manager migrate's report in ns marked ready for the +// configured major ("2"), recording each release at its UID and generation. +func migrateMark(t *testing.T, ns string, releases ...*unstructured.Unstructured) *corev1.ConfigMap { + t.Helper() + names := make([]string, 0, len(releases)) + versions := map[string]map[string]any{} + for _, hr := range releases { + names = append(names, hr.GetName()) + versions[hr.GetName()] = map[string]any{"uid": string(hr.GetUID()), "generation": hr.GetGeneration()} + } + raw, err := json.Marshal(versions) + require.NoError(t, err) + return &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{ + Namespace: ns, Name: controller.DefaultMigrationReport, + Annotations: map[string]string{ + controller.MigrationReadyAnnotation: "2", + controller.MigrationReadyReleasesAnnotation: strings.Join(names, ","), + controller.MigrationReadyVersionsAnnotation: string(raw), + }, + }} +}