perf(partitionstore): redundant runtime.DeepCopyJSON in DiskStore.Put causes severe GC churn and heap spikes in large cluster scans
Summary
In core/pkg/resourcehandler/partitionstore, DiskStore.Put unconditionally performs a recursive runtime.DeepCopyJSON on every single Kubernetes resource before serializing it to disk.
Because DiskStore immediately streams the serialized bytes to disk via json.Marshal(rec) and never retains or mutates the Go map in memory, this deep copy is completely redundant. For medium-to-large clusters, this creates millions of short-lived heap allocations, leading to heavy Go runtime Garbage Collector (GC) pressure, scanning latency, and unnecessary memory spikes.
Real-World Production Problem & Impact
OOMKilled in Resource-Constrained Environments (CI/CD & Kubernetes Jobs):
- When Kubescape runs inside CI/CD runners or as a Kubernetes CronJob/CLI with strict container memory limits (e.g.,
resources.limits.memory: 512Mior1Gi), memory predictability is vital. - In enterprise clusters containing 10,000 to 50,000 workloads, deep copying every complex manifest (10KB–50KB per Deployment/Pod with extensive annotations and spec definitions) temporarily inflates the Go heap by hundreds of megabytes before the GC can reclaim them. This heap volatility increases the probability of container OOMKilled (Exit Code 137).
- When Kubescape runs inside CI/CD runners or as a Kubernetes CronJob/CLI with strict container memory limits (e.g.,
Garbage Collection (GC) Thrashing & CPU Steal:
runtime.DeepCopyJSONrecursively traverses every nested map and slice, generating thousands of small heap allocations per manifest.- Immediately after
json.Marshal(rec)completes, these newly allocated maps are thrown away as garbage. - This forces the Go GC into frequent mark-and-sweep cycles and CPU-intensive stop-the-world pauses, slowing down cluster resource collection times significantly.
Contradicts the Purpose of
partitionstore:- The partition spill store engine (introduced in #3818) was specifically built to bound streaming collector memory usage by offloading resources to disk. Allocating full deep copies on the heap during the disk-spill phase defeats the core optimization goal of the disk store.
Root Cause Analysis
In core/pkg/resourcehandler/partitionstore/record.go:
func newRecord(gvr string, namespace string, obj workloadinterface.IMetadata) record {
return record{
ID: obj.GetID(),
GVR: gvr,
Namespace: namespace,
Object: runtime.DeepCopyJSON(obj.GetObject()), // <-- Unconditional recursive deep copy
}
}Source: kubescape/kubescape