← Back to Pull requests

perf(helm): reduce retained heap in release informer caches #60105

Closed
unknown closed this pull request without merging on Nov 19, 2026 04:58 UTC
View on GitHub
unknown unknown commented on Nov 10, 2026 15:45 UTC
Author

What does this PR do?

Cache compact Helm release summaries and computed tags instead of full ConfigMaps and Secrets. Update and deletion handlers use the summaries, including tombstones and custom value tags.

Functional changes

| Before | After |
| --- | --- |
| The Helm check retains encoded release payloads for every observed revision alongside its decoded summaries. | Both stores keep compact release summaries and computed tags; the full encoded payloads are released. |

Metrics, service checks, events, and Helm values mapped to tags keep their existing behavior.

Motivation

Helm release records can be large and accumulate across revisions. The check only needs metadata and computed tags after decoding them.

Describe how you validated your changes

The package tests and temporary heap regression test passed three times. The benchmark source is preserved in the dropdown below and omitted from the PR diff. Focused Go lint, Gazelle, buildifier, release-note checks, and pre-commit hooks passed. Median retained heap across three benchmark repetitions on macOS arm64:

| Storage | Values as tags | Before (100 revisions) | After (100 revisions) | Reduction |
| --- | --- | --- | --- | --- |
| configmap | false | 14,123,128 B | 131,344 B | 99.07% |
| configmap | true | 14,125,920 B | 133,792 B | 99.05% |
| secret | false | 14,133,024 B | 131,360 B | 99.07% |
| secret | true | 14,135,536 B | 133,808 B | 99.05% |

<details>
<summary>Temporary heap benchmark source and reproduction</summary>

Temporarily save the source below as pkg/collector/corechecks/cluster/helm/cache_memory_test.go, then regenerate the local build target and run:

bazel run //:gazelle -- pkg/collector/corechecks/cluster/helm
bazel test //pkg/collector/corechecks/cluster/helm:helm_test_dca \
  --test_arg=-test.run=^$ \
  --test_arg=-test.bench=BenchmarkHelmCacheLiveHeap \
  --test_arg=-test.benchtime=1x --test_arg=-test.count=3 \
  --test_output=all

The synthetic fixture has 100 revisions (10 releases with 10 revisions each), each containing a 128 KiB manifest and 32 KiB of values. Both cases populate the same client-go indexer and real Helm release store. The before case retains full API objects; the after case retains the compact objects. Source fixture storage is excluded from the heap delta, and both caches are kept alive through two post-population GCs. These results measure retained Go heap, not RSS or production savings; timing includes GC and is not a decoder throughput comparison.

// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2026-present Datadog, Inc.

//go:build kubeapiserver

package helm

import (
	"bytes"
	"compress/gzip"
	"encoding/json"
	"fmt"
	"math/rand"
	"runtime"
	"strconv"
	"testing"

	"github.com/stretchr/testify/require"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/tools/cache"
)

func TestHelmCacheLiveHeap(t *testing.T) {
	// Do not run in parallel: HeapAlloc measures the entire process. Large
	// payloads make the expected difference much larger than runtime noise.
	for _, storage := range []helmStorage{k8sConfigmaps, k8sSecrets} {
		t.Run(string(storage), func(t *testing.T) {
			fixtures := helmCacheMemoryFixtures(t, storage, 20)
			for _, valuesAsTags := range []bool{false, true} {
				t.Run(fmt.Sprintf("values_as_tags=%t", valuesAsTags), func(t *testing.T) {
					before := helmCacheLiveHeap(t, fixtures, storage, false, valuesAsTags)
					after := helmCacheLiveHeap(t, fixtures, storage, true, valuesAsTags)
					t.Logf("%d revisions: before=%d live bytes, after=%d live bytes, reduction=%.2f%%",
						len(fixtures), before, after, 100*(1-float64(after)/float64(before)))
					require.Positive(t, after)
					require.Less(t, after, before/2, "compact caches should release the large payloads")
				})
			}
		})
	}
}

// BenchmarkHelmCacheLiveHeap compares steady-state heap retention, not allocation
// volume. Both cases populate the real client-go indexer and Helm release store.
// "before" retains the full API objects, as the informer did before the change;
// "after" retains transformRelease's compact objects. The release store has the
// same summaries and tags in both cases. This is a synthetic cache comparison,
// not a benchmark of the old decoder's CPU cost or an end-to-end informer run.
//
// Run with -test.run=^$ -test.bench=BenchmarkHelmCacheLiveHeap
// -test.benchtime=1x -test.count=3. Compare live-B/cache and live-B/revision;
// ns/op includes forced GC and is not a throughput measurement.
func BenchmarkHelmCacheLiveHeap(b *testing.B) {
	for _, storage := range []helmStorage{k8sConfigmaps, k8sSecrets} {
		fixtures := helmCacheMemoryFixtures(b, storage, 100)
		for _, valuesAsTags := range []bool{false, true} {
			for _, compact := range []bool{false, true} {
				mode := "before"
				if compact {
					mode = "after"
				}
				b.Run(fmt.Sprintf("%s/values_as_tags=%t/%s", storage, valuesAsTags, mode), func(b *testing.B) {
					var liveBytes int64
					for i := 0; i < b.N; i++ {
						liveBytes += helmCacheLiveHeap(b, fixtures, storage, compact, valuesAsTags)
					}
					perCache := float64(liveBytes) / float64(b.N)
					b.ReportMetric(perCache, "live-B/cache")
					b.ReportMetric(perCache/float64(len(fixtures)), "live-B/revision")
				})
			}
		}
	}
}

func helmCacheLiveHeap(tb testing.TB, fixtures [][]byte, storage helmStorage, compact, valuesAsTags bool) int64 {
	tb.Helper()
	check := newCheck().(*HelmCheck)
	if valuesAsTags {
		check.instance.HelmValuesAsTags = map[string]string{"option": "option_value"}
	}
	indexer := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc})
	var before, after runtime.MemStats
	// A second collection also clears pools that can temporarily retain buffers.
	runtime.GC()
	runtime.GC()
	runtime.ReadMemStats(&before)
	populateHelmMemoryCache(tb, fixtures, storage, compact, check, indexer)
	runtime.GC()
	runtime.GC()
	runtime.ReadMemStats(&after)
	// Keep the cache, summary store, and source fixtures alive through the sample.
	// In particular, fixture storage must not disappear between measurements.
	runtime.KeepAlive(indexer)
	runtime.KeepAlive(check)
	runtime.KeepAlive(fixtures)
	return int64(after.HeapAlloc) - int64(before.HeapAlloc)
}

func populateHelmMemoryCache(tb testing.TB, fixtures [][]byte, storage helmStorage, compact bool, check *HelmCheck, indexer cache.Indexer) {
	tb.Helper()
	for _, wire := range fixtures {
		var obj interface{}
		if storage == k8sConfigmaps {
			cm := &v1.ConfigMap{}
			require.NoError(tb, cm.Unmarshal(wire))
			obj = cm
		} else {
			secret := &v1.Secret{}
			require.NoError(tb, secret.Unmarshal(wire))
			obj = secret
		}
		summary, err := check.transformRelease(obj)
		require.NoError(tb, err)
		require.NotNil(tb, summary.(*cachedRelease).taggedRelease)
		check.addRelease(summary)
		if compact {
			obj = summary
		}
		require.NoError(tb, indexer.Add(obj))
	}
	require.Len(tb, indexer.List(), len(fixtures))
	require.Len(tb, check.store.getAll(storage), len(fixtures))
	// Return before collecting so temporary references to raw API objects and
	// decoded values cannot contribute to the retained-heap measurement.
}

func helmCacheMemoryFixtures(tb testing.TB, storage helmStorage, count int) [][]byte {
	tb.Helper()
	// Deterministic, poorly compressible data avoids unrealistically tiny gzip
	// payloads. Each revision carries a 128 KiB manifest and 32 KiB of values.
	rng := rand.New(rand.NewSource(1))
	payload := make([]byte, 160*1024)
	for i := range payload {
		payload[i] = 'a' + byte(rng.Intn(26))
	}
	fixtures := make([][]byte, count)
	for i := range fixtures {
		rel := release{
			Name: fmt.Sprintf("app-%d", i/10), Namespace: "default", Version: i%10 + 1,
			Info:   &info{Status: "deployed"},
			Config: map[string]interface{}{"option": "override", "unused": string(payload[:32*1024])},
			Chart: &chart{
				Metadata: &metadata{Name: "chart", Version: "1.0.0", AppVersion: "1.0.0"},
				Values:   map[string]interface{}{"option": "default"},
			},
		}
		data, err := json.Marshal(struct {
			release
			Manifest string `json:"manifest"`
		}{rel, string(payload[32*1024:])})
		require.NoError(tb, err)
		var compressed bytes.Buffer
		writer := gzip.NewWriter(&compressed)
		_, err = writer.Write(data)
		require.NoError(tb, err)
		require.NoError(tb, writer.Close())
		encoded := b64.EncodeToString(compressed.Bytes())
		metadata := metav1.ObjectMeta{
			Name: fmt.Sprintf("sh.helm.release.v1.%s.v%d", rel.Name, rel.Version), Namespace: rel.Namespace,
			ResourceVersion: strconv.Itoa(i + 1), Labels: map[string]string{"owner": "helm"},
		}
		if storage == k8sConfigmaps {
			fixtures[i], err = (&v1.ConfigMap{ObjectMeta: metadata, Data: map[string]string{"release": encoded}}).Marshal()
		} else {
			fixtures[i], err = (&v1.Secret{ObjectMeta: metadata, Data: map[string][]byte{"release": []byte(encoded)}}).Marshal()
		}
		require.NoError(tb, err)
	}
	return fixtures
}

</details>

Typed Kubernetes API unmarshalling still happens before the transform.

Diff: 650 lines (+487 / -163) across 8 files Reviewer: Mathew-Estafanous Review duration: 12312m
All Vouch review confidence checks passed
Residual risk 0.30 = Change Risk (0.75) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.75 · 650 lines diff across 8 files
0.75
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
0.17
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
60%
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.388
Shallow Review Depth shallow_review_depth
0.289
Sensitive Paths sensitive_paths
0.075
Real PR Conversation Timeline
1 comments
"Review active on #60105"
general weight: 0.35
Assignees
Unassigned
Labels
risk: low confidence: 60.5% reviewed sensitive_module
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: 75.2% (HIGH) · Higher = larger blast radius
75.2%
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: 60.5% · Lower = rushed or shallow review
60.5%
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: 29.7% · Safe to merge
29.7%