← Back to Pull requests

Merge profiles recorded before 1.0 when their recording is deleted #3552

Merged
Vincent056 merged 4 files (792 lines) on Oct 07, 2026 05:58 UTC
View on GitHub
Vincent056 Vincent056 commented on Oct 06, 2026 16:52 UTC
Author

What type of PR is this?

/kind bug

What this PR does / why we need it:

Since 1.0, recorded profiles carry the spo.x-k8s.io/recording-namespace label, and the recording merger selects a recording's partial profiles by recording-id and recording-namespace (listPartialProfiles, hasPartialProfiles). Profiles recorded before 1.0 only carry recording-id. So after an upgrade from 0.x, the partial profiles of a recording that was started before the upgrade are invisible to the merge:

  • on main, deleting the recording releases it without merging them, so the partial profiles are left behind unmerged;

  • on 1.0.x, where only the daemon's finalizer handling releases recordings (handleRecordingFinalizer also returns early without the namespace label), the recording stays in deletion forever with the spo.x-k8s.io/has-unmerged-profiles finalizer.
  • This PR adopts such profiles when the recording is being deleted. It labels the recording's profiles that have no recording-namespace with the recording's namespace, and merges them on the next reconcile, once the cache shows the labels. Profiles are cluster-scoped, so the name alone can't tell recordings in different namespaces apart. The profiles are only adopted when exactly one recording has that name; otherwise a warning event explains why they aren't merged.

    Which issue(s) this PR fixes:

    None

    Does this PR have test?

    Yes. There are unit tests for the merger: profiles recorded before 1.0 get labeled on the first reconcile and merged on the second, profiles are left alone when the recording name is ambiguous, and profiles of other recordings are not touched. The main test fails without the fix.

    The scenario was also reproduced on OpenShift 4.21 with an OLM upgrade from 0.10.1 to 1.0.1. A 0.10 recording with mergeStrategy: containers left two partial profiles, and after the upgrade deleting the recording hung. Adding the recording-namespace label to the partial profiles, as this change does, made 1.0.1 merge them within seconds into an installed profile and release the recording.

    Special notes for your reviewer:

  • The requeue after labeling is deliberate: the merge lists profiles through the cached client, so merging in the same reconcile could miss the newly labeled profiles. On main, it would then release the recording and orphan them.

  • The same change is needed on any 1.0.x line that supports upgrades from 0.x.
  • Does this PR introduce a user-facing change?

    ``release-note
    Partial profiles recorded by a ProfileRecording before an upgrade to 1.0 are now merged when the recording is deleted, instead of being left unmerged or keeping the recording from being deleted.
    ``

    🤖 Generated with Claude Code

    Diff: 792 lines (+786 / -6) across 4 files Reviewer: saschagrunert Review duration: 786m
    All Vouch review confidence checks passed
    Residual risk 0.09 = Change Risk (0.47) × (1 − Review Confidence (0.80)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.47 · 792 lines diff across 4 files
    0.47
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.80 · 5 substantive comment(s)
    0.80
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    80%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.399
    Real PR Conversation Timeline
    15 items
    linux-foundation-easycla[bot] linux-foundation-easycla[bot] commented on Oct 06, 2026 16:52 UTC
    Bot

    <a href="https://easycla.lfx.linuxfoundation.org/#/?version=2"><img src="https://s3.amazonaws.com/cla-project-logo-prod/cla-signed.svg?v=2" alt="CLA Signed" align="left" height="28" width="328" ></a><br >The committers listed above are authorized under a signed CLA.<ul><li>:white_check_mark: login: Vincent056 / name: Vincent Shen (9a4da598334abe2f44da49458ccf346a26219e68)</li></ul>

    codecov-commenter codecov-commenter commented on Oct 06, 2026 16:59 UTC
    Contributor

    Codecov Report


    :x: Patch coverage is 78.44311% with 36 lines in your changes missing coverage. Please review.
    :white_check_mark: Project coverage is 83.04%. Comparing base (470f2d8) to head (7c194a2).

    :x: Your patch status has failed because the patch coverage (78.44%) is below the target coverage (80.00%). You can increase the patch coverage or adjust the target coverage.

    <details><summary>Additional details and impacted files</summary>

    @@            Coverage Diff             @@
    ##             main    #3552      +/-   ##
    ==========================================
    - Coverage   83.15%   83.04%   -0.11%     
    ==========================================
      Files         183      184       +1     
      Lines       16399    16562     +163     
    ==========================================
    + Hits        13636    13754     +118     
    - Misses       2763     2808      +45     
    

    </details>
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • </details>

    saschagrunert saschagrunert commented on code on Oct 06, 2026 17:38 UTC
    Code Review
    internal/pkg/manager/recordingmerger/recordingmerger.go:1
    @@ -247,6 +271,115 @@ func (r *PolicyMergeReconciler) releaseRecording(
     	return nil
     }
     
    +// adoptLegacyProfiles labels the profiles of the recording that were recorded
    +// before 1.0 with the recording namespace and returns how many it labeled.
    +// Before 1.0, recorded profiles only carried the recording name, while the
    +// merge and the release of the recording select them by name and namespace:
    +// without the label, the partial profiles of a recording that was started
    +// before an upgrade are never merged. Profiles are cluster-scoped, so the name
    +// alone cannot tell recordings in different namespaces apart; the profiles are
    +// only adopted if a single recording has this name.
    +func (r *PolicyMergeReconciler) adoptLegacyProfiles(
    +	ctx context.Context,
    +	profileRecording *profilerecordingapi.ProfileRecording,
    +) (int, error) {
    +	byName, err := labels.NewRequirement(
    +		profilerecordingapi.ProfileToRecordingLabel,
    +		selection.Equals,
    +		[]string{profileRecording.GetName()},
    +	)
    +	if err != nil {
    +		return 0, fmt.Errorf("selecting profiles by recording name: %w", err)
    +	}
    +
    +	withoutNamespace, err := labels.NewRequirement(
    +		profilerecordingapi.ProfileToRecordingNamespaceLabel,
    +		selection.DoesNotExist,
    +		nil,
    +	)
    +	if err != nil {
    +		return 0, fmt.Errorf("selecting profiles without recording namespace: %w", err)
    +	}
    +
    +	selector := client.MatchingLabelsSelector{

    This selector doesn't require spo.x-k8s.io/partial=true, so it also matches installed profiles that 0.x merged (they carry recording-id too). If the 0.x recording ns-b/foo produced foo-nginx and was deleted, then creating and deleting ns-a/foo after the upgrade labels foo-nginx with recording-namespace=ns-a. A later ns-b/foo then fails CheckRecordingOwner with ErrProfileOwnedByOtherRecording, although it passes today. Could the selector be derived from partialProfileLabels (keep name and partial, swap the namespace for a DoesNotExist requirement), so the two selectors can't drift?

    saschagrunert saschagrunert commented on code on Oct 06, 2026 17:38 UTC
    Code Review
    internal/pkg/manager/recordingmerger/recordingmerger.go:1
    @@ -247,6 +271,115 @@ func (r *PolicyMergeReconciler) releaseRecording(
     	return nil
     }
     
    +// adoptLegacyProfiles labels the profiles of the recording that were recorded
    +// before 1.0 with the recording namespace and returns how many it labeled.
    +// Before 1.0, recorded profiles only carried the recording name, while the
    +// merge and the release of the recording select them by name and namespace:
    +// without the label, the partial profiles of a recording that was started
    +// before an upgrade are never merged. Profiles are cluster-scoped, so the name
    +// alone cannot tell recordings in different namespaces apart; the profiles are
    +// only adopted if a single recording has this name.
    +func (r *PolicyMergeReconciler) adoptLegacyProfiles(
    +	ctx context.Context,
    +	profileRecording *profilerecordingapi.ProfileRecording,
    +) (int, error) {
    +	byName, err := labels.NewRequirement(
    +		profilerecordingapi.ProfileToRecordingLabel,
    +		selection.Equals,
    +		[]string{profileRecording.GetName()},
    +	)
    +	if err != nil {
    +		return 0, fmt.Errorf("selecting profiles by recording name: %w", err)
    +	}
    +
    +	withoutNamespace, err := labels.NewRequirement(
    +		profilerecordingapi.ProfileToRecordingNamespaceLabel,
    +		selection.DoesNotExist,
    +		nil,
    +	)
    +	if err != nil {
    +		return 0, fmt.Errorf("selecting profiles without recording namespace: %w", err)
    +	}
    +
    +	selector := client.MatchingLabelsSelector{
    +		Selector: labels.NewSelector().Add(*byName, *withoutNamespace),
    +	}
    +
    +	var legacy []client.Object
    +
    +	for _, k := range mergeKinds {
    +		list := k.newList()
    +		if err := r.client.List(ctx, list, selector); err != nil {
    +			return 0, fmt.Errorf("listing profiles of kind %s: %w", k.kind, err)
    +		}
    +
    +		if err := apimeta.EachListItem(list, func(obj runtime.Object) error {
    +			prf, ok := obj.(client.Object)
    +			if !ok {
    +				return fmt.Errorf("object %T is not a client.Object", obj)
    +			}
    +
    +			legacy = append(legacy, prf)
    +
    +			return nil
    +		}); err != nil {
    +			return 0, err
    +		}
    +	}
    +
    +	if len(legacy) == 0 {
    +		return 0, nil
    +	}
    +
    +	recordings := &profilerecordingapi.ProfileRecordingList{}
    +	if err := r.client.List(ctx, recordings); err != nil {
    +		return 0, fmt.Errorf("listing profile recordings: %w", err)
    +	}
    +
    +	sameName := 0
    +
    +	for i := range recordings.Items {
    +		if recordings.Items[i].GetName() == profileRecording.GetName() {
    +			sameName++
    +		}
    +	}
    +
    +	if sameName != 1 {

    sameName only counts recordings that still exist. Suppose ns-a/foo and ns-b/foo both have unmerged 0.x partial profiles. Deleting ns-b/foo first sees 2, so it warns and gets released, but its partial profiles stay. Deleting ns-a/foo later sees 1 and adopts and merges the partial profiles of both namespaces into ns-a's profile, which then allows another workload's syscalls.

    saschagrunert saschagrunert commented on code on Oct 06, 2026 17:38 UTC
    Code Review
    internal/pkg/manager/recordingmerger/recordingmerger.go:1
    @@ -247,6 +271,115 @@ func (r *PolicyMergeReconciler) releaseRecording(
     	return nil
     }
     
    +// adoptLegacyProfiles labels the profiles of the recording that were recorded
    +// before 1.0 with the recording namespace and returns how many it labeled.
    +// Before 1.0, recorded profiles only carried the recording name, while the
    +// merge and the release of the recording select them by name and namespace:
    +// without the label, the partial profiles of a recording that was started
    +// before an upgrade are never merged. Profiles are cluster-scoped, so the name
    +// alone cannot tell recordings in different namespaces apart; the profiles are
    +// only adopted if a single recording has this name.
    +func (r *PolicyMergeReconciler) adoptLegacyProfiles(
    +	ctx context.Context,
    +	profileRecording *profilerecordingapi.ProfileRecording,
    +) (int, error) {
    +	byName, err := labels.NewRequirement(
    +		profilerecordingapi.ProfileToRecordingLabel,
    +		selection.Equals,
    +		[]string{profileRecording.GetName()},
    +	)
    +	if err != nil {
    +		return 0, fmt.Errorf("selecting profiles by recording name: %w", err)
    +	}
    +
    +	withoutNamespace, err := labels.NewRequirement(
    +		profilerecordingapi.ProfileToRecordingNamespaceLabel,
    +		selection.DoesNotExist,
    +		nil,
    +	)
    +	if err != nil {
    +		return 0, fmt.Errorf("selecting profiles without recording namespace: %w", err)
    +	}
    +
    +	selector := client.MatchingLabelsSelector{
    +		Selector: labels.NewSelector().Add(*byName, *withoutNamespace),
    +	}
    +
    +	var legacy []client.Object
    +
    +	for _, k := range mergeKinds {
    +		list := k.newList()
    +		if err := r.client.List(ctx, list, selector); err != nil {
    +			return 0, fmt.Errorf("listing profiles of kind %s: %w", k.kind, err)
    +		}
    +
    +		if err := apimeta.EachListItem(list, func(obj runtime.Object) error {
    +			prf, ok := obj.(client.Object)
    +			if !ok {
    +				return fmt.Errorf("object %T is not a client.Object", obj)
    +			}
    +
    +			legacy = append(legacy, prf)
    +
    +			return nil
    +		}); err != nil {
    +			return 0, err
    +		}
    +	}
    +
    +	if len(legacy) == 0 {
    +		return 0, nil
    +	}
    +
    +	recordings := &profilerecordingapi.ProfileRecordingList{}
    +	if err := r.client.List(ctx, recordings); err != nil {
    +		return 0, fmt.Errorf("listing profile recordings: %w", err)
    +	}
    +
    +	sameName := 0
    +
    +	for i := range recordings.Items {
    +		if recordings.Items[i].GetName() == profileRecording.GetName() {
    +			sameName++
    +		}
    +	}
    +
    +	if sameName != 1 {
    +		r.record.Eventf(
    +			profileRecording,
    +			nil,
    +			util.EventTypeWarning,
    +			reasonAmbiguousLegacy,
    +			util.EventActionMerge,
    +			"Not merging %d profiles recorded before 1.0: %d recordings are named %s, "+
    +				"and without the %s label they cannot be told apart",
    +			len(legacy),
    +			sameName,
    +			profileRecording.GetName(),
    +			profilerecordingapi.ProfileToRecordingNamespaceLabel,
    +		)
    +
    +		return 0, nil

    After returning 0 here, Reconcile goes on to mergeProfiles, which finds no namespaced partial profiles, emits NoPartialProfiles and releases the recording at :225. The legacy partial profiles are then orphaned, which is the problem this PR is fixing, and the second event is misleading. A same-named recording created after the legacy profiles can't own them. Could the count skip recordings whose creationTimestamp is later than the profiles'? That would settle the most likely post-upgrade case.

    saschagrunert saschagrunert commented on code on Oct 06, 2026 17:38 UTC
    Code Review
    internal/pkg/manager/recordingmerger/recordingmerger.go:1
    @@ -113,6 +121,22 @@ func (r *PolicyMergeReconciler) Reconcile(
     	if !profileRecording.GetDeletionTimestamp().IsZero() { // object is being deleted
     		logger.Info("Is being deleted, will check if there are policies to be merged")
     
    +		adopted, err := r.adoptLegacyProfiles(ctx, profileRecording)
    +		if err != nil {
    +			return reconcile.Result{}, fmt.Errorf("%s: %w", errAdoptingProfiles, err)
    +		}
    +
    +		if adopted > 0 {
    +			// The merge lists the profiles from the cache, which may not show
    +			// the new labels yet, so merge them on the next reconcile.
    +			logger.Info(
    +				"Labeled profiles recorded before 1.0 with the recording namespace",
    +				"profiles", adopted,
    +			)
    +
    +			return reconcile.Result{RequeueAfter: adoptRequeueDelay}, nil

    This relies on the cache showing the new labels within adoptRequeueDelay. If it doesn't, the next reconcile lists the same unlabeled profiles, patches them again and requeues. Did you consider a one-time adoption at manager startup instead? Every recording would still exist at that point, which would also settle the ordering problem from :347, where a recording deleted earlier no longer counts toward the ambiguity check.

    saschagrunert saschagrunert commented on code on Oct 06, 2026 17:38 UTC
    Code Review
    internal/pkg/manager/recordingmerger/recordingmerger.go:1
    @@ -247,6 +271,115 @@ func (r *PolicyMergeReconciler) releaseRecording(
     	return nil
     }
     
    +// adoptLegacyProfiles labels the profiles of the recording that were recorded
    +// before 1.0 with the recording namespace and returns how many it labeled.
    +// Before 1.0, recorded profiles only carried the recording name, while the
    +// merge and the release of the recording select them by name and namespace:
    +// without the label, the partial profiles of a recording that was started
    +// before an upgrade are never merged. Profiles are cluster-scoped, so the name
    +// alone cannot tell recordings in different namespaces apart; the profiles are
    +// only adopted if a single recording has this name.
    +func (r *PolicyMergeReconciler) adoptLegacyProfiles(
    +	ctx context.Context,
    +	profileRecording *profilerecordingapi.ProfileRecording,
    +) (int, error) {
    +	byName, err := labels.NewRequirement(
    +		profilerecordingapi.ProfileToRecordingLabel,
    +		selection.Equals,
    +		[]string{profileRecording.GetName()},
    +	)
    +	if err != nil {
    +		return 0, fmt.Errorf("selecting profiles by recording name: %w", err)
    +	}
    +
    +	withoutNamespace, err := labels.NewRequirement(
    +		profilerecordingapi.ProfileToRecordingNamespaceLabel,
    +		selection.DoesNotExist,
    +		nil,
    +	)
    +	if err != nil {
    +		return 0, fmt.Errorf("selecting profiles without recording namespace: %w", err)
    +	}
    +
    +	selector := client.MatchingLabelsSelector{
    +		Selector: labels.NewSelector().Add(*byName, *withoutNamespace),
    +	}
    +
    +	var legacy []client.Object
    +
    +	for _, k := range mergeKinds {
    +		list := k.newList()
    +		if err := r.client.List(ctx, list, selector); err != nil {
    +			return 0, fmt.Errorf("listing profiles of kind %s: %w", k.kind, err)
    +		}
    +
    +		if err := apimeta.EachListItem(list, func(obj runtime.Object) error {
    +			prf, ok := obj.(client.Object)
    +			if !ok {
    +				return fmt.Errorf("object %T is not a client.Object", obj)
    +			}
    +
    +			legacy = append(legacy, prf)
    +
    +			return nil
    +		}); err != nil {
    +			return 0, err
    +		}
    +	}
    +
    +	if len(legacy) == 0 {
    +		return 0, nil
    +	}
    +
    +	recordings := &profilerecordingapi.ProfileRecordingList{}
    +	if err := r.client.List(ctx, recordings); err != nil {

    This lists from the cache, which only covers the watched namespaces when WATCH_NAMESPACE or the namespace restriction is set. Profiles are cluster-scoped and are still listed in full, so a same-named recording outside the watched namespaces isn't counted and its legacy profiles can be adopted.

    saschagrunert saschagrunert commented on code on Oct 06, 2026 17:38 UTC
    Code Review
    internal/pkg/manager/recordingmerger/recordingmerger_test.go:1
    @@ -439,3 +440,115 @@ func TestDeletePartialProfilesOnlyDeletesListed(t *testing.T) {
     	// A profile which is already gone is not an error.
     	require.NoError(t, deletePartialProfiles(t.Context(), r.client, listed))
     }
    +
    +// legacyPartialSeccomp is a partial profile as recorded before 1.0, which only
    +// labeled recorded profiles with the recording name.
    +func legacyPartialSeccomp(name string, syscalls ...string) *seccompprofile.SeccompProfile {
    +	prf := partialSeccomp(name, "nginx", syscalls...)
    +	delete(prf.Labels, profilerecordingapi.ProfileToRecordingNamespaceLabel)
    +
    +	return prf
    +}
    +
    +func reconcileTestRecording(t *testing.T, r *PolicyMergeReconciler) reconcile.Result {
    +	t.Helper()
    +
    +	res, err := r.Reconcile(t.Context(), reconcile.Request{
    +		NamespacedName: types.NamespacedName{Name: testRecording, Namespace: testNamespace},
    +	})
    +	require.NoError(t, err)
    +
    +	return res
    +}
    +
    +// Partial profiles recorded before an upgrade to 1.0 have no recording
    +// namespace label, which the merge selects on. Without adopting them, the
    +// recording would never merge them.
    +func TestAdoptLegacyProfiles(t *testing.T) {

    Could you add cases for (a) a non-partial legacy profile with the same recording-id, which shouldn't be relabeled; (b) stale legacy partial profiles from a same-named recording that is already deleted; and (c) the ambiguous case, checking that the partial profiles aren't orphaned after the release?

    saschagrunert saschagrunert approved these changes on Oct 07, 2026 05:30 UTC
    Approved Reviewer

    Approved these changes.

    kubernetes-prow[bot] kubernetes-prow[bot] commented on Oct 07, 2026 05:30 UTC
    Bot

    [APPROVALNOTIFIER] This PR is APPROVED

    This pull-request has been approved by: <a href="https://github.com/kubernetes-sigs/security-profiles-operator/pull/3552#pullrequestreview-5438047409" title="Approved">saschagrunert</a>, <a href="https://github.com/kubernetes-sigs/security-profiles-operator/pull/3552#" title="Author self-approved">Vincent056</a>

    The full list of commands accepted by this bot can be found here.

    The pull request process is described here

    <details >
    Needs approval from an approver in each of these files:

  • ~~OWNERS~~ [saschagrunert]
  • Approvers can indicate their approval by writing /approve in a comment
    Approvers can cancel approval by writing /approve cancel in a comment
    </details>
    <!-- META={"approvers":[]} -->

    saschagrunert saschagrunert commented on code on Oct 07, 2026 05:31 UTC
    Code Review
    internal/pkg/manager/recordingmerger/legacy.go:1
    @@ -0,0 +1,408 @@
    +/*
    +Copyright The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package recordingmerger
    +
    +import (
    +	"context"
    +	"fmt"
    +	"slices"
    +	"strings"
    +	"time"
    +
    +	"k8s.io/apimachinery/pkg/api/meta"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/apimachinery/pkg/labels"
    +	"k8s.io/apimachinery/pkg/runtime"
    +	"k8s.io/apimachinery/pkg/selection"
    +	"k8s.io/apimachinery/pkg/util/wait"
    +	"sigs.k8s.io/controller-runtime/pkg/client"
    +
    +	profilerecordingapi "sigs.k8s.io/security-profiles-operator/api/profilerecording/v1"
    +	"sigs.k8s.io/security-profiles-operator/internal/pkg/util"
    +)
    +
    +// Partial profiles recorded before 1.0 only carry the recording name, while
    +// the merge and the release of a recording select its partial profiles by the
    +// recording name and namespace. A recording which was started before an
    +// upgrade would never merge them, so they are adopted once at startup: every
    +// recording which may own them still exists then. A recording which may own
    +// partial profiles that could not be adopted keeps its finalizer, because
    +// releasing it would orphan them and merging them could add the syscalls of
    +// another workload to its profile.
    +
    +const (
    +	// legacyAdoptionWait is how long a deleted recording waits for the
    +	// adoption at startup before it is reconciled again.
    +	legacyAdoptionWait = 2 * time.Second
    +
    +	// legacyHoldWait is how long a deleted recording which is held for
    +	// partial profiles recorded before 1.0 waits before it checks them again.
    +	legacyHoldWait = time.Minute
    +
    +	// legacyCacheTimeout bounds the wait for the cache to show the adopted
    +	// partial profiles.
    +	legacyCacheTimeout = 2 * time.Minute
    +
    +	// legacyEventProfiles is how many partial profiles an event names.
    +	legacyEventProfiles = 5
    +
    +	reasonAmbiguousLegacy string = "AmbiguousLegacyPartialProfiles"
    +	reasonHeldForLegacy   string = "UnattributedLegacyPartialProfiles"
    +)
    +
    +// legacyAdoptionBackoff retries the adoption at startup after errors.
    +var legacyAdoptionBackoff = wait.Backoff{
    +	Duration: time.Second,
    +	Factor:   2,
    +	Steps:    6,
    +}
    +
    +// legacyPartialProfileSelector selects the partial profiles recorded before
    +// 1.0 by the recordings with this name: the partial profile labels of a
    +// recording, without the recording namespace.
    +func legacyPartialProfileSelector(recordingName string) (client.MatchingLabelsSelector, error) {
    +	selector := labels.NewSelector()
    +
    +	for key, value := range partialProfileLabels(&profilerecordingapi.ProfileRecording{
    +		ObjectMeta: metav1.ObjectMeta{Name: recordingName},
    +	}) {
    +		op, values := selection.Equals, []string{value}
    +		if key == profilerecordingapi.ProfileToRecordingNamespaceLabel {
    +			op, values = selection.DoesNotExist, nil
    +		}
    +
    +		requirement, err := labels.NewRequirement(key, op, values)
    +		if err != nil {
    +			return client.MatchingLabelsSelector{}, fmt.Errorf(
    +				"selecting partial profiles recorded before 1.0: %w", err,
    +			)
    +		}
    +
    +		selector = selector.Add(*requirement)
    +	}
    +
    +	return client.MatchingLabelsSelector{Selector: selector}, nil
    +}
    +
    +// listLegacyPartialProfiles lists the partial profiles of every kind which
    +// were recorded before 1.0 by a recording with this name and are not being
    +// deleted.
    +func listLegacyPartialProfiles(
    +	ctx context.Context,
    +	reader client.Reader,
    +	recordingName string,
    +) ([]client.Object, error) {
    +	selector, err := legacyPartialProfileSelector(recordingName)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	var profiles []client.Object
    +
    +	for _, k := range mergeKinds {
    +		list := k.newList()
    +		if err := reader.List(ctx, list, selector); err != nil {
    +			return nil, fmt.Errorf(
    +				"listing partial profiles of kind %s recorded before 1.0: %w",
    +				k.kind,
    +				err,
    +			)
    +		}
    +
    +		if err := meta.EachListItem(list, func(obj runtime.Object) error {
    +			prf, ok := obj.(client.Object)
    +			if !ok {
    +				return fmt.Errorf("object %T is not a client.Object", obj)
    +			}
    +
    +			if prf.GetDeletionTimestamp().IsZero() {
    +				profiles = append(profiles, prf)
    +			}
    +
    +			return nil
    +		}); err != nil {
    +			return nil, err
    +		}
    +	}
    +
    +	return profiles, nil
    +}
    +
    +// mayOwn returns whether the recording may have recorded the profile. A
    +// recording which was created after the profile cannot have recorded it.
    +func mayOwn(recording *profilerecordingapi.ProfileRecording, prf client.Object) bool {
    +	return !recording.GetCreationTimestamp().After(prf.GetCreationTimestamp().Time)
    +}
    +
    +// profileNames names the first profiles for an event.
    +func profileNames(profiles []client.Object) string {
    +	names := make([]string, 0, len(profiles))
    +	for _, prf := range profiles {
    +		names = append(names, prf.GetName())
    +	}
    +
    +	slices.Sort(names)
    +
    +	if len(names) <= legacyEventProfiles {
    +		return strings.Join(names, ", ")
    +	}
    +
    +	return fmt.Sprintf("%s and %d more",
    +		strings.Join(names[:legacyEventProfiles], ", "), len(names)-legacyEventProfiles)
    +}
    +
    +// apiReader returns the reader of the API server, and the client in tests.
    +func (r *PolicyMergeReconciler) apiReader() client.Reader {
    +	if r.reader != nil {
    +		return r.reader
    +	}
    +
    +	return r.client
    +}
    +
    +// legacyAdopter adopts the partial profiles recorded before 1.0 once, when
    +// the manager starts. It runs on the leader, like the merge.
    +type legacyAdopter struct {
    +	r *PolicyMergeReconciler
    +}
    +
    +// NeedLeaderElection runs the adoption on the leader only.
    +func (*legacyAdopter) NeedLeaderElection() bool {
    +	return true
    +}
    +
    +// Start adopts the partial profiles recorded before 1.0 and lets the deleted
    +// recordings be merged afterwards. Errors are logged rather than returned,
    +// because they must not stop the manager: a recording which may own partial
    +// profiles that were not adopted is held, see legacyHold.
    +func (a *legacyAdopter) Start(ctx context.Context) error {
    +	defer a.r.legacyAdoptionPending.Store(false)
    +
    +	err := wait.ExponentialBackoffWithContext(
    +		ctx,
    +		legacyAdoptionBackoff,
    +		func(ctx context.Context) (bool, error) {
    +			if err := a.r.adoptLegacyPartialProfiles(ctx); err != nil {
    +				a.r.log.Error(
    +					err,
    +					"Cannot adopt the partial profiles recorded before 1.0, retrying",
    +				)
    +
    +				return false, nil
    +			}
    +
    +			return true, nil
    +		},
    +	)
    +	if err != nil {
    +		a.r.log.Error(err, "Giving up adopting the partial profiles recorded before 1.0")
    +	}
    +
    +	return nil
    +}
    +
    +// adoptLegacyPartialProfiles labels every partial profile recorded before 1.0
    +// with the namespace of the only recording which may have recorded it. The
    +// recordings are listed from the API server: the cache only covers the watched
    +// namespaces, and a recording outside of them may own a partial profile too.
    +func (r *PolicyMergeReconciler) adoptLegacyPartialProfiles(ctx context.Context) error {
    +	reader := r.apiReader()
    +
    +	recordings := &profilerecordingapi.ProfileRecordingList{}
    +	if err := reader.List(ctx, recordings); err != nil {
    +		return fmt.Errorf("listing profile recordings: %w", err)
    +	}
    +
    +	byName := map[string][]*profilerecordingapi.ProfileRecording{}
    +
    +	for i := range recordings.Items {
    +		recording := &recordings.Items[i]
    +		byName[recording.GetName()] = append(byName[recording.GetName()], recording)
    +	}
    +
    +	var adopted []client.Object
    +
    +	for name, recordingsWithName := range byName {
    +		profiles, err := listLegacyPartialProfiles(ctx, reader, name)
    +		if err != nil {
    +			return err
    +		}
    +
    +		ambiguous := map[*profilerecordingapi.ProfileRecording][]client.Object{}
    +
    +		for _, prf := range profiles {
    +			var owners []*profilerecordingapi.ProfileRecording
    +
    +			for _, recording := range recordingsWithName {
    +				if mayOwn(recording, prf) {
    +					owners = append(owners, recording)
    +				}
    +			}
    +
    +			switch len(owners) {
    +			case 0:
    +				// Recorded by a recording which is gone: a recording with the
    +				// same name was created later.
    +				r.log.Info("No recording may own the partial profile recorded before 1.0",
    +					"profile", prf.GetName(), "recording", name)
    +			case 1:
    +				if err := r.adoptLegacyPartialProfile(ctx, prf, owners[0]); err != nil {
    +					return err
    +				}
    +
    +				adopted = append(adopted, prf)
    +			default:
    +				for _, owner := range owners {
    +					ambiguous[owner] = append(ambiguous[owner], prf)
    +				}
    +			}
    +		}
    +
    +		for owner, ownerProfiles := range ambiguous {
    +			r.record.Eventf(
    +				owner,
    +				nil,
    +				util.EventTypeWarning,
    +				reasonAmbiguousLegacy,
    +				util.EventActionMerge,
    +				"Partial profiles recorded before 1.0 may belong to this or another recording named %s, "+
    +					"set the %s label to the namespace of their recording to merge them: %s",
    +				name,
    +				profilerecordingapi.ProfileToRecordingNamespaceLabel,
    +				profileNames(ownerProfiles),
    +			)
    +		}
    +	}
    +
    +	if len(adopted) > 0 {
    +		r.log.Info("Adopted partial profiles recorded before 1.0", "profiles", len(adopted))
    +	}
    +
    +	return r.waitForCachedAdoption(ctx, adopted)
    +}
    +
    +// adoptLegacyPartialProfile labels a partial profile recorded before 1.0 with
    +// the namespace of its recording.
    +func (r *PolicyMergeReconciler) adoptLegacyPartialProfile(
    +	ctx context.Context,
    +	prf client.Object,
    +	recording *profilerecordingapi.ProfileRecording,
    +) error {
    +	orig, ok := prf.DeepCopyObject().(client.Object)
    +	if !ok {
    +		return fmt.Errorf("object %T is not a client.Object", prf)
    +	}
    +
    +	prfLabels := prf.GetLabels()
    +	prfLabels[profilerecordingapi.ProfileToRecordingNamespaceLabel] = recording.GetNamespace()
    +	prf.SetLabels(prfLabels)
    +
    +	if err := r.client.Patch(ctx, prf, client.MergeFrom(orig)); err != nil {
    +		return fmt.Errorf("labeling partial profile %s: %w", prf.GetName(), err)
    +	}
    +
    +	return nil
    +}
    +
    +// waitForCachedAdoption waits until the cache shows the adopted partial
    +// profiles, so that the merge of a deleted recording, which lists them from
    +// the cache, does not miss them once the adoption is done.
    +func (r *PolicyMergeReconciler) waitForCachedAdoption(
    +	ctx context.Context,
    +	adopted []client.Object,
    +) error {
    +	if len(adopted) == 0 {

    If this times out, Start retries adoptLegacyPartialProfiles, which lists from the API server and finds no unlabeled profiles anymore. adopted is then empty, the wait is skipped and legacyAdoptionPending gets cleared while the cache may still not show the labels. A merge in that window misses the profiles, releaseRecording still sees them through the API reader and keeps the finalizer, and nothing reconciles the recording again until the next resync. Unlikely with a two minute timeout, but keeping the adopted profiles across retries (or waiting on them in Start) would close it.

    saschagrunert saschagrunert commented on code on Oct 07, 2026 05:31 UTC
    Code Review
    internal/pkg/manager/recordingmerger/legacy.go:1
    @@ -0,0 +1,408 @@
    +/*
    +Copyright The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package recordingmerger
    +
    +import (
    +	"context"
    +	"fmt"
    +	"slices"
    +	"strings"
    +	"time"
    +
    +	"k8s.io/apimachinery/pkg/api/meta"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/apimachinery/pkg/labels"
    +	"k8s.io/apimachinery/pkg/runtime"
    +	"k8s.io/apimachinery/pkg/selection"
    +	"k8s.io/apimachinery/pkg/util/wait"
    +	"sigs.k8s.io/controller-runtime/pkg/client"
    +
    +	profilerecordingapi "sigs.k8s.io/security-profiles-operator/api/profilerecording/v1"
    +	"sigs.k8s.io/security-profiles-operator/internal/pkg/util"
    +)
    +
    +// Partial profiles recorded before 1.0 only carry the recording name, while
    +// the merge and the release of a recording select its partial profiles by the
    +// recording name and namespace. A recording which was started before an
    +// upgrade would never merge them, so they are adopted once at startup: every
    +// recording which may own them still exists then. A recording which may own
    +// partial profiles that could not be adopted keeps its finalizer, because
    +// releasing it would orphan them and merging them could add the syscalls of
    +// another workload to its profile.
    +
    +const (
    +	// legacyAdoptionWait is how long a deleted recording waits for the
    +	// adoption at startup before it is reconciled again.
    +	legacyAdoptionWait = 2 * time.Second
    +
    +	// legacyHoldWait is how long a deleted recording which is held for
    +	// partial profiles recorded before 1.0 waits before it checks them again.
    +	legacyHoldWait = time.Minute
    +
    +	// legacyCacheTimeout bounds the wait for the cache to show the adopted
    +	// partial profiles.
    +	legacyCacheTimeout = 2 * time.Minute
    +
    +	// legacyEventProfiles is how many partial profiles an event names.
    +	legacyEventProfiles = 5
    +
    +	reasonAmbiguousLegacy string = "AmbiguousLegacyPartialProfiles"
    +	reasonHeldForLegacy   string = "UnattributedLegacyPartialProfiles"
    +)
    +
    +// legacyAdoptionBackoff retries the adoption at startup after errors.
    +var legacyAdoptionBackoff = wait.Backoff{
    +	Duration: time.Second,
    +	Factor:   2,
    +	Steps:    6,
    +}
    +
    +// legacyPartialProfileSelector selects the partial profiles recorded before
    +// 1.0 by the recordings with this name: the partial profile labels of a
    +// recording, without the recording namespace.
    +func legacyPartialProfileSelector(recordingName string) (client.MatchingLabelsSelector, error) {
    +	selector := labels.NewSelector()
    +
    +	for key, value := range partialProfileLabels(&profilerecordingapi.ProfileRecording{
    +		ObjectMeta: metav1.ObjectMeta{Name: recordingName},
    +	}) {
    +		op, values := selection.Equals, []string{value}
    +		if key == profilerecordingapi.ProfileToRecordingNamespaceLabel {
    +			op, values = selection.DoesNotExist, nil
    +		}
    +
    +		requirement, err := labels.NewRequirement(key, op, values)
    +		if err != nil {
    +			return client.MatchingLabelsSelector{}, fmt.Errorf(
    +				"selecting partial profiles recorded before 1.0: %w", err,
    +			)
    +		}
    +
    +		selector = selector.Add(*requirement)
    +	}
    +
    +	return client.MatchingLabelsSelector{Selector: selector}, nil
    +}
    +
    +// listLegacyPartialProfiles lists the partial profiles of every kind which
    +// were recorded before 1.0 by a recording with this name and are not being
    +// deleted.
    +func listLegacyPartialProfiles(
    +	ctx context.Context,
    +	reader client.Reader,
    +	recordingName string,
    +) ([]client.Object, error) {
    +	selector, err := legacyPartialProfileSelector(recordingName)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	var profiles []client.Object
    +
    +	for _, k := range mergeKinds {
    +		list := k.newList()
    +		if err := reader.List(ctx, list, selector); err != nil {
    +			return nil, fmt.Errorf(
    +				"listing partial profiles of kind %s recorded before 1.0: %w",
    +				k.kind,
    +				err,
    +			)
    +		}
    +
    +		if err := meta.EachListItem(list, func(obj runtime.Object) error {
    +			prf, ok := obj.(client.Object)
    +			if !ok {
    +				return fmt.Errorf("object %T is not a client.Object", obj)
    +			}
    +
    +			if prf.GetDeletionTimestamp().IsZero() {
    +				profiles = append(profiles, prf)
    +			}
    +
    +			return nil
    +		}); err != nil {
    +			return nil, err
    +		}
    +	}
    +
    +	return profiles, nil
    +}
    +
    +// mayOwn returns whether the recording may have recorded the profile. A
    +// recording which was created after the profile cannot have recorded it.
    +func mayOwn(recording *profilerecordingapi.ProfileRecording, prf client.Object) bool {
    +	return !recording.GetCreationTimestamp().After(prf.GetCreationTimestamp().Time)
    +}
    +
    +// profileNames names the first profiles for an event.
    +func profileNames(profiles []client.Object) string {
    +	names := make([]string, 0, len(profiles))
    +	for _, prf := range profiles {
    +		names = append(names, prf.GetName())
    +	}
    +
    +	slices.Sort(names)
    +
    +	if len(names) <= legacyEventProfiles {
    +		return strings.Join(names, ", ")
    +	}
    +
    +	return fmt.Sprintf("%s and %d more",
    +		strings.Join(names[:legacyEventProfiles], ", "), len(names)-legacyEventProfiles)
    +}
    +
    +// apiReader returns the reader of the API server, and the client in tests.
    +func (r *PolicyMergeReconciler) apiReader() client.Reader {
    +	if r.reader != nil {
    +		return r.reader
    +	}
    +
    +	return r.client
    +}
    +
    +// legacyAdopter adopts the partial profiles recorded before 1.0 once, when
    +// the manager starts. It runs on the leader, like the merge.
    +type legacyAdopter struct {
    +	r *PolicyMergeReconciler
    +}
    +
    +// NeedLeaderElection runs the adoption on the leader only.
    +func (*legacyAdopter) NeedLeaderElection() bool {
    +	return true
    +}
    +
    +// Start adopts the partial profiles recorded before 1.0 and lets the deleted
    +// recordings be merged afterwards. Errors are logged rather than returned,
    +// because they must not stop the manager: a recording which may own partial
    +// profiles that were not adopted is held, see legacyHold.
    +func (a *legacyAdopter) Start(ctx context.Context) error {
    +	defer a.r.legacyAdoptionPending.Store(false)
    +
    +	err := wait.ExponentialBackoffWithContext(
    +		ctx,
    +		legacyAdoptionBackoff,
    +		func(ctx context.Context) (bool, error) {
    +			if err := a.r.adoptLegacyPartialProfiles(ctx); err != nil {
    +				a.r.log.Error(
    +					err,
    +					"Cannot adopt the partial profiles recorded before 1.0, retrying",
    +				)
    +
    +				return false, nil
    +			}
    +
    +			return true, nil
    +		},
    +	)
    +	if err != nil {
    +		a.r.log.Error(err, "Giving up adopting the partial profiles recorded before 1.0")
    +	}
    +
    +	return nil
    +}
    +
    +// adoptLegacyPartialProfiles labels every partial profile recorded before 1.0
    +// with the namespace of the only recording which may have recorded it. The
    +// recordings are listed from the API server: the cache only covers the watched
    +// namespaces, and a recording outside of them may own a partial profile too.
    +func (r *PolicyMergeReconciler) adoptLegacyPartialProfiles(ctx context.Context) error {
    +	reader := r.apiReader()
    +
    +	recordings := &profilerecordingapi.ProfileRecordingList{}
    +	if err := reader.List(ctx, recordings); err != nil {
    +		return fmt.Errorf("listing profile recordings: %w", err)
    +	}
    +
    +	byName := map[string][]*profilerecordingapi.ProfileRecording{}
    +
    +	for i := range recordings.Items {
    +		recording := &recordings.Items[i]
    +		byName[recording.GetName()] = append(byName[recording.GetName()], recording)
    +	}
    +
    +	var adopted []client.Object
    +
    +	for name, recordingsWithName := range byName {
    +		profiles, err := listLegacyPartialProfiles(ctx, reader, name)
    +		if err != nil {
    +			return err
    +		}
    +
    +		ambiguous := map[*profilerecordingapi.ProfileRecording][]client.Object{}
    +
    +		for _, prf := range profiles {
    +			var owners []*profilerecordingapi.ProfileRecording
    +
    +			for _, recording := range recordingsWithName {
    +				if mayOwn(recording, prf) {
    +					owners = append(owners, recording)
    +				}
    +			}
    +
    +			switch len(owners) {
    +			case 0:
    +				// Recorded by a recording which is gone: a recording with the
    +				// same name was created later.
    +				r.log.Info("No recording may own the partial profile recorded before 1.0",
    +					"profile", prf.GetName(), "recording", name)
    +			case 1:
    +				if err := r.adoptLegacyPartialProfile(ctx, prf, owners[0]); err != nil {
    +					return err
    +				}
    +
    +				adopted = append(adopted, prf)
    +			default:
    +				for _, owner := range owners {
    +					ambiguous[owner] = append(ambiguous[owner], prf)
    +				}
    +			}
    +		}
    +
    +		for owner, ownerProfiles := range ambiguous {
    +			r.record.Eventf(
    +				owner,
    +				nil,
    +				util.EventTypeWarning,
    +				reasonAmbiguousLegacy,
    +				util.EventActionMerge,
    +				"Partial profiles recorded before 1.0 may belong to this or another recording named %s, "+
    +					"set the %s label to the namespace of their recording to merge them: %s",
    +				name,
    +				profilerecordingapi.ProfileToRecordingNamespaceLabel,
    +				profileNames(ownerProfiles),
    +			)
    +		}
    +	}
    +
    +	if len(adopted) > 0 {
    +		r.log.Info("Adopted partial profiles recorded before 1.0", "profiles", len(adopted))
    +	}
    +
    +	return r.waitForCachedAdoption(ctx, adopted)
    +}
    +
    +// adoptLegacyPartialProfile labels a partial profile recorded before 1.0 with
    +// the namespace of its recording.
    +func (r *PolicyMergeReconciler) adoptLegacyPartialProfile(
    +	ctx context.Context,
    +	prf client.Object,
    +	recording *profilerecordingapi.ProfileRecording,
    +) error {
    +	orig, ok := prf.DeepCopyObject().(client.Object)
    +	if !ok {
    +		return fmt.Errorf("object %T is not a client.Object", prf)
    +	}
    +
    +	prfLabels := prf.GetLabels()
    +	prfLabels[profilerecordingapi.ProfileToRecordingNamespaceLabel] = recording.GetNamespace()
    +	prf.SetLabels(prfLabels)
    +
    +	if err := r.client.Patch(ctx, prf, client.MergeFrom(orig)); err != nil {
    +		return fmt.Errorf("labeling partial profile %s: %w", prf.GetName(), err)
    +	}
    +
    +	return nil
    +}
    +
    +// waitForCachedAdoption waits until the cache shows the adopted partial
    +// profiles, so that the merge of a deleted recording, which lists them from
    +// the cache, does not miss them once the adoption is done.
    +func (r *PolicyMergeReconciler) waitForCachedAdoption(
    +	ctx context.Context,
    +	adopted []client.Object,
    +) error {
    +	if len(adopted) == 0 {
    +		return nil
    +	}
    +
    +	err := wait.PollUntilContextTimeout(ctx, 100*time.Millisecond, legacyCacheTimeout, true,
    +		func(ctx context.Context) (bool, error) {
    +			for _, prf := range adopted {
    +				cached, ok := prf.DeepCopyObject().(client.Object)
    +				if !ok {
    +					return false, fmt.Errorf("object %T is not a client.Object", prf)
    +				}
    +
    +				if err := r.client.Get(ctx, client.ObjectKeyFromObject(prf), cached); err != nil {
    +					if client.IgnoreNotFound(err) == nil {
    +						continue
    +					}
    +
    +					// Retried until the timeout.
    +					return false, nil
    +				}
    +
    +				if _, ok := cached.GetLabels()[profilerecordingapi.ProfileToRecordingNamespaceLabel]; !ok {
    +					return false, nil
    +				}
    +			}
    +
    +			return true, nil
    +		})
    +	if err != nil {
    +		return fmt.Errorf("waiting for the cache to show the adopted partial profiles: %w", err)
    +	}
    +
    +	return nil
    +}
    +
    +// legacyHold returns how long a deleted recording waits before its partial
    +// profiles get merged and it gets released: while the partial profiles
    +// recorded before 1.0 are being adopted at startup, and as long as partial
    +// profiles recorded before 1.0 exist which it may own but which were not
    +// adopted, because several recordings with its name may own them. They are
    +// merged once their recording namespace label is set.
    +func (r *PolicyMergeReconciler) legacyHold(
    +	ctx context.Context,
    +	recording *profilerecordingapi.ProfileRecording,
    +) (time.Duration, error) {
    +	if r.legacyAdoptionPending.Load() {
    +		return legacyAdoptionWait, nil
    +	}
    +
    +	profiles, err := listLegacyPartialProfiles(ctx, r.apiReader(), recording.GetName())
    +	if err != nil {
    +		return 0, err
    +	}
    +
    +	var held []client.Object
    +
    +	for _, prf := range profiles {
    +		if mayOwn(recording, prf) {
    +			held = append(held, prf)
    +		}
    +	}
    +
    +	if len(held) == 0 {
    +		return 0, nil
    +	}
    +
    +	r.record.Eventf(

    A held recording emits this warning every legacyHoldWait for as long as it is held, which can be indefinitely. Event aggregation limits the noise, but nit: could it be emitted only when the set of held profiles changes, or once per hold?

    saschagrunert saschagrunert commented on code on Oct 07, 2026 05:31 UTC
    Code Review
    internal/pkg/manager/recordingmerger/legacy.go:1
    @@ -0,0 +1,408 @@
    +/*
    +Copyright The Kubernetes Authors.
    +
    +Licensed under the Apache License, Version 2.0 (the "License");
    +you may not use this file except in compliance with the License.
    +You may obtain a copy of the License at
    +
    +    http://www.apache.org/licenses/LICENSE-2.0
    +
    +Unless required by applicable law or agreed to in writing, software
    +distributed under the License is distributed on an "AS IS" BASIS,
    +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    +See the License for the specific language governing permissions and
    +limitations under the License.
    +*/
    +
    +package recordingmerger
    +
    +import (
    +	"context"
    +	"fmt"
    +	"slices"
    +	"strings"
    +	"time"
    +
    +	"k8s.io/apimachinery/pkg/api/meta"
    +	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    +	"k8s.io/apimachinery/pkg/labels"
    +	"k8s.io/apimachinery/pkg/runtime"
    +	"k8s.io/apimachinery/pkg/selection"
    +	"k8s.io/apimachinery/pkg/util/wait"
    +	"sigs.k8s.io/controller-runtime/pkg/client"
    +
    +	profilerecordingapi "sigs.k8s.io/security-profiles-operator/api/profilerecording/v1"
    +	"sigs.k8s.io/security-profiles-operator/internal/pkg/util"
    +)
    +
    +// Partial profiles recorded before 1.0 only carry the recording name, while
    +// the merge and the release of a recording select its partial profiles by the
    +// recording name and namespace. A recording which was started before an
    +// upgrade would never merge them, so they are adopted once at startup: every
    +// recording which may own them still exists then. A recording which may own
    +// partial profiles that could not be adopted keeps its finalizer, because
    +// releasing it would orphan them and merging them could add the syscalls of
    +// another workload to its profile.
    +
    +const (
    +	// legacyAdoptionWait is how long a deleted recording waits for the
    +	// adoption at startup before it is reconciled again.
    +	legacyAdoptionWait = 2 * time.Second
    +
    +	// legacyHoldWait is how long a deleted recording which is held for
    +	// partial profiles recorded before 1.0 waits before it checks them again.
    +	legacyHoldWait = time.Minute
    +
    +	// legacyCacheTimeout bounds the wait for the cache to show the adopted
    +	// partial profiles.
    +	legacyCacheTimeout = 2 * time.Minute
    +
    +	// legacyEventProfiles is how many partial profiles an event names.
    +	legacyEventProfiles = 5
    +
    +	reasonAmbiguousLegacy string = "AmbiguousLegacyPartialProfiles"
    +	reasonHeldForLegacy   string = "UnattributedLegacyPartialProfiles"
    +)
    +
    +// legacyAdoptionBackoff retries the adoption at startup after errors.
    +var legacyAdoptionBackoff = wait.Backoff{
    +	Duration: time.Second,
    +	Factor:   2,
    +	Steps:    6,
    +}
    +
    +// legacyPartialProfileSelector selects the partial profiles recorded before
    +// 1.0 by the recordings with this name: the partial profile labels of a
    +// recording, without the recording namespace.
    +func legacyPartialProfileSelector(recordingName string) (client.MatchingLabelsSelector, error) {
    +	selector := labels.NewSelector()
    +
    +	for key, value := range partialProfileLabels(&profilerecordingapi.ProfileRecording{
    +		ObjectMeta: metav1.ObjectMeta{Name: recordingName},
    +	}) {
    +		op, values := selection.Equals, []string{value}
    +		if key == profilerecordingapi.ProfileToRecordingNamespaceLabel {
    +			op, values = selection.DoesNotExist, nil
    +		}
    +
    +		requirement, err := labels.NewRequirement(key, op, values)
    +		if err != nil {
    +			return client.MatchingLabelsSelector{}, fmt.Errorf(
    +				"selecting partial profiles recorded before 1.0: %w", err,
    +			)
    +		}
    +
    +		selector = selector.Add(*requirement)
    +	}
    +
    +	return client.MatchingLabelsSelector{Selector: selector}, nil
    +}
    +
    +// listLegacyPartialProfiles lists the partial profiles of every kind which
    +// were recorded before 1.0 by a recording with this name and are not being
    +// deleted.
    +func listLegacyPartialProfiles(
    +	ctx context.Context,
    +	reader client.Reader,
    +	recordingName string,
    +) ([]client.Object, error) {
    +	selector, err := legacyPartialProfileSelector(recordingName)
    +	if err != nil {
    +		return nil, err
    +	}
    +
    +	var profiles []client.Object
    +
    +	for _, k := range mergeKinds {
    +		list := k.newList()
    +		if err := reader.List(ctx, list, selector); err != nil {
    +			return nil, fmt.Errorf(
    +				"listing partial profiles of kind %s recorded before 1.0: %w",
    +				k.kind,
    +				err,
    +			)
    +		}
    +
    +		if err := meta.EachListItem(list, func(obj runtime.Object) error {
    +			prf, ok := obj.(client.Object)
    +			if !ok {
    +				return fmt.Errorf("object %T is not a client.Object", obj)
    +			}
    +
    +			if prf.GetDeletionTimestamp().IsZero() {
    +				profiles = append(profiles, prf)
    +			}
    +
    +			return nil
    +		}); err != nil {
    +			return nil, err
    +		}
    +	}
    +
    +	return profiles, nil
    +}
    +
    +// mayOwn returns whether the recording may have recorded the profile. A
    +// recording which was created after the profile cannot have recorded it.
    +func mayOwn(recording *profilerecordingapi.ProfileRecording, prf client.Object) bool {
    +	return !recording.GetCreationTimestamp().After(prf.GetCreationTimestamp().Time)

    Not a blocker, but worth a note in the docs: stale partial profiles left by a failed 0.x merge of a deleted recording are still adopted by an older recording with the same name, because the creation time can't tell them apart. Mentioning that such profiles can be labeled or deleted before the upgrade would help.

    saschagrunert saschagrunert commented on Oct 07, 2026 05:31 UTC
    Reviewer

    Thanks for the rework, the startup adoption settles the ordering and cache issues nicely. Could you update the PR description to the new design? It still describes labeling on deletion, the requeue after labeling and the "exactly one recording has that name" rule, which will end up in the merge record. The 1.0.x note probably needs a second look as well.

    Reviewers
    Assignees
    Vincent056 Vincent056
    Labels
    risk: low confidence: 80.1% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 47.3% (MEDIUM) · Higher = larger blast radius
    47.3%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 80.1% · Lower = rushed or shallow review
    80.1%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 9.4% · Safe to merge
    9.4%