Reduce cache locking duration when the DaemonSet controller fetches pods
Tier 2 medium go · cross-file · real merged PR from kubernetes/kubernetes #130859
Ground-truth defects
The new pod index `AddPodControllerUIDIndexer` / `PodControllerUIDIndex` keys solely on the owning controllerRef's UID (`[]string{string(ref.UID)}`), ignoring namespace, kind, and name. Controllers (DaemonSet/ReplicaSet/Job/StatefulSet) that look pods up through this index can claim the wrong pods when a stale or duplicated ownerReference UID collides. The fix re-keys the index on the full (namespace, kind, name, uid) tuple.
The change under review
diff
@@ -86,6 +86,13 @@ const ( // PodNodeNameKeyIndex is the name of the index used by PodInformer to index pods by their node name. PodNodeNameKeyIndex = "spec.nodeName" + + // OrphanPodIndexKey is used to index all Orphan pods to this key + OrphanPodIndexKey = "_ORPHAN_POD" + + // podControllerUIDIndex is the name for the Pod store's index function, + // which is to index by pods's controllerUID. + PodControllerUIDIndex = "podControllerUID" ) var UpdateTaintBackoff = wait.Backoff{ @@ -1076,6 +1083,30 @@ func AddPodNodeNameIndexer(podInformer cache.SharedIndexInformer) error { }) } +// AddPodControllerUIDIndexer adds an indexer for Pod's controllerRef.UID to the given PodInformer. +// This indexer is used to efficiently look up pods by their ControllerRef.UID +func AddPodControllerUIDIndexer(podInformer cache.SharedIndexInformer) error { + if _, exists := podInformer.GetIndexer().GetIndexers()[PodControllerUIDIndex]; exists { + // indexer already exists, do nothing + return nil + } + return podInformer.AddIndexers(cache.Indexers{ + PodControllerUIDIndex: func(obj interface{}) ([]string, error) { + pod, ok := obj.(*v1.Pod) + if !ok { + return nil, nil + } + // Get the ControllerRef of the Pod to check if it's managed by a controller + if ref := metav1.GetControllerOf(pod); ref != nil { + return []string{string(ref.UID)}, nil + } + // If the Pod has no controller (i.e., it's orphaned), index it with the OrphanPodIndexKey + // This helps identify orphan pods for reconciliation and adoption by controllers + return []string{OrphanPodIndexKey}, nil + }, + }) +} + // PodKey returns a key unique to the given pod within a cluster. // It's used so we consistently use the same key scheme in this module. // It does exactly what cache.MetaNamespaceKeyFunc would have done @@ -113,7 +113,7 @@ type DaemonSetsController struct { historyStoreSynced cache.InformerSynced // podLister get list/get pods from the shared informers's store podLister corelisters.PodLister - // podIndexer allows looking up pods by node name. + // podIndexer allows looking up pods by node name or by ControllerRef UID podIndexer cache.Indexer // podStoreSynced returns true if the pod store has been synced at least once. // Added as a member to the struct to allow injection for testing. @@ -217,6 +217,7 @@ func NewDaemonSetsController( dsc.podLister = podInformer.Lister() dsc.podStoreSynced = podInformer.Informer().HasSynced controller.AddPodNodeNameIndexer(podInformer.Informer()) + controller.AddPodControllerUIDIndexer(podInformer.Informer()) dsc.podIndexer = podInformer.Informer().GetIndexer() nodeInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ @@ -688,6 +689,30 @@ func (dsc *DaemonSetsController) updateNode(logger klog.Logger, old, cur interfa dsc.nodeUpdateQueue.Add(curNode.Name) } +// getPodsFromCache returns the Pods that a given DS should manage. +func (dsc *DaemonSetsController) getDaemonPodsFromCache(ds *apps.DaemonSet) ([]*v1.Pod, error) { + // Iterate over two keys: + // The UID of the Daemonset, which identifies Pods that are controlled by the Daemonset. + // The OrphanPodIndexKey, which helps identify orphaned Pods that are not currently managed by any controller, + // but may be adopted later on if they have matching labels with the Daemonset. + podsForDS := []*v1.Pod{} + for _, key := range []string{string(ds.UID), controller.OrphanPodIndexKey} { + podObjs, err := dsc.podIndexer.ByIndex(controller.PodControllerUIDIndex, key) + if err != nil { + return nil, err + } + for _, obj := range podObjs { + pod, ok := obj.(*v1.Pod) + if !ok { + utilruntime.HandleError(fmt.Errorf("unexpected object type in pod indexer: %v", obj)) + continue + } + podsForDS = append(podsForDS, pod) + } + } + return podsForDS, nil +} + // getDaemonPods returns daemon pods owned by the given ds. // This also reconciles ControllerRef by adopting/orphaning. // Note that returned Pods are pointers to objects in the cache. @@ -697,10 +722,8 @@ func (dsc *DaemonSetsController) getDaemonPods(ctx context.Context, ds *apps.Dae if err != nil { return nil, err } - - // List all pods to include those that don't match the selector anymore but - // have a ControllerRef pointing to this controller. - pods, err := dsc.podLister.Pods(ds.Namespace).List(labels.Everything()) + // List all pods indexed to DS UID and Orphan pods + pods, err := dsc.getDaemonPodsFromCache(ds) if err != nil { return nil, err }
Leaderboard for this case
medium · 3 of 9 bots fully caught it (33% solve rate) · 33% avg coverage.
| # | Bot | Result | Caught | Coverage | Findings | False alarms |
|---|---|---|---|---|---|---|
| 1 | Drape (Deep Review) | solved | 1/1 | 100.0% | 2 | 0 |
| 2 | greptile | solved | 1/1 | 100.0% | 2 | 0 |
| 3 | Mjolnir (Opus 5.5) | solved | 1/1 | 100.0% | 2 | 0 |
| 4 | Cubic | miss | 0/1 | 0.0% | 1 | 0 |
| 5 | cursor | miss | 0/1 | 0.0% | 1 | 0 |
| 6 | Drape (Review) | miss | 0/1 | 0.0% | 1 | 0 |
| 7 | Mjolnir (Sonnet 5.5) | miss | 0/1 | 0.0% | 0 | 0 |
| 8 | qodo | miss | 0/1 | 0.0% | 0 | 0 |
| 9 | Claude Code (Opus 5.5) | miss | 0/1 | 0.0% | 3 | 1 |
Bot results
Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✗ | — |
The orphan lookup does return pods from every namespace, but ClaimObject skips any orphan whose namespace differs from the controller's. So no cross-namespace adoption, invalid ownerReference or GC deletion can happen, and those pods are never returned as claimed. [invalid: contradiction] [consensus 3/4: invalid=3, valid=1]
The namespace-isolation part is refuted by the namespace guard in ClaimObject. The performance part is real: each sync now goes through every orphaned pod in the cluster, where the old code listed only the DaemonSet's namespace. That cost is small and each skipped orphan is cheap. [grounded: diff] [consensus 3/4: valid=3, invalid=1]
The new call drops its error. The sync path now depends on ByIndex(PodControllerUIDIndex), so if the indexer fails to register, every sync errors. The existing node-name indexer call ignores its error the same way, which makes this unlikely to trigger in practice. [grounded: diff] [consensus 3/4: valid=3, invalid=1]
raw comments (3)
The `OrphanPodIndexKey` lookup does not filter by namespace. The indexer files every orphaned pod in the cluster under the single key `_ORPHAN_POD`. The old code limited the list with `podLister.Pods(ds.Namespace)`. Now `getDaemonPods` passes orphaned pods from every namespace to `ClaimPods`, and `ClaimPods` checks only the label selector, not the namespace. As a result, a DaemonSet in namespace A will try to adopt any orphaned pod in namespace B whose labels match its selector. It patches that pod with an ownerReference to a controller in another namespace, which is invalid. The garbage collector then treats the owner as missing and can delete the pod, so one namespace can take over or delete another namespace's pods. The pods are also counted toward the DaemonSet's per-node pods, which can cause wrong deletions or status. Fix: include the namespace in the orphan key (e.g. `_ORPHAN_POD/<namespace>`), or skip pods where `pod.Namespace != ds.Namespace`.
The indexer puts every orphaned pod in the cluster under one global key, `OrphanPodIndexKey`, with no namespace. Any controller that uses this index (here, the DaemonSet controller) receives orphans from all namespaces. That breaks namespace isolation, and in large clusters every sync scans every orphaned pod in the cluster. The key should include the namespace.
The error returned by `AddPodControllerUIDIndexer` is ignored. If adding the index fails (for example, because the shared informer has already started), `ByIndex` will fail on every sync with 'index does not exist', and the DaemonSet controller will stop working without any error at construction time. The error should be returned from `NewDaemonSetsController`.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✗ | — |
The old code listed only pods in the DaemonSet's namespace (`dsc.podLister.Pods(ds.Namespace).List`). The new index puts every orphan pod in the cluster under one non-namespaced key, `_ORPHAN_POD`, and `getDaemonPodsFromCache` does not filter by namespace. So every DaemonSet sync now fetches orphans from all namespaces and passes them to ClaimPods, which the old namespace-scoped list never did. This is a real scalability regression. [grounded: diff] [consensus 5/5: valid=5]
raw comments (2)
<!-- cubic:v=34b0a03f-bd65-46ed-b10d-6e0f2c1b83e0 -->
<!-- cubic:review-run=aae0a6e9-9047-595d-8c48-661494c40c10 -->
<!-- metadata:{"confidence":9} -->
P2: When a cluster has orphan Pods in other namespaces, every DaemonSet sync retrieves and iterates all of them because `OrphanPodIndexKey` is cluster-wide. `ClaimPods` ignores cross-namespace orphans only after this work, so keep the orphan lookup namespace-scoped or make the orphan index namespace-aware.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At pkg/controller/daemon/daemon_controller.go, line 699:
<comment>When a cluster has orphan Pods in other namespaces, every DaemonSet sync retrieves and iterates all of them because `OrphanPodIndexKey` is cluster-wide. `ClaimPods` ignores cross-namespace orphans only after this work, so keep the orphan lookup namespace-scoped or make the orphan index namespace-aware.</comment>
<file context>
@@ -688,6 +689,30 @@ func (dsc *DaemonSetsController) updateNode(logger klog.Logger, old, cur interfa
+ // The OrphanPodIndexKey, which helps identify orphaned Pods that are not currently managed by any controller,
+ // but may be adopted later on if they have matching labels with the Daemonset.
+ podsForDS := []*v1.Pod{}
+ for _, key := range []string{string(ds.UID), controller.OrphanPodIndexKey} {
+ podObjs, err := dsc.podIndexer.ByIndex(controller.PodControllerUIDIndex, key)
+ if err != nil {
</file context>
```
</details>
<!-- cubic:review-summary:start -->
**1 issue found** across 2 files
<!-- cubic:review-summary:end -->
<details>
<summary>Prompt for AI agents (unresolved issues)</summary>
```text
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="pkg/controller/daemon/daemon_controller.go">
<violation number="1" location="pkg/controller/daemon/daemon_controller.go:699">
P2: When a cluster has orphan Pods in other namespaces, every DaemonSet sync retrieves and iterates all of them because `OrphanPodIndexKey` is cluster-wide. `ClaimPods` ignores cross-namespace orphans only after this work, so keep the orphan lookup namespace-scoped or make the orphan index namespace-aware.</violation>
</file>
```
</details>
<sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/50/ai_pr_review_github_delivery_8c4464575bab4bd0c554ec50626b7bd6ecd0781a3c195e1b19db17d1ef2eb3e5?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F50)</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_8c4464575bab4bd0c554ec50626b7bd6ecd0781a3c195e1b19db17d1ef2eb3e5:b8c875154d0511e72ebf2852e99d59fcacc6eb5d:aae0a6e9-9047-595d-8c48-661494c40c10 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✗ | — |
The indexer puts every orphan pod in the cluster under one key, `_ORPHAN_POD`, with no namespace in the key. The old code called `Pods(ds.Namespace).List`, which stayed inside the DaemonSet's namespace. Now every DaemonSet sync pulls and walks all orphan pods in the cluster, which is a real performance regression introduced by this change. [grounded: tree pkg/controller/daemon/daemon_controller.go] [consensus 5/5: valid=5]
raw comments (2)
### Orphan pod index ignores namespace
**Medium Severity**
<!-- DESCRIPTION START -->
`getDaemonPodsFromCache` looks up every pod under the cluster-wide `OrphanPodIndexKey` and never filters by `ds.Namespace`. The previous `Pods(ds.Namespace).List` only scanned that namespace, so each DaemonSet sync now loads and walks all orphan pods in the cluster. `ByIndex` holds the informer read lock while copying that set, which can erase the intended speedup and add lock contention in multi-namespace clusters.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: c8f03ac9-aa5d-46eb-9e4d-3de8cb1d5e0a -->
<!-- LOCATIONS START
pkg/controller/daemon/daemon_controller.go#L698-L712
pkg/controller/controller_utils.go#L1102-L1105
pkg/controller/controller_utils.go#L89-L91
LOCATIONS END -->
<details>
<summary>Additional Locations (2)</summary>
- [`pkg/controller/controller_utils.go#L1102-L1105`](https://github.com/drape-io/crbench-cursor-2026-09/blob/80945c1eb2134a4685c3ff3d887f86460d0480af/pkg/controller/controller_utils.go#L1102-L1105)
- [`pkg/controller/controller_utils.go#L89-L91`](https://github.com/drape-io/crbench-cursor-2026-09/blob/80945c1eb2134a4685c3ff3d887f86460d0480af/pkg/controller/controller_utils.go#L89-L91)
</details>
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjJmNmQ1YWVmLWU2ZDAtNGE1Ni05MzZkLWVjZjI2NjljNTE0ZCIsImVuY3J5cHRpb25LZXkiOiI4cWxqakcyQkZhZXo4eUdqX2prX0RmM2pwVENkOXFmeFpLUlpFeHllcTRNIiwiYnJhbmNoIjoidDItazhzLTEzMDg1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjJmNmQ1YWVmLWU2ZDAtNGE1Ni05MzZkLWVjZjI2NjljNTE0ZCIsImVuY3J5cHRpb25LZXkiOiI4cWxqakcyQkZhZXo4eUdqX2prX0RmM2pwVENkOXFmeFpLUlpFeHllcTRNIiwiYnJhbmNoIjoidDItazhzLTEzMDg1OSIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJOdW1iZXIiOjkzLCJjb21taXRTaGEiOiI4MDk0NWMxZWIyMTM0YTQ2ODVjM2ZmM2Q4ODdmODY0NjBkMDQ4MGFmIiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 80945c1eb2134a4685c3ff3d887f86460d0480af. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_REVIEW -->
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
<!-- BUGBOT_FIX_ALL -->
<a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aTo4M2ZiODFhMS0wYmQzLTRiOWYtYWJmMi02ZmYxNGIxZDJhZWIiLCJlbmNyeXB0aW9uS2V5IjoiSkl5dGFMQnJrUE52bzZfQnJBS1BYOXlkUmdBMm5UMG5EZ1lFSE5ybE5mdyIsImJyYW5jaCI6InQyLWs4cy0xMzA4NTkiLCJyZXBvT3duZXIiOiJkcmFwZS1pbyIsInJlcG9OYW1lIjoiY3JiZW5jaC1jdXJzb3ItMjAyNi0wOSIsInByb3ZpZGVyIjoiZ2l0aHViIn19" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>
<!-- /BUGBOT_FIX_ALL -->
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN -->
<sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END -->
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 80945c1eb2134a4685c3ff3d887f86460d0480af. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
The removed code listed pods only in ds.Namespace. The new code puts every orphan pod in the cluster under one global key, so every sync fetches all of them and passes them to ClaimPods. ClaimObject's namespace check (controller_ref_manager.go:111) keeps the result correct, but the per-sync cost still grows with the number of orphan pods cluster-wide. That is a real performance regression. [grounded: tree pkg/controller/controller_utils.go] [consensus 3/3: valid=3]
raw comments (2)
**DaemonSet sync scans orphan pods cluster-wide**
The orphan index key isn't namespaced, so `getDaemonPodsFromCache` returns ownerless pods from every namespace. The old code listed only the DaemonSet's namespace. Sync cost now grows with the number of bare pods in the whole cluster. Put the namespace in the orphan key (namespace + "/" + OrphanPodIndexKey).
```
pkg/controller/daemon/daemon_controller.go:692 // getPodsFromCache returns the Pods that a given DS should manage.
pkg/controller/daemon/daemon_controller.go:693 func (dsc *DaemonSetsController) getDaemonPodsFromCache(ds *apps.DaemonSet) ([]*v1.Pod, error) {
pkg/controller/daemon/daemon_controller.go:694 // Iterate over two keys:
pkg/controller/daemon/daemon_controller.go:695 // The UID of the Daemonset, which identifies Pods that are controlled by the Daemonset.
pkg/controller/controller_utils.go:1103 // If the Pod has no controller (i.e., it's orphaned), index it with the OrphanPodIndexKey
pkg/controller/controller_utils.go:1104 // This helps identify orphan pods for reconciliation and adoption by controllers
pkg/controller/controller_utils.go:1105 return []string{OrphanPodIndexKey}, nil
pkg/controller/controller_ref_manager.go:102 if m.Controller.GetDeletionTimestamp() != nil || !match(obj) {
pkg/controller/controller_ref_manager.go:103 // Ignore if we're being deleted or selector doesn't match.
pkg/controller/controller_ref_manager.go:104 return false, nil
```
**DaemonSet claims pods from other namespaces**
The UID index lookup isn't limited to ds.Namespace. A pod in another namespace with an owner reference to this DS's UID gets claimed, and the DS may then delete a pod with the same name in its own namespace. In `getDaemonPodsFromCache`, skip pods outside ds.Namespace.
```
pkg/controller/daemon/daemon_controller.go:698 podsForDS := []*v1.Pod{}
pkg/controller/daemon/daemon_controller.go:699 for _, key := range []string{string(ds.UID), controller.OrphanPodIndexKey} {
pkg/controller/daemon/daemon_controller.go:700 podObjs, err := dsc.podIndexer.ByIndex(controller.PodControllerUIDIndex, key)
pkg/controller/daemon/daemon_controller.go:701 if err != nil {
pkg/controller/controller_ref_manager.go:71 if controllerRef != nil {
pkg/controller/controller_ref_manager.go:72 if controllerRef.UID != m.Controller.GetUID() {
pkg/controller/controller_ref_manager.go:73 // Owned by someone else. Ignore.
pkg/controller/controller_ref_manager.go:74 return false, nil
pkg/controller/controller_ref_manager.go:75 }
pkg/controller/controller_ref_manager.go:76 if match(obj) {
```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✗ | — |
The removed line `dsc.podLister.Pods(ds.Namespace).List(labels.Everything())` was scoped to the DaemonSet's namespace. The new orphan index key is cluster-wide and is not split by namespace, so every sync now returns orphan pods from all namespaces. ClaimObject still drops pods from other namespaces, so the result stays correct. The defect is a real performance regression that this change introduced. [grounded: diff] [consensus 3/3: valid=3]
raw comments (1)
**Orphan lookup scans pods from all namespaces**
`getDaemonPodsFromCache` fetches every orphan pod in the whole cluster via `OrphanPodIndexKey`. The old code listed only the DaemonSet's namespace. Pods from other namespaces are returned and only dropped later in `ClaimObject`. Skip orphan pods whose namespace differs from ds.Namespace in getDaemonPodsFromCache, or key the orphan index by namespace.
```
pkg/controller/daemon/daemon_controller.go:698 podsForDS := []*v1.Pod{}
pkg/controller/daemon/daemon_controller.go:699 for _, key := range []string{string(ds.UID), controller.OrphanPodIndexKey} {
pkg/controller/daemon/daemon_controller.go:700 podObjs, err := dsc.podIndexer.ByIndex(controller.PodControllerUIDIndex, key)
pkg/controller/daemon/daemon_controller.go:701 if err != nil {
pkg/controller/controller_ref_manager.go:111 if len(m.Controller.GetNamespace()) > 0 && m.Controller.GetNamespace() != obj.GetNamespace() {
pkg/controller/controller_ref_manager.go:112 // Ignore if namespace not match
pkg/controller/controller_ref_manager.go:113 return false, nil
pkg/controller/controller_ref_manager.go:114 }
```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | exact |
The indexer puts every controller-less pod in every namespace under the single `_ORPHAN_POD` key. The removed code listed only the DaemonSet's namespace via `podLister.Pods(ds.Namespace)`. Now each sync pulls in orphan pods from the whole cluster and hands them to ClaimPods. That is a real per-sync cost regression, and it also lets pods from other namespaces reach the adoption logic. [grounded: diff] [consensus 3/3: valid=3]
raw comments (3)
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> <a href="#"><img alt="security" src="https://greptile-static-assets.s3.amazonaws.com/badges/Security.svg?v=2" align="top"></a> **Cross-Namespace Pods Suppress Creation**
The UID lookup is cluster-wide, so a Pod in another namespace can set its controller owner reference to this DaemonSet's UID and, when its labels match, be claimed as an existing daemon Pod. The foreign Pod is then grouped under its node and suppresses creation of the legitimate daemon Pod there, allowing one namespace to disrupt DaemonSet coverage in another. Filter indexed results by `ds.Namespace` or include the namespace in the index keys before passing Pods to `ClaimPods`.
**How this was verified:** Kubernetes accepts owner references without validating the owner's namespace, and the claimed foreign Pod is counted as existing during per-node reconciliation.
<a href="#"><img alt="P2" src="https://greptile-static-assets.s3.amazonaws.com/badges/p2.svg?v=9" align="top"></a> **Orphan Lookup Scans Cluster**
Every DaemonSet reconciliation now retrieves the cluster-wide collection of ownerless Pods through the single `_ORPHAN_POD` index key, even though only Pods in the DaemonSet's namespace can be adopted. In clusters with many namespaces or orphan Pods, each DaemonSet repeatedly scans and checks an unrelated global set. Include the namespace in the orphan index key or otherwise use a namespace-scoped lookup.
<h3>Greptile Summary</h3>
This PR adds a shared Pod index keyed by controller UID, with a common key for ownerless Pods, and changes DaemonSet reconciliation to use that index instead of listing all Pods in the DaemonSet namespace.
- Reduces scanning of namespace Pods owned by unrelated controllers.
- Introduces a namespace-isolation flaw for Pods crafted with a DaemonSet UID from another namespace.
- Makes every DaemonSet scan the cluster-wide ownerless-Pod bucket.
<h3>Confidence Score: 3/5</h3>
This PR is not safe to merge until indexed Pod candidates are constrained to the DaemonSet's namespace.
The cluster-wide UID lookup lets a cross-namespace Pod carrying the DaemonSet UID be treated as an existing daemon Pod, suppressing legitimate workload creation; the global orphan bucket also adds avoidable cluster-wide reconciliation work.
**Files Needing Attention:** pkg/controller/daemon/daemon_controller.go, pkg/controller/controller_utils.go
<details open><summary><h3>Security Review</h3></summary>
A Pod in another namespace can spoof the DaemonSet's controller UID and matching labels, causing the DaemonSet controller to count it as present and suppress the legitimate Pod on that node.
</details>
<details><summary><h3>Important Files Changed</h3></summary>
| Filename | Overview |
|----------|----------|
| pkg/controller/controller_utils.go | Adds controller-UID and global orphan indexing; the keys omit namespace and enable both cross-namespace UID matches and a potentially large shared orphan bucket. |
| pkg/controller/daemon/daemon_controller.go | Replaces namespace-scoped Pod listing with cluster-wide indexed retrieval, allowing a foreign claimed Pod to affect node coverage and causing global orphan scans. |
</details>
<details open><summary><h3>Flowchart</h3></summary>
```mermaid
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Pod informer cache] --> B{Controller reference}
B -->|DaemonSet UID| C[UID index bucket]
B -->|No controller| D[Global orphan bucket]
C --> E[getDaemonPodsFromCache]
D --> E
E --> F[ClaimPods]
F --> G[Group claimed Pods by node]
G --> H{Claimed Pod exists on node?}
H -->|Yes| I[Suppress daemon Pod creation]
H -->|No| J[Create daemon Pod]
```
</details>
<!-- greptile_other_comments_section -->
<sub>Reviews (1): Last reviewed commit: ["Update pkg/controller/controller\_utils.g..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/d290b4742bf38b0735366a65510b09b1a63bb238) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284558)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✓ | off by one |
Every orphan pod is indexed under one global key, whatever its namespace. getDaemonPodsFromCache therefore returns orphan pods from all namespaces, where the old podLister.Pods(ds.Namespace).List call returned only pods from the DaemonSet's namespace. ClaimPods drops the pods from other namespaces, so nothing is adopted wrongly, but work per sync now grows with the number of orphan pods in the whole cluster. That is a real performance regression this change introduced. [grounded: tree pkg/controller/controller_utils.go] [consensus 3/3: valid=3]
raw comments (2)
[P2] Orphan-pod index key is cluster-wide, so each DaemonSet sync scans orphan pods in every namespace
(used at pkg/controller/daemon/daemon_controller.go:699-700) The old code used `dsc.podLister.Pods(ds.Namespace).List(...)`, which only looked at pods in the DaemonSet's namespace. The new indexer puts every pod without a controller under one global `OrphanPodIndexKey`, and `getDaemonPodsFromCache` reads that key with no namespace filter. Every bare pod in the cluster has no controller (one-off pods, debug pods, static/mirror pods without controller refs, and so on), so each DaemonSet sync now copies them all and runs `ClaimPods` on each one. Cross-namespace pods are only dropped late in `ClaimObject`, after the selector match. In clusters with many namespaces and bare pods, this can cost more than the namespace-scoped list it replaced, which undercuts the point of the change. It also means a pod in another namespace whose controllerRef UID matches the DaemonSet would now be returned as claimed, where the namespaced list previously excluded it. Putting the namespace in the orphan key (for example `OrphanPodIndexKey + "/" + pod.Namespace`) and querying with `ds.Namespace` would keep the lookup limited to that namespace.
[P2] The orphan pod index is cluster-wide, so every DaemonSet sync scans every orphan pod in the cluster.
`AddPodControllerUIDIndexer` puts every pod that has no controller under one global key, `OrphanPodIndexKey`, whatever its namespace. `getDaemonPodsFromCache` (daemon_controller.go:699) reads that key for every DaemonSet, so each sync now returns orphan pods from all namespaces. The old code only listed pods in `ds.Namespace`. `ClaimPods` then runs a selector match and a namespace check on each of those pods and drops the ones from other namespaces (controller_ref_manager.go:111), so nothing outside the namespace gets adopted. The problem is cost: the work per sync grows with the number of orphan pods in the whole cluster, not in one namespace. Bare pods without an owner are common in large clusters, so a DaemonSet in a small namespace can end up doing far more work than before, which works against the goal of this change. Including the pod namespace in the orphan index key (for example `OrphanPodIndexKey + "/" + pod.Namespace`) and looking up the key for `ds.Namespace` would keep the lookup limited to one namespace.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✗ | — |
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d1 | high | ✗ | — |
raw comments (2)
<h3>Qodo is busy working</h3>
Check back in a few minutes. Qodo's code review agents are on it.
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<img src="https://www.qodo.ai/wp-content/uploads/2026/01/anteater-looking-at-ants-01-transparent-bg-croped-ezgif.com-optimize-1.gif" width="30%">
<h3>PR Summary by Qodo</h3>
Index DaemonSet pods by controller UID for faster reconciliation
<code>✨ Enhancement</code> <code>🕐 20-40 Minutes</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<details>
<summary>AI Description</summary>
<dl>
<dd>
<br/>
><pre>
>• Index pods by controller UID, with a dedicated bucket for orphaned pods.
>• Limit DaemonSet reconciliation candidates to owned and candidate orphan pods.
>• Avoid namespace-wide pod scans during DaemonSet ownership reconciliation.
></pre>
</dd>
</dl>
</details>
<details>
<summary>Diagram</summary>
<dl>
<dd>
<br/>
```mermaid
graph TD
P["Pod informer"] --> I["UID indexer"] --> O["Owned pods"] --> L["DS cache lookup"] --> C["Claim manager"]
I --> R["Orphan pods"] --> L
```
</dd>
</dl>
</details>
<details>
<summary>High-Level Assessment</summary>
<dl>
<dd>
<br/>
>The following are alternative approaches to this PR:
<details>
<summary><b>1. Namespace-scoped orphan index keys</b></summary>
<dl>
<dd>
- ➕ Avoids scanning orphan Pods from unrelated namespaces during every DaemonSet reconciliation
- ➕ Preserves the namespace boundary of the previous Pod lister query
- ➖ Requires composite key construction for orphan lookups
- ➖ Makes the shared index contract slightly more complex
</dd>
</dl>
</details>
>**Recommendation:** Keep controller-UID indexing, but consider namespace-scoping the orphan key before merging. Controller UIDs provide efficient owned-Pod lookup, while a namespace-qualified orphan bucket avoids turning each reconciliation into a cluster-wide orphan scan.
</dd>
</dl>
</details>
<details>
<summary> Files changed (2) <code> +59 / -5 </code> </summary>
<dl>
<dd>
<br/>
<details>
<summary>Enhancement (2) <code> +59 / -5 </code></summary>
<dl>
<dd>
<details>
<summary>controller_utils.go<code>Add controller UID and orphan Pod indexing</code> <code>+31/-0</code></summary>
<br/>
>Add controller UID and orphan Pod indexing
>
><pre>
>• Defines index names for controller-owned and orphan Pods. Adds an idempotent informer indexer that stores Pods under their controller reference UID or a shared orphan sentinel.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/48/files#diff-8128d56d17ba6f10e337cf42856a93fcfaf5bce5b7efbc6d9a371bb5c04c7098'>pkg/controller/controller_utils.go</a>
</details>
<details>
<summary>daemon_controller.go<code>Use indexed Pod candidates during DaemonSet reconciliation</code> <code>+28/-5</code></summary>
<br/>
>Use indexed Pod candidates during DaemonSet reconciliation
>
><pre>
>• Registers the controller UID index on the shared Pod informer and adds a cache helper that combines Pods owned by the DaemonSet with orphan candidates. Replaces the namespace-wide Pod listing used before ownership claiming.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/48/files#diff-073530752026c269afe84022a2d452456b7f7edcc2a71c05068ee601e3e14915'>pkg/controller/daemon/daemon_controller.go</a>
</details>
</dd>
</dl>
</details>
</dd>
</dl>
</details>