diff --git a/docs/docs/operator/building-blocks/controllers.mdx b/docs/docs/operator/building-blocks/controllers.mdx index 2a41cab6..ff762ad9 100644 --- a/docs/docs/operator/building-blocks/controllers.mdx +++ b/docs/docs/operator/building-blocks/controllers.mdx @@ -145,6 +145,11 @@ This method is called when a resource is deleted, but should only be used for: - Triggering non-critical cleanup tasks - Updating external systems about the deletion +If an object is deleted and recreated under the same name, `DeletedAsync` for the old object and +`ReconcileAsync` for the new one are independent reconciliations and may run in any order or in +parallel. Do not clean up resources in `DeletedAsync` by a name derived from the entity alone — the +recreated object may already own them. Use owner references or [finalizers](./finalizer) instead. + ```csharp public async Task> DeletedAsync( V1DemoEntity entity, diff --git a/docs/docs/operator/configuration/queue-strategy.mdx b/docs/docs/operator/configuration/queue-strategy.mdx index 755f4e99..0e8784d2 100644 --- a/docs/docs/operator/configuration/queue-strategy.mdx +++ b/docs/docs/operator/configuration/queue-strategy.mdx @@ -31,9 +31,15 @@ queue-consumer hosted service. Which consumer is started depends on the configur All scheduling state lives in the operator pod's heap. When the same entity is scheduled multiple times before it becomes ready, the in-memory queue keeps -one entry per namespace/name key. The entry scheduled to run earliest is kept, and later enqueue calls -can update the reconciliation metadata for that scheduled entry. Scheduled entries are not removed by -the reconciler while processing an API-server event. +one entry per object, keyed by the object's UID (entities without a UID fall back to namespace/name). +The entry scheduled to run earliest is kept, and later enqueue calls can update the reconciliation +metadata for that scheduled entry. Scheduled entries are not removed by the reconciler while processing +an API-server event. + +Because the key is the UID, an object that is deleted and recreated under the same name yields two +separate entries: `DeletedAsync` receives the deleted object and `ReconcileAsync` receives the new one. +An entry for a non-deleted object whose name now resolves to a different (recreated) object is skipped +when it is processed, since the new object is reconciled through its own entry. - **Advantages**: Zero configuration. Minimal latency between watch event and reconciliation call. - **Disadvantages**: Pending requeue timers are lost when the pod restarts. In practice this is @@ -77,7 +83,7 @@ in-memory queue (see [Multiple Controllers per Entity](../building-blocks/contro ::: Custom queues should follow the same de-duplication contract as the built-in implementation: keep at -most one pending entry per namespace/name key and preserve the earliest scheduled execution time. +most one pending entry per object UID (falling back to namespace/name when no UID is set) and preserve the earliest scheduled execution time. `Enqueue` returns `Task`: return `true` when the entry was scheduled and `false` when it was dropped (for example because the `cancellationToken` was already cancelled, or — for a queue that @@ -99,7 +105,7 @@ public Task Enqueue( return Task.FromResult(false); // dropped } - // ... schedule the entry (de-duplicated by namespace/name) ... + // ... schedule the entry (de-duplicated by UID) ... return Task.FromResult(true); // scheduled } ``` diff --git a/src/KubeOps.Operator/Queue/EntityQueueBackgroundService{TEntity}.cs b/src/KubeOps.Operator/Queue/EntityQueueBackgroundService{TEntity}.cs index f6dadd05..6d93da9f 100644 --- a/src/KubeOps.Operator/Queue/EntityQueueBackgroundService{TEntity}.cs +++ b/src/KubeOps.Operator/Queue/EntityQueueBackgroundService{TEntity}.cs @@ -110,6 +110,21 @@ protected virtual async Task> ReconcileSingleAsync ? entry.Entity : await client.GetAsync(entry.Entity.Name(), entry.Entity.Namespace(), cancellationToken); + // The object loaded by name may be a different object than the one the entry was scheduled for, when + // the original was deleted and recreated under the same name (e.g. a pending requeue whose Deleted + // event was never observed). That object has its own queue entry, so the stale one is skipped. + if (entity is not null + && !string.IsNullOrEmpty(entry.Entity.Uid()) + && entity.Uid() != entry.Entity.Uid()) + { + logger + .LogDebug( + """Queued entry for "{Identifier}" is stale; the object was recreated as "{Current}". Skipping.""", + entry.Entity.ToIdentifierString(), + entity.ToIdentifierString()); + return ReconciliationResult.Success(entity); + } + if (entity is not null) { // The gate runs on the entity that will actually be reconciled — the freshly loaded object for diff --git a/src/KubeOps.Operator/Queue/TimedEntityQueue.cs b/src/KubeOps.Operator/Queue/TimedEntityQueue.cs index 8952a43a..2cbbcf30 100644 --- a/src/KubeOps.Operator/Queue/TimedEntityQueue.cs +++ b/src/KubeOps.Operator/Queue/TimedEntityQueue.cs @@ -157,7 +157,8 @@ public Task Enqueue(TEntity entity, ReconciliationType type, Reconciliatio newQueueIn.TotalSeconds); } - // schedule deleted reconciliations must not be cancelled + // schedule deleted reconciliations must not be cancelled; entries are keyed by UID, so + // this only merges events of the same object, never those of a recreated namesake var newReconciliationType = oldEntry.ReconciliationType == ReconciliationType.Deleted ? oldEntry.ReconciliationType : type; diff --git a/src/KubeOps.Operator/Queue/TimedEntityQueueExtensions.cs b/src/KubeOps.Operator/Queue/TimedEntityQueueExtensions.cs index 3ac377d8..6de53baa 100644 --- a/src/KubeOps.Operator/Queue/TimedEntityQueueExtensions.cs +++ b/src/KubeOps.Operator/Queue/TimedEntityQueueExtensions.cs @@ -13,9 +13,10 @@ namespace KubeOps.Operator.Queue; public static class TimedEntityQueueExtensions { /// - /// Retrieves a unique key for the specified Kubernetes entity. The key is constructed - /// using the entity's namespace and name, if available. If the entity does not have - /// a valid name, the method returns null. + /// Retrieves a unique key for the specified Kubernetes entity. The key is the entity's UID, so that + /// a deleted object and a newly created object with the same namespace and name are never merged into + /// one queue entry. Entities without a UID (e.g. objects constructed locally) fall back to namespace + /// and name. If the entity does not have a valid name, the method returns null. /// /// /// The type of the Kubernetes entity. Must implement . @@ -38,6 +39,11 @@ public static class TimedEntityQueueExtensions return null; } + if (!string.IsNullOrWhiteSpace(entity.Uid())) + { + return entity.Uid(); + } + return string.IsNullOrWhiteSpace(entity.Namespace()) ? entity.Name() : $"{entity.Namespace()}/{entity.Name()}"; diff --git a/test/KubeOps.Operator.Test/Queue/EntityQueueBackgroundService.Test.cs b/test/KubeOps.Operator.Test/Queue/EntityQueueBackgroundService.Test.cs index c00905a5..59d6e099 100644 --- a/test/KubeOps.Operator.Test/Queue/EntityQueueBackgroundService.Test.cs +++ b/test/KubeOps.Operator.Test/Queue/EntityQueueBackgroundService.Test.cs @@ -527,6 +527,33 @@ public async Task Deleted_Entry_Uses_Entity_From_Queue_Without_Client_Lookup() Times.Once); } + [Trait("Area", "EntityIdentity")] + [Fact] + public async Task Stale_Entry_Is_Skipped_When_Object_Was_Recreated_With_Same_Name() + { + var queue = new ControllableQueue(); + var reconcilerMock = new Mock>(); + var clientMock = new Mock(); + var stale = CreateEntity("uid-old"); + var recreated = CreateEntity("uid-new"); + + await using var service = CreateService(queue, reconcilerMock, clientMock, recreated); + await service.StartAsync(TestContext.Current.CancellationToken); + + queue.Push(stale, ReconciliationType.Modified, ReconciliationTriggerSource.Operator); + queue.Complete(); + + await Task.Delay(300, TestContext.Current.CancellationToken); + await service.StopAsync(TestContext.Current.CancellationToken); + + reconcilerMock.Verify( + r => r.Reconcile( + It.IsAny>(), + It.IsAny()), + Times.Never); + queue.EnqueueCallCount.Should().Be(0); + } + [Fact] public async Task Discard_Strategy_Drops_Concurrent_Entry_For_Same_Uid() { diff --git a/test/KubeOps.Operator.Test/Queue/ScopeAwareEntityQueueBackgroundService.Test.cs b/test/KubeOps.Operator.Test/Queue/ScopeAwareEntityQueueBackgroundService.Test.cs index ab35081f..53e3dd00 100644 --- a/test/KubeOps.Operator.Test/Queue/ScopeAwareEntityQueueBackgroundService.Test.cs +++ b/test/KubeOps.Operator.Test/Queue/ScopeAwareEntityQueueBackgroundService.Test.cs @@ -146,10 +146,17 @@ private void SetupResponsibility(V1OperatorIntegrationTestEntity entity, bool re .Setup(s => s.IsResponsibleForAsync(entity, It.IsAny())) .ReturnsAsync(responsible); - private static V1OperatorIntegrationTestEntity CreateEntity(string uid) => + // Snapshot and current are two states of the same object, so they share the UID and differ in version. + private static V1OperatorIntegrationTestEntity CreateEntity(string resourceVersion) => new() { - Metadata = new V1ObjectMeta { Name = "test-entity", NamespaceProperty = "test-namespace", Uid = uid }, + Metadata = new V1ObjectMeta + { + Name = "test-entity", + NamespaceProperty = "test-namespace", + Uid = "test-uid", + ResourceVersion = resourceVersion, + }, }; private static QueueEntry CreateEntry( diff --git a/test/KubeOps.Operator.Test/Queue/TimedEntityQueue.Test.cs b/test/KubeOps.Operator.Test/Queue/TimedEntityQueue.Test.cs index 72cf2f9f..5b006ed8 100644 --- a/test/KubeOps.Operator.Test/Queue/TimedEntityQueue.Test.cs +++ b/test/KubeOps.Operator.Test/Queue/TimedEntityQueue.Test.cs @@ -328,6 +328,109 @@ public void Dispose_Should_Complete_Without_Exception() act.Should().NotThrow(); } + [Trait("Area", "EntityIdentity")] + [Fact] + public async Task Enqueue_Should_Not_Merge_Added_Of_Recreated_Object_Into_Pending_Deleted() + { + using var queue = new TimedEntityQueue(Mock.Of>>()); + var deleted = CreateSecret("ns", "secret", "uid-old"); + var recreated = CreateSecret("ns", "secret", "uid-new"); + + await queue.Enqueue( + deleted, + ReconciliationType.Deleted, + ReconciliationTriggerSource.ApiServer, + TimeSpan.Zero, + retryCount: 0, + TestContext.Current.CancellationToken); + await queue.Enqueue( + recreated, + ReconciliationType.Added, + ReconciliationTriggerSource.ApiServer, + TimeSpan.Zero, + retryCount: 0, + TestContext.Current.CancellationToken); + + var items = await DrainQueue(queue, TimeSpan.FromMilliseconds(500)); + + items.Should().HaveCount(2); + items.Should().ContainSingle(e => e.ReconciliationType == ReconciliationType.Deleted) + .Which.Entity.Uid().Should().Be("uid-old"); + items.Should().ContainSingle(e => e.ReconciliationType == ReconciliationType.Added) + .Which.Entity.Uid().Should().Be("uid-new"); + } + + [Trait("Area", "EntityIdentity")] + [Fact] + public async Task Enqueue_Should_Not_Merge_Deleted_Retry_Of_Previous_Object_Into_Pending_Added() + { + using var queue = new TimedEntityQueue(Mock.Of>>()); + var recreated = CreateSecret("ns", "secret", "uid-new"); + var deleted = CreateSecret("ns", "secret", "uid-old"); + + await queue.Enqueue( + recreated, + ReconciliationType.Added, + ReconciliationTriggerSource.ApiServer, + TimeSpan.Zero, + retryCount: 0, + TestContext.Current.CancellationToken); + await queue.Enqueue( + deleted, + ReconciliationType.Deleted, + ReconciliationTriggerSource.ApiServer, + TimeSpan.FromMilliseconds(100), + retryCount: 1, + TestContext.Current.CancellationToken); + + var items = await DrainQueue(queue, TimeSpan.FromMilliseconds(500)); + + items.Should().HaveCount(2); + items.Should().ContainSingle(e => e.ReconciliationType == ReconciliationType.Added) + .Which.Entity.Uid().Should().Be("uid-new"); + items.Should().ContainSingle(e => e.ReconciliationType == ReconciliationType.Deleted) + .Which.Entity.Uid().Should().Be("uid-old"); + } + + [Trait("Area", "EntityIdentity")] + [Fact] + public async Task Enqueue_Should_Merge_Entries_Of_Same_Uid() + { + using var queue = new TimedEntityQueue(Mock.Of>>()); + + await queue.Enqueue( + CreateSecret("ns", "secret", "uid"), + ReconciliationType.Deleted, + ReconciliationTriggerSource.ApiServer, + TimeSpan.FromMilliseconds(100), + retryCount: 0, + TestContext.Current.CancellationToken); + await queue.Enqueue( + CreateSecret("ns", "secret", "uid"), + ReconciliationType.Modified, + ReconciliationTriggerSource.Operator, + TimeSpan.FromMilliseconds(100), + retryCount: 0, + TestContext.Current.CancellationToken); + + queue.Count.Should().Be(1); + + var items = await DrainQueue(queue, TimeSpan.FromMilliseconds(500)); + + items.Should().ContainSingle() + .Which.ReconciliationType.Should().Be(ReconciliationType.Deleted); + } + + [Trait("Area", "EntityIdentity")] + [Fact] + public void GetKey_Should_Use_Uid_And_Fall_Back_To_Namespace_And_Name() + { + using var queue = new TimedEntityQueue(Mock.Of>>()); + + queue.GetKey(CreateSecret("ns", "secret", "uid")).Should().Be("uid"); + queue.GetKey(CreateSecret("ns", "secret")).Should().Be("ns/secret"); + } + private static V1Secret CreateSecret(string secretNamespace, string secretName) { var secret = new V1Secret(); @@ -339,6 +442,13 @@ private static V1Secret CreateSecret(string secretNamespace, string secretName) return secret; } + private static V1Secret CreateSecret(string secretNamespace, string secretName, string uid) + { + var secret = CreateSecret(secretNamespace, secretName); + secret.Metadata.Uid = uid; + return secret; + } + private static async Task WaitUntil(Func condition, TimeSpan timeout) { var deadline = DateTimeOffset.UtcNow + timeout;