Skip to content

[bug]: TimedEntityQueue coalesces a recreated object's Added into the namesake's pending Deleted — the new object is never reconciled #1266

Closed

Description

@guillaume86

Describe the bug

TimedEntityQueue<TEntity> keys its pending-entry dictionary by namespace/name, not by uid, and its AddOrUpdate merge preserves a pending entry's Deleted reconciliation type unconditionally. When an object is deleted and a new object with the same name is created while the Deleted entry is still pending (it sits in _management for up to one 100 ms timer tick, longer for delayed requeues), the new object's Added event is coalesced into the delete:

  • the merged entry keeps ReconciliationType.Deleted but now carries the new entity, so DeletedAsync is invoked with an object that is alive on the API server;
  • the new object's Added reconciliation never happens — its birth edge is lost.

The loss is sticky, not self-healing: the watcher's uid-keyed generation cache has already recorded the new object's generation when the event was accepted, so (under the generation-based reconcile strategy) subsequent Modified events at the same generation are suppressed. The recreated object is never reconciled until its spec changes (generation bump) or the watch re-lists (reconnect / operator restart). We observed recreated objects sitting unmanaged for minutes in an otherwise healthy operator.

The relevant code in src/KubeOps.Operator/Queue/TimedEntityQueue.cs (v13.1.0, unchanged on main as of v13.3.1):

// TimedEntityQueueExtensions.GetKey — identity is name, not uid:
return string.IsNullOrWhiteSpace(entity.Namespace())
    ? entity.Name()
    : $"{entity.Namespace()}/{entity.Name()}";
// Enqueue's updateValueFactory — a pending Deleted swallows whatever arrives for the same key:
// schedule deleted reconciliations must not be cancelled
var newReconciliationType = oldEntry.ReconciliationType == ReconciliationType.Deleted
    ? oldEntry.ReconciliationType
    : type;

oldEntry.Cancel();
return new(entity, newReconciliationType, reconciliationTriggerSource, newQueueIn, retryCount);

The "deleted reconciliations must not be cancelled" guard is sound for the same object, but across a delete/recreate the same key names two different objects (different uids), and coalescing their events is never sound: both reconciliations matter — the old object's deletion and the new object's birth.

To reproduce

Directly against the queue (the exact race, made deterministic — both enqueues land inside one promotion tick):

using k8s.Models;
using KubeOps.Abstractions.Reconciliation;
using KubeOps.Operator.Queue;
using Microsoft.Extensions.Logging.Abstractions;

var queue = new TimedEntityQueue<V1ConfigMap>(NullLogger<TimedEntityQueue<V1ConfigMap>>.Instance);

var dead  = new V1ConfigMap { Metadata = new V1ObjectMeta(name: "sample", namespaceProperty: "default", uid: "uid-old") };
var fresh = new V1ConfigMap { Metadata = new V1ObjectMeta(name: "sample", namespaceProperty: "default", uid: "uid-new") };

// The watcher enqueues every watch event with queueIn: TimeSpan.Zero.
await queue.Enqueue(dead,  ReconciliationType.Deleted, ReconciliationTriggerSource.ApiServer, TimeSpan.Zero, 0, CancellationToken.None);
await queue.Enqueue(fresh, ReconciliationType.Added,   ReconciliationTriggerSource.ApiServer, TimeSpan.Zero, 0, CancellationToken.None);

await foreach (var entry in queue)
{
    // Exactly one entry comes out:
    //   entry.ReconciliationType == ReconciliationType.Deleted
    //   entry.Entity.Uid()       == "uid-new"
    // The new object's Added is gone, and DeletedAsync will receive the live object.
    Console.WriteLine($"{entry.ReconciliationType} {entry.Entity.Uid()}");
    break;
}

End to end, with any operator built from the getting-started template (a custom entity, say Widget, and a controller that logs ReconcileAsync / DeletedAsync):

  1. kubectl apply -f widget.yaml (name sample) → ReconcileAsync logs, as expected.
  2. Recreate it under the same name inside the coalescing window — back-to-back delete + create, e.g. kubectl delete widget sample --wait=false && kubectl apply -f widget.yaml, or kubectl replace --force -f widget.yaml. Programmatic delete-then-create (a controller superseding a resource it manages) hits the window reliably.
  3. Observe: DeletedAsync fires (inspect the entity — it is the new object, alive on the API server); ReconcileAsync for the recreated object never fires.
  4. The object stays unreconciled indefinitely; edit its spec (generation bump) or restart the operator and reconciliation resumes.

The window is one 100 ms promotion tick for watch events; for entries scheduled with a delay (error retry / requeue) the window is the whole remaining delay.

Expected behavior

A delete/recreate of the same name yields both reconciliations: DeletedAsync with the old object and ReconcileAsync with the new one. One object's pending deletion must never consume a different object's birth; DeletedAsync must never receive an object that exists on the API server.

The clean fix seems to be keying _management by uid (falling back to namespace/name only where no uid exists): the dead object's Deleted entry and the new object's Added entry then coexist naturally, and the Deleted-preservation guard keeps working for genuine same-object event runs. A narrower alternative is to preserve Deleted in the updateValueFactory only when the incoming entity's uid matches the pending entry's — a different uid means a different object, whose events must not be merged.

Screenshots

No response

Additional Context

  • Observed on KubeOps 13.1.0 (.NET); the queue code is unchanged on main as of v13.3.1, so the defect should still be present in current releases.
  • The second-order effect deserves a mention because it turns a lost edge into a lost object: the uid-keyed generation dedup in the watcher records the recreated object's generation when its (subsequently swallowed) Added is accepted, so later metadata-only events are suppressed and nothing re-triggers reconciliation until a generation bump or a watch re-list.
  • Happy to provide more detail or test a fix.

Activity

  1. kimpenhaus commented on Sep 30, 2026

    @kimpenhaus
    Collaborator

    hey @guillaume86,

    thanks for the detailed bug report. I just pushed a fix - maybe you can re-test with that version once the pre-release is created?

    The namespace/name key is an old relict and I changed it to use the UID as all the other caches already do.

    Hope that helps - thanks again!

  2. guillaume86 commented on Oct 1, 2026

    @guillaume86
    Author

    Re-tested on 13.3.2-prerelease.2 — confirmed fixed, thank you for the fast turnaround.

    • The unit-level repro from the report now yields both entries: the Deleted carrying the old uid and the Added carrying the new one.
    • Our operator's test suite, including the delete/recreate-same-name rebirth scenario that originally caught this, is green on the prerelease, and the operator runs clean on a kind testbed.

    We've taken the prerelease; we'll move to 13.3.2 final when it ships.

  3. kimpenhaus commented on Oct 1, 2026

    @kimpenhaus
    Collaborator

    @guillaume86 oh wow - thanks for the fast re-test and confirmation. next stable release with the bugfix in it will be on tuesday next week (10-06-2026)

    best, m.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions