Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Bound chart response cache retention

pulse-triage[bot]68887f7114b3
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 20e2a943e2..af1b3b4401 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -2256,6 +2256,11 @@ the intentionally sparse public response.
13. Preserve shipped security-doc guidance in shared lifecycle setup helpers so `internal/api/configapi/config_setup_handlers.go` and adjacent install/setup runtime paths point operators at the running build's local security documentation route rather than GitHub `main` links.
14. Keep shared `internal/api/chartapi/service.go` workload-chart downsampling presentation-only: when that service caps mixed-cadence workload history into equal-time buckets for operator-facing cards, lifecycle-adjacent setup and fleet surfaces must not reuse the shaped chart samples as heartbeat, enrollment, or last-seen authority.
That same presentation-only boundary must preserve canonical millisecond timestamps when it serializes chart points, so lifecycle-adjacent first-host and fleet surfaces do not misread rounded chart samples as duplicate or restarted heartbeat evidence.
+ The chart service's shared payload cache may sweep expired query variants
+ and evict payloads at its process-local retention bounds, but cache
+ residency, eviction, or an oversized response bypassing retention must not
+ become agent connectedness, heartbeat, enrollment, or fleet freshness
+ evidence.
The same rule now applies to storage summary interaction. Shared sticky-card or row-hover focus behavior on infrastructure, workloads, and storage may reuse the canonical chart transport, but lifecycle-adjacent install, enrollment, and fleet surfaces must not treat highlighted summary series or sticky-shell state as agent freshness or setup progress.
The same rule now applies to infrastructure-summary metric filters. Shared
infrastructure and other route-owned consumers may narrow the canonical
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index cb36bacc3d..5c75b5b76f 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -926,6 +926,12 @@ organization, range, metric set, and workload scope, but that cache is
transport-only. It may amortize polling and remount cost, but it must not
change normalized response shape, bypass monitor or read-state availability
checks, merge tenants, or become the source of truth for telemetry freshness.
+Infrastructure-summary, workloads-summary, and per-workload chart payloads
+must share one bounded retention budget across query variants: no more than 64
+entries or 16 MiB of encoded payloads. Inserts must purge expired variants and
+evict the oldest retained payloads as either bound is reached; a response larger
+than the byte budget may still use in-flight singleflight deduplication but must
+not be retained after the request completes.
Router-owned unified-resource adapter construction is also transport wiring,
not an API-local health model. When `internal/api/router.go` creates default or
tenant monitor adapters, it must pass the effective monitor configuration into
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index 0b4951f038..56996a0877 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -2509,6 +2509,12 @@ remounts. The cached payloads must still be built from the canonical
store-backed/read-state sources, must remain isolated by organization and
explicit chart scope, and must not become telemetry freshness, lifecycle,
recovery, or persistence authority.
+Those summary caches and the per-workload chart cache share one process-local
+retention budget of 64 payloads and 16 MiB. Every insert sweeps expired query
+variants and evicts oldest payloads at either bound, so raw range, node,
+metric-order, or point-count variants cannot turn a short TTL into unbounded
+steady-state memory. Responses larger than the byte budget remain uncached
+after singleflight completion rather than displacing the whole cache.
Those budgets also assume Kubernetes pod history lookups hit one canonical
series key. Pod chart and history consumers must normalize bare pod IDs onto
`k8s:<cluster>:pod:<uid>` before lookup; otherwise demo and mock workloads pay
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 86766a552b..fdcdb92cbc 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -1730,6 +1730,10 @@ recovery scope, or a storage/recovery-owned secret source.
alerts context. They do not prove storage encryption, backup integrity,
repository authenticity, protection coverage, or restore readiness.
31. Keep infrastructure summary chart bucketing and short response caching presentation-only on the adjacent shared API boundary. When `internal/api/chartapi/service.go` normalizes mixed-cadence infrastructure history into equal-time summary buckets or serves a cached summary payload for repeated operator-facing summary-card requests, storage and recovery may consume the resulting visual context only; they must not reinterpret those normalized chart samples, cached timestamps, or cache hits as recovery freshness windows, backup cadence, or restore evidence.
+ Expiry sweeps, oldest-payload eviction, and byte/cardinality limits in that
+ shared chart cache are transport memory controls only. Storage and recovery
+ must not reinterpret cache residency or an oversized uncached response as
+ storage-history retention, recovery-point expiry, or backup coverage.
The same router may wire the adjacent server-owned agent command
authorization verifier, but storage/recovery must not treat an approval id,
signed command grant, or command result as restore authorization or
diff --git a/internal/api/chartapi/payload_cache.go b/internal/api/chartapi/payload_cache.go
new file mode 100644
index 0000000000..53b706f89d
--- /dev/null
+++ b/internal/api/chartapi/payload_cache.go
@@ -0,0 +1,124 @@
+package chartapi
+
+import (
+ "sync"
+ "time"
+)
+
+type cachedChartPayload struct {
+ payload []byte
+ expiresAt time.Time
+ sequence uint64
+}
+
+// boundedChartPayloadCache keeps the short-lived chart response caches from
+// retaining an unbounded set of expired query variants. Chart payloads can be
+// several MiB on large estates, so both cardinality and bytes are bounded.
+type boundedChartPayloadCache struct {
+ mu sync.Mutex
+ entries map[string]cachedChartPayload
+ maxEntries int
+ maxBytes int
+ bytes int
+ sequence uint64
+}
+
+func newBoundedChartPayloadCache(maxEntries, maxBytes int) boundedChartPayloadCache {
+ if maxEntries < 0 {
+ maxEntries = 0
+ }
+ if maxBytes < 0 {
+ maxBytes = 0
+ }
+ return boundedChartPayloadCache{
+ entries: make(map[string]cachedChartPayload, maxEntries),
+ maxEntries: maxEntries,
+ maxBytes: maxBytes,
+ }
+}
+
+func (c *boundedChartPayloadCache) get(key string, now time.Time) ([]byte, bool) {
+ if c == nil || key == "" {
+ return nil, false
+ }
+
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ entry, ok := c.entries[key]
+ if !ok {
+ return nil, false
+ }
+ if !now.Before(entry.expiresAt) {
+ c.removeLocked(key, entry)
+ return nil, false
+ }
+ return entry.payload, true
+}
+
+func (c *boundedChartPayloadCache) put(key string, payload []byte, expiresAt, now time.Time) {
+ if c == nil || key == "" || len(payload) == 0 {
+ return
+ }
+
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.entries == nil {
+ c.entries = make(map[string]cachedChartPayload, c.maxEntries)
+ }
+ c.pruneExpiredLocked(now)
+ if previous, ok := c.entries[key]; ok {
+ c.removeLocked(key, previous)
+ }
+ if c.maxEntries == 0 || c.maxBytes == 0 || len(payload) > c.maxBytes {
+ return
+ }
+
+ for len(c.entries) >= c.maxEntries || c.bytes+len(payload) > c.maxBytes {
+ if !c.removeOldestLocked() {
+ return
+ }
+ }
+ c.sequence++
+ c.entries[key] = cachedChartPayload{
+ payload: payload,
+ expiresAt: expiresAt,
+ sequence: c.sequence,
+ }
+ c.bytes += len(payload)
+}
+
+func (c *boundedChartPayloadCache) pruneExpiredLocked(now time.Time) {
+ for key, entry := range c.entries {
+ if !now.Before(entry.expiresAt) {
+ c.removeLocked(key, entry)
+ }
+ }
+}
+
+func (c *boundedChartPayloadCache) removeOldestLocked() bool {
+ var (
+ oldestKey string
+ oldestEntry cachedChartPayload
+ found bool
+ )
+ for key, entry := range c.entries {
+ if !found || entry.sequence < oldestEntry.sequence {
+ oldestKey = key
+ oldestEntry = entry
+ found = true
+ }
+ }
+ if !found {
+ return false
+ }
+ c.removeLocked(oldestKey, oldestEntry)
+ return true
+}
+
+func (c *boundedChartPayloadCache) removeLocked(key string, entry cachedChartPayload) {
+ delete(c.entries, key)
+ c.bytes -= len(entry.payload)
+ if c.bytes < 0 {
+ c.bytes = 0
+ }
+}
diff --git a/internal/api/chartapi/payload_cache_test.go b/internal/api/chartapi/payload_cache_test.go
new file mode 100644
index 0000000000..98548bad50
--- /dev/null
+++ b/internal/api/chartapi/payload_cache_test.go
@@ -0,0 +1,114 @@
+package chartapi
+
+import (
+ "bytes"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+)
+
+func TestBoundedChartPayloadCacheLimitsCardinalityAndBytes(t *testing.T) {
+ now := time.Date(2026, time.August, 30, 10, 0, 0, 0, time.UTC)
+ cache := newBoundedChartPayloadCache(2, 10)
+
+ cache.put("first", bytes.Repeat([]byte{'a'}, 6), now.Add(time.Minute), now)
+ cache.put("second", bytes.Repeat([]byte{'b'}, 4), now.Add(time.Minute), now)
+ cache.put("third", bytes.Repeat([]byte{'c'}, 6), now.Add(time.Minute), now)
+
+ if _, ok := cache.get("first", now); ok {
+ t.Fatal("oldest entry remained after the shared byte budget was exhausted")
+ }
+ if _, ok := cache.get("second", now); !ok {
+ t.Fatal("newer entry was unexpectedly evicted")
+ }
+ if _, ok := cache.get("third", now); !ok {
+ t.Fatal("new entry was not retained")
+ }
+ if got := len(cache.entries); got != 2 {
+ t.Fatalf("retained entries = %d, want 2", got)
+ }
+ if cache.bytes > cache.maxBytes {
+ t.Fatalf("retained bytes = %d, exceeds budget %d", cache.bytes, cache.maxBytes)
+ }
+}
+
+func TestBoundedChartPayloadCachePurgesExpiredVariantsOnInsert(t *testing.T) {
+ now := time.Date(2026, time.August, 30, 10, 0, 0, 0, time.UTC)
+ cache := newBoundedChartPayloadCache(4, 32)
+
+ cache.put("expired-a", []byte("aaaa"), now.Add(time.Second), now)
+ cache.put("expired-b", []byte("bbbb"), now.Add(time.Second), now)
+ later := now.Add(2 * time.Second)
+ cache.put("live", []byte("cccc"), later.Add(time.Second), later)
+
+ if got := len(cache.entries); got != 1 {
+ t.Fatalf("retained entries after expiry sweep = %d, want 1", got)
+ }
+ if cache.bytes != len("cccc") {
+ t.Fatalf("retained bytes after expiry sweep = %d, want %d", cache.bytes, len("cccc"))
+ }
+}
+
+func TestBoundedChartPayloadCacheDoesNotRetainOversizedResponse(t *testing.T) {
+ now := time.Date(2026, time.August, 30, 10, 0, 0, 0, time.UTC)
+ cache := newBoundedChartPayloadCache(4, 8)
+ cache.put("oversized", bytes.Repeat([]byte{'x'}, 9), now.Add(time.Minute), now)
+
+ if _, ok := cache.get("oversized", now); ok {
+ t.Fatal("response larger than the full cache budget was retained")
+ }
+ if len(cache.entries) != 0 || cache.bytes != 0 {
+ t.Fatalf("oversized response changed cache state: entries=%d bytes=%d", len(cache.entries), cache.bytes)
+ }
+}
+
+func TestChartRoutesShareOnePayloadRetentionBudget(t *testing.T) {
+ now := time.Date(2026, time.August, 30, 10, 0, 0, 0, time.UTC)
+ service := NewService(nil)
+ service.chartPayloads = newBoundedChartPayloadCache(2, 10)
+
+ service.cacheInfrastructureChartsPayload("infra", []byte("aaaa"), now)
+ service.cacheWorkloadsSummaryChartsPayload("summary", []byte("bbbb"), now)
+ service.chartPayloads.put(
+ workloadChartsCachePrefix+"workloads",
+ []byte("cccc"),
+ now.Add(workloadChartsCacheTTL),
+ now,
+ )
+
+ if got := len(service.chartPayloads.entries); got != 2 {
+ t.Fatalf("retained entries across chart routes = %d, want shared cap 2", got)
+ }
+ if service.chartPayloads.bytes > service.chartPayloads.maxBytes {
+ t.Fatalf("retained bytes across chart routes = %d, exceeds shared budget %d", service.chartPayloads.bytes, service.chartPayloads.maxBytes)
+ }
+ if _, ok := service.cachedInfrastructureChartsPayload("infra", now); ok {
+ t.Fatal("oldest route entry was not evicted from the shared cache")
+ }
+}
+
+func TestBoundedChartPayloadCacheStaysWithinBudgetUnderConcurrency(t *testing.T) {
+ now := time.Date(2026, time.August, 30, 10, 0, 0, 0, time.UTC)
+ cache := newBoundedChartPayloadCache(8, 4<<10)
+ payload := bytes.Repeat([]byte{'x'}, 1024)
+
+ var workers sync.WaitGroup
+ for index := range 128 {
+ workers.Add(1)
+ go func() {
+ defer workers.Done()
+ key := fmt.Sprintf("variant-%d", index)
+ cache.put(key, payload, now.Add(time.Minute), now)
+ _, _ = cache.get(key, now)
+ }()
+ }
+ workers.Wait()
+
+ if got := len(cache.entries); got > cache.maxEntries {
+ t.Fatalf("retained entries after concurrent writes = %d, exceeds cap %d", got, cache.maxEntries)
+ }
+ if cache.bytes > cache.maxBytes {
+ t.Fatalf("retained bytes after concurrent writes = %d, exceeds budget %d", cache.bytes, cache.maxBytes)
+ }
+}
diff --git a/internal/api/chartapi/service.go b/internal/api/chartapi/service.go
index df37457a72..82d65711fa 100644
--- a/internal/api/chartapi/service.go
+++ b/internal/api/chartapi/service.go
@@ -25,15 +25,17 @@ import (
const workloadChartsCacheTTL = 3 * time.Second
const summaryChartsCacheTTL = 5 * time.Second
-type cachedWorkloadChartsEntry struct {
- body []byte
- cachedAt time.Time
-}
-
-type summaryChartsCacheEntry struct {
- payload []byte
- expiresAt time.Time
-}
+const (
+ // All three chart routes share one retention budget. This stays modest for
+ // low-memory container deployments while still holding several ordinary
+ // large-estate responses.
+ chartPayloadCacheMaxEntries = 64
+ chartPayloadCacheMaxBytes = 16 << 20
+
+ infrastructureChartsCachePrefix = "infrastructure|"
+ workloadsSummaryCachePrefix = "workloads-summary|"
+ workloadChartsCachePrefix = "workload-charts|"
+)
// MonitorResolver supplies the authenticated tenant monitor selected by the
// router context. Chart computation remains entirely owned by Service.
@@ -46,17 +48,18 @@ type MonitorResolver interface {
type Service struct {
resolver MonitorResolver
- infrastructureChartsMu sync.Mutex
- infrastructureCharts map[string]summaryChartsCacheEntry
- workloadsSummaryChartsMu sync.Mutex
- workloadsSummaryCharts map[string]summaryChartsCacheEntry
+ chartPayloads boundedChartPayloadCache
workloadChartsComputeGroup singleflight.Group
- workloadChartsCacheMu sync.RWMutex
- workloadChartsCache map[string]cachedWorkloadChartsEntry
}
func NewService(resolver MonitorResolver) *Service {
- return &Service{resolver: resolver}
+ return &Service{
+ resolver: resolver,
+ chartPayloads: newBoundedChartPayloadCache(
+ chartPayloadCacheMaxEntries,
+ chartPayloadCacheMaxBytes,
+ ),
+ }
}
func (r *Service) getTenantMonitor(ctx context.Context) *monitoring.Monitor {
@@ -787,33 +790,19 @@ func (r *Service) cachedInfrastructureChartsPayload(key string, now time.Time) (
if r == nil || key == "" {
return nil, false
}
- r.infrastructureChartsMu.Lock()
- defer r.infrastructureChartsMu.Unlock()
-
- entry, ok := r.infrastructureCharts[key]
- if !ok {
- return nil, false
- }
- if !now.Before(entry.expiresAt) {
- delete(r.infrastructureCharts, key)
- return nil, false
- }
- return entry.payload, true
+ return r.chartPayloads.get(infrastructureChartsCachePrefix+key, now)
}
func (r *Service) cacheInfrastructureChartsPayload(key string, payload []byte, now time.Time) {
if r == nil || key == "" || len(payload) == 0 {
return
}
- r.infrastructureChartsMu.Lock()
- defer r.infrastructureChartsMu.Unlock()
- if r.infrastructureCharts == nil {
- r.infrastructureCharts = make(map[string]summaryChartsCacheEntry, 8)
- }
- r.infrastructureCharts[key] = summaryChartsCacheEntry{
- payload: payload,
- expiresAt: now.Add(summaryChartsCacheTTL),
- }
+ r.chartPayloads.put(
+ infrastructureChartsCachePrefix+key,
+ payload,
+ now.Add(summaryChartsCacheTTL),
+ now,
+ )
}
func targetWorkloadsSummarySeriesPoints(duration time.Duration) int {
@@ -836,33 +825,19 @@ func (r *Service) cachedWorkloadsSummaryChartsPayload(key string, now time.Time)
if r == nil || key == "" {
return nil, false
}
- r.workloadsSummaryChartsMu.Lock()
- defer r.workloadsSummaryChartsMu.Unlock()
-
- entry, ok := r.workloadsSummaryCharts[key]
- if !ok {
- return nil, false
- }
- if !now.Before(entry.expiresAt) {
- delete(r.workloadsSummaryCharts, key)
- return nil, false
- }
- return entry.payload, true
+ return r.chartPayloads.get(workloadsSummaryCachePrefix+key, now)
}
func (r *Service) cacheWorkloadsSummaryChartsPayload(key string, payload []byte, now time.Time) {
if r == nil || key == "" || len(payload) == 0 {
return
}
- r.workloadsSummaryChartsMu.Lock()
- defer r.workloadsSummaryChartsMu.Unlock()
- if r.workloadsSummaryCharts == nil {
- r.workloadsSummaryCharts = make(map[string]summaryChartsCacheEntry, 8)
- }
- r.workloadsSummaryCharts[key] = summaryChartsCacheEntry{
- payload: payload,
- expiresAt: now.Add(summaryChartsCacheTTL),
- }
+ r.chartPayloads.put(
+ workloadsSummaryCachePrefix+key,
+ payload,
+ now.Add(summaryChartsCacheTTL),
+ now,
+ )
}
func aggregateInfrastructureSummaryBucketValue(
@@ -1439,38 +1414,29 @@ func (r *Service) HandleWorkloadCharts(w http.ResponseWriter, req *http.Request)
}
cacheKey := orgID + "|" + timeRange + "|" + selectedNodeID + "|" + maxPointsRaw
- r.workloadChartsCacheMu.RLock()
- if entry, ok := r.workloadChartsCache[cacheKey]; ok && time.Since(entry.cachedAt) <= workloadChartsCacheTTL {
- body := entry.body
- r.workloadChartsCacheMu.RUnlock()
+ cacheKey = workloadChartsCachePrefix + cacheKey
+ now := time.Now()
+ if body, ok := r.chartPayloads.get(cacheKey, now); ok {
w.Header().Set("Content-Type", "application/json")
if _, err := w.Write(body); err != nil {
log.Error().Err(err).Msg("Failed to write cached workload chart data response")
}
return
}
- r.workloadChartsCacheMu.RUnlock()
v, err, _ := r.workloadChartsComputeGroup.Do(cacheKey, func() (any, error) {
// Re-check cache inside the singleflight barrier in case an earlier
// caller already populated it while we were queued.
- r.workloadChartsCacheMu.RLock()
- if entry, ok := r.workloadChartsCache[cacheKey]; ok && time.Since(entry.cachedAt) <= workloadChartsCacheTTL {
- r.workloadChartsCacheMu.RUnlock()
- return entry.body, nil
+ if body, ok := r.chartPayloads.get(cacheKey, time.Now()); ok {
+ return body, nil
}
- r.workloadChartsCacheMu.RUnlock()
body, err := r.buildWorkloadChartsResponse(req.Context(), monitor, timeRange, selectedNodeID, maxPoints, duration, inMemoryChartThreshold)
if err != nil {
return nil, err
}
- r.workloadChartsCacheMu.Lock()
- if r.workloadChartsCache == nil {
- r.workloadChartsCache = map[string]cachedWorkloadChartsEntry{}
- }
- r.workloadChartsCache[cacheKey] = cachedWorkloadChartsEntry{body: body, cachedAt: time.Now()}
- r.workloadChartsCacheMu.Unlock()
+ cachedAt := time.Now()
+ r.chartPayloads.put(cacheKey, body, cachedAt.Add(workloadChartsCacheTTL), cachedAt)
return body, nil
})
if err != nil {
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 0d59789fd1..7dd8bb1604 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -3464,6 +3464,9 @@ func TestContract_WorkloadChartMetricBudgetGuardrailsRemainCanonical(t *testing.
`workloadsSummaryChartsCacheKey`,
`cachedWorkloadsSummaryChartsPayload`,
`cacheWorkloadsSummaryChartsPayload`,
+ `chartPayloadCacheMaxEntries = 64`,
+ `chartPayloadCacheMaxBytes = 16 << 20`,
+ `chartPayloads boundedChartPayloadCache`,
`type workloadSummaryMetricBucket struct`,
}
for _, snippet := range requiredSnippets {