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.

Reduce metrics rollup write amplification

rcourtmandb9747856656
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index bf19688816..d713b41695 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -48,6 +48,9 @@ All files are located in `/etc/pulse/` (Systemd) or `/data/` (Docker/Kubernetes)
Path overrides:
- `PULSE_DATA_DIR` sets the base directory for `system.json`, encrypted files, and the bootstrap token.
+- `PULSE_METRICS_DB_PATH` sets only the metrics SQLite database path. Use this
+ for tmpfs-backed metrics history without moving secrets or config off the
+ persistent data directory.
Multi-tenant layout:
- Default org uses the root data directory for backward compatibility.
diff --git a/docs/DOCKER.md b/docs/DOCKER.md
index ca3f3c3625..43c9bab5b9 100644
--- a/docs/DOCKER.md
+++ b/docs/DOCKER.md
@@ -58,11 +58,27 @@ Pulse is configured via the UI (`system.json`) with optional environment overrid
| `ALLOWED_ORIGINS` | CORS allowed origin (`*` or a single origin). Empty = same-origin only. | *(unset)* |
| `LOG_LEVEL` | Log verbosity (`debug`, `info`, `warn`, `error`) | `info` |
| `PULSE_DISABLE_DOCKER_UPDATE_ACTIONS` | Hide Docker update buttons (read-only mode) | `false` |
+| `PULSE_METRICS_DB_PATH` | Optional path for only `metrics.db`, useful with tmpfs | `/data/metrics.db` |
+| `PULSE_METRICS_ROLLUP_INTERVAL` | Metrics aggregation cadence; minimum 5 minutes | `15m` |
> **Tip**: Set `LOG_LEVEL=warn` to reduce log volume while still capturing important events.
> **Note**: API tokens are managed in the UI and stored in `api_tokens.json`.
> **Note**: Plain text values in `PULSE_AUTH_PASS` are auto-hashed on startup.
+For SSD-sensitive installs, keep `/data` persistent and put only metrics
+history on tmpfs:
+
+```yaml
+services:
+ pulse:
+ environment:
+ PULSE_METRICS_DB_PATH: /metrics-tmpfs/metrics.db
+ tmpfs:
+ - /metrics-tmpfs:size=512m,uid=1000,gid=1000,mode=0700
+```
+
+Metrics history stored this way is lost on container restart.
+
<details>
<summary><strong>Advanced: Resource Limits & Healthcheck</strong></summary>
diff --git a/docs/METRICS_HISTORY.md b/docs/METRICS_HISTORY.md
index fdb9c87882..c36d5e5f2f 100644
--- a/docs/METRICS_HISTORY.md
+++ b/docs/METRICS_HISTORY.md
@@ -24,6 +24,8 @@ Default retention values (subject to change) are:
- Minute: 24 hours
- Hourly: 7 days
- Daily: 90 days
+- Rollups: every 15 minutes by default, bounded so rollups still run well
+ before raw samples expire
## Advanced: Retention Tuning
@@ -45,6 +47,42 @@ Keys:
After changing these values, restart Pulse.
+## Advanced: Disk Write Tuning
+
+Pulse keeps metrics history on disk by default. SSD-sensitive installs can move
+only the metrics SQLite database without moving secrets or general config:
+
+```bash
+PULSE_METRICS_DB_PATH=/dev/shm/pulse/metrics.db
+```
+
+For Docker, mount a tmpfs at the selected directory and keep `/data` on a
+persistent volume:
+
+```yaml
+services:
+ pulse:
+ environment:
+ PULSE_METRICS_DB_PATH: /metrics-tmpfs/metrics.db
+ tmpfs:
+ - /metrics-tmpfs:size=512m,uid=1000,gid=1000,mode=0700
+```
+
+Using tmpfs makes metrics history ephemeral across restarts. It should not be
+used for `/data`, because `/data` also contains config, encrypted credentials,
+tokens, and other state that must remain durable.
+
+The aggregation cadence can also be lengthened when an install prefers fewer,
+larger rollup writes over more frequent smaller writes:
+
+```bash
+PULSE_METRICS_ROLLUP_INTERVAL=30m
+```
+
+Values below 5 minutes are ignored. Values longer than half of the raw-retention
+window are capped by the metrics store so raw samples are still rolled up before
+retention pruning can remove them.
+
## API Access
Pulse exposes the persistent metrics store via:
diff --git a/docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-metrics-write-amplification-2026-05-03.md b/docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-metrics-write-amplification-2026-05-03.md
new file mode 100644
index 0000000000..f4c4da69de
--- /dev/null
+++ b/docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-metrics-write-amplification-2026-05-03.md
@@ -0,0 +1,62 @@
+# Known RC Issue Closure For GA Metrics Write Amplification Record
+
+- Date: `2026-05-03`
+- Gate: `known-rc-issue-closure-for-ga`
+- Issue: `https://github.com/rcourtman/Pulse/issues/1124`
+- Linked comment: `https://github.com/rcourtman/Pulse/issues/1124#issuecomment-4275445806`
+- Result: `passed`
+
+## Context
+
+Issue `#1124` remains open after the earlier v5 fixes for agent-config reads,
+metrics retention cleanup, and WAL truncation. The linked 2026-04-19 comment
+reports Pulse `5.1.28` on current PVE inside a Debian 13 LXC with disk writes
+visible every 5 minutes and memory use around 3 to 4 GiB on a 5 GiB container.
+The attached screenshot shows periodic write spikes of roughly 10 MB, matching
+the hard-coded 5-minute metrics rollup cadence in the current metrics store.
+
+Later comments on the same issue also ask for a way to keep metrics history in
+memory or move the metrics database to a path that Docker can mount as tmpfs.
+That feedback is valid for SSD-sensitive self-hosted installs, but the canonical
+v6 fix belongs in the shared metrics persistence layer rather than in a
+deployment-specific workaround.
+
+## Disposition
+
+The v6 metrics store now reduces default rollup write amplification and exposes
+explicit operator controls:
+
+- `pkg/metrics/store.go` no longer hard-codes the background rollup ticker to 5
+ minutes. The default rollup cadence is 15 minutes, with a 5-minute lower bound
+ and an upper bound tied to half of raw retention so data is aggregated before
+ pruning can remove raw samples.
+- `PULSE_METRICS_ROLLUP_INTERVAL` lets operators choose a longer cadence when
+ they prefer fewer, larger rollup writes over fresher minute aggregates.
+- `PULSE_METRICS_DB_PATH` lets Docker/LXC installs move only `metrics.db` to a
+ tmpfs or dedicated mount while leaving `/data` or `/etc/pulse` durable for
+ config, encrypted credentials, sessions, and tokens.
+- The public metrics-history and Docker documentation now describe the tmpfs
+ tradeoff and warn that tmpfs-backed metrics history is ephemeral.
+
+This does not make durable metrics free of disk writes. Persistent history still
+requires writes for raw samples, rollups, retention, and SQLite metadata. The
+fix closes the v6 product gap raised by `#1124`: the default rollup path no
+longer forces 5-minute write spikes, and SSD-sensitive operators have a governed
+runtime path for memory-backed metrics storage without moving secrets off
+durable storage.
+
+## Proof
+
+- `go test ./pkg/metrics -count=1`
+- `go test ./internal/config -run 'TestLoad_EnvOverrides_(MetricsStorage|InvalidMetricsRollupIntervalIgnored)$' -count=1`
+- `go test ./internal/monitoring -run '^$' -count=1`
+- `go test ./internal/config -count=1`
+- `python3 scripts/release_control/status_audit.py --check`
+- `python3 scripts/release_control/contract_audit.py --check`
+
+## Outcome
+
+The metrics write-amplification path reported in `#1124` has a v6 runtime fix,
+operator-facing controls, documentation, and subsystem-contract coverage. The
+`known-rc-issue-closure-for-ga` gate remains satisfied for the current v6
+release candidate.
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 81846e1b38..4dbaaa4f70 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -4463,6 +4463,12 @@
"kind": "file",
"evidence_tier": "managed-runtime-exercise"
},
+ {
+ "repo": "pulse",
+ "path": "docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-metrics-write-amplification-2026-05-03.md",
+ "kind": "file",
+ "evidence_tier": "managed-runtime-exercise"
+ },
{
"repo": "pulse",
"path": "docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-rc3-followup-2026-05-01.md",
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 13ad0ad322..291925141b 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -435,6 +435,12 @@ The registry proof map now treats provider discovery and metrics history as
their own governed runtime surfaces instead of leaving them folded into a
generic monitoring catch-all. Changes to provider wiring, discovery helpers,
or metrics history retention must stay attached to those explicit proof routes.
+Monitor construction is the runtime handoff for metrics-store placement and
+aggregation cadence: `internal/monitoring/monitor.go` may pass the resolved
+data path, `PULSE_METRICS_DB_PATH`, and `PULSE_METRICS_ROLLUP_INTERVAL` through
+to `pkg/metrics`, but the SQLite path normalization, rollup bounds, and write
+amplification policy stay owned by the metrics store rather than by a
+monitoring-local helper.
Install-wide telemetry counts are also monitoring-owned now. Any telemetry or
reporting surface that claims installation totals must aggregate across the
provisioned tenant set through the reloadable multi-tenant monitor boundary,
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 30e064bac5..1aa93fff1c 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -581,10 +581,18 @@ rewriting `metrics.db` on SSD-backed systems. Duplicate samples for the same
resource type, resource id, metric type, timestamp, and tier must be treated as
idempotent writes against the metrics table's unique key rather than as noisy
SQLite constraint failures; for raw writes, the latest buffered value wins and
-aggregate-only min/max columns stay unset. Any future change that reduces that
-batching headroom, makes WAL checkpoints more aggressive again, or reopens
-duplicate-write failures must re-prove the metrics-store hot path with the
-owned store tests rather than assuming the earlier vacuum fixes are sufficient.
+aggregate-only min/max columns stay unset. Rollups must not be hard-coded to a
+5-minute disk-write cadence: the default cadence should favor fewer, larger
+rollup transactions, remain bounded by raw retention so data is aggregated
+before pruning, and stay overrideable for operators who deliberately trade
+freshness for lower write frequency. The runtime must also allow an explicit
+metrics database path so SSD-sensitive Docker/LXC installs can place only the
+metrics SQLite store on tmpfs while keeping secrets and general configuration on
+durable storage. Any future change that reduces that batching headroom, makes
+WAL checkpoints more aggressive again, reopens duplicate-write failures, or
+removes the metrics DB path/cadence controls must re-prove the metrics-store
+hot path with the owned store tests rather than assuming the earlier vacuum
+fixes are sufficient.
contract instead of inventing an infrastructure-local summary filter branch.
For shared line charts on that hot path, the shared sparkline primitive may
isolate the selected series inside the existing render budget, but that
diff --git a/docs/release-control/v6/internal/subsystems/security-privacy.md b/docs/release-control/v6/internal/subsystems/security-privacy.md
index 78fc0e2a16..c6992ded08 100644
--- a/docs/release-control/v6/internal/subsystems/security-privacy.md
+++ b/docs/release-control/v6/internal/subsystems/security-privacy.md
@@ -486,6 +486,12 @@ state must otherwise come from the resolved `ConfigPath` / `DataPath` owner or
the shared `PULSE_DATA_DIR` fallback. These surfaces may not probe `/etc/pulse`
or `/data` independently and silently override the configured path authority
just because those directories exist on the host.
+`PULSE_METRICS_DB_PATH` is the explicit non-secret exception for metrics
+history placement only: it may move `metrics.db` to tmpfs or a dedicated mount,
+but it must not become a second authority for `.env`, tokens, encrypted
+credentials, sessions, bootstrap state, billing state, or other security
+persistence. `internal/config/config.go` owns that env parsing so the exception
+stays visible at the shared runtime config boundary.
That same auth-env boundary must also fail closed on password normalization:
`internal/config/config.go` and `internal/config/watcher.go` may auto-hash a
plaintext `PULSE_AUTH_PASS`, but they must never preserve a raw plaintext value
diff --git a/frontend-modern/public/docs/CONFIGURATION.md b/frontend-modern/public/docs/CONFIGURATION.md
index bf19688816..d713b41695 100644
--- a/frontend-modern/public/docs/CONFIGURATION.md
+++ b/frontend-modern/public/docs/CONFIGURATION.md
@@ -48,6 +48,9 @@ All files are located in `/etc/pulse/` (Systemd) or `/data/` (Docker/Kubernetes)
Path overrides:
- `PULSE_DATA_DIR` sets the base directory for `system.json`, encrypted files, and the bootstrap token.
+- `PULSE_METRICS_DB_PATH` sets only the metrics SQLite database path. Use this
+ for tmpfs-backed metrics history without moving secrets or config off the
+ persistent data directory.
Multi-tenant layout:
- Default org uses the root data directory for backward compatibility.
diff --git a/internal/config/config.go b/internal/config/config.go
index 98234ae624..41bd36d089 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -178,10 +178,12 @@ type Config struct {
// Metrics retention settings (tiered storage)
// These control how long historical metrics are retained at each aggregation level.
- MetricsRetentionRawHours int `json:"metricsRetentionRawHours"` // Raw data (~5s intervals), default: 2 hours
- MetricsRetentionMinuteHours int `json:"metricsRetentionMinuteHours"` // Minute averages, default: 24 hours
- MetricsRetentionHourlyDays int `json:"metricsRetentionHourlyDays"` // Hourly averages, default: 7 days
- MetricsRetentionDailyDays int `json:"metricsRetentionDailyDays"` // Daily averages, default: 90 days
+ MetricsRetentionRawHours int `json:"metricsRetentionRawHours"` // Raw data (~5s intervals), default: 2 hours
+ MetricsRetentionMinuteHours int `json:"metricsRetentionMinuteHours"` // Minute averages, default: 24 hours
+ MetricsRetentionHourlyDays int `json:"metricsRetentionHourlyDays"` // Hourly averages, default: 7 days
+ MetricsRetentionDailyDays int `json:"metricsRetentionDailyDays"` // Daily averages, default: 90 days
+ MetricsDBPath string `json:"-"` // Optional env-only SQLite path override for metrics.db
+ MetricsRollupInterval time.Duration `json:"-"` // Optional env-only rollup cadence override
// Logging settings
LogLevel string `envconfig:"LOG_LEVEL" default:"info"`
@@ -701,6 +703,33 @@ func parsePollingIntervalEnv(envName string, minDuration time.Duration) (time.Du
return 0, false
}
+func parseDurationOverrideEnv(envName string, minDuration time.Duration) (time.Duration, bool) {
+ value := utils.GetenvTrim(envName)
+ if value == "" {
+ return 0, false
+ }
+
+ if dur, err := time.ParseDuration(value); err == nil {
+ if dur < minDuration {
+ log.Warn().Dur("duration", dur).Msgf("Ignoring %s below %s from environment", envName, minDuration)
+ return 0, false
+ }
+ return dur, true
+ }
+
+ if seconds, err := strconv.Atoi(value); err == nil {
+ dur := time.Duration(seconds) * time.Second
+ if dur < minDuration {
+ log.Warn().Int("seconds", seconds).Msgf("Ignoring %s below %s from environment", envName, minDuration)
+ return 0, false
+ }
+ return dur, true
+ }
+
+ log.Warn().Str("value", value).Msgf("Invalid %s value, expected duration or seconds", envName)
+ return 0, false
+}
+
// Load reads configuration from encrypted persistence files.
func Load() (*Config, error) {
return load(true)
@@ -1347,6 +1376,16 @@ func load(initLogging bool) (*Config, error) {
cfg.EnvOverrides["PULSE_METRICS_TOKEN"] = true
log.Debug().Msg("Metrics token configured from env var")
}
+ if metricsDBPath := utils.GetenvTrim("PULSE_METRICS_DB_PATH"); metricsDBPath != "" {
+ cfg.MetricsDBPath = metricsDBPath
+ cfg.EnvOverrides["PULSE_METRICS_DB_PATH"] = true
+ log.Info().Str("path", metricsDBPath).Msg("Metrics database path overridden by environment")
+ }
+ if dur, ok := parseDurationOverrideEnv("PULSE_METRICS_ROLLUP_INTERVAL", 5*time.Minute); ok {
+ cfg.MetricsRollupInterval = dur
+ cfg.EnvOverrides["PULSE_METRICS_ROLLUP_INTERVAL"] = true
+ log.Info().Dur("interval", dur).Msg("Metrics rollup interval overridden by environment")
+ }
// Support PULSE_AGENT_URL as an alias for PULSE_AGENT_CONNECT_URL
// (Check this first so standard PULSE_AGENT_CONNECT_URL takes precedence if both set)
diff --git a/internal/config/config_load_test.go b/internal/config/config_load_test.go
index 3f42e59fa3..2646b2b7c8 100644
--- a/internal/config/config_load_test.go
+++ b/internal/config/config_load_test.go
@@ -85,6 +85,31 @@ func TestLoad_EnvOverrides(t *testing.T) {
assert.Equal(t, "admin", cfg.AuthUser)
}
+func TestLoad_MetricsStorageEnvOverrides(t *testing.T) {
+ t.Setenv("PULSE_DATA_DIR", t.TempDir())
+ t.Setenv("PULSE_METRICS_DB_PATH", "/dev/shm/pulse/metrics.db")
+ t.Setenv("PULSE_METRICS_ROLLUP_INTERVAL", "30m")
+
+ cfg, err := Load()
+ require.NoError(t, err)
+
+ assert.Equal(t, "/dev/shm/pulse/metrics.db", cfg.MetricsDBPath)
+ assert.Equal(t, 30*time.Minute, cfg.MetricsRollupInterval)
+ assert.True(t, cfg.EnvOverrides["PULSE_METRICS_DB_PATH"])
+ assert.True(t, cfg.EnvOverrides["PULSE_METRICS_ROLLUP_INTERVAL"])
+}
+
+func TestLoad_InvalidMetricsRollupIntervalIgnored(t *testing.T) {
+ t.Setenv("PULSE_DATA_DIR", t.TempDir())
+ t.Setenv("PULSE_METRICS_ROLLUP_INTERVAL", "2m")
+
+ cfg, err := Load()
+ require.NoError(t, err)
+
+ assert.Zero(t, cfg.MetricsRollupInterval)
+ assert.False(t, cfg.EnvOverrides["PULSE_METRICS_ROLLUP_INTERVAL"])
+}
+
func TestLoad_DotEnv(t *testing.T) {
tempDir := t.TempDir()
envFile := filepath.Join(tempDir, ".env")
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index a9059d3b30..32c1288e8d 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -91,6 +91,26 @@ func TestGetStateRefreshesLiveAlertSnapshots(t *testing.T) {
}
}
+func TestMetricsStoreRuntimeOverridesStayOnMonitorBoundary(t *testing.T) {
+ data, err := os.ReadFile("monitor.go")
+ if err != nil {
+ t.Fatalf("failed to read monitor.go: %v", err)
+ }
+ source := string(data)
+
+ for _, snippet := range []string{
+ "metricsStoreConfig := metrics.DefaultConfig(cfg.DataPath)",
+ "if strings.TrimSpace(cfg.MetricsDBPath) != \"\" {",
+ "metricsStoreConfig.DBPath = cfg.MetricsDBPath",
+ "if cfg.MetricsRollupInterval > 0 {",
+ "metricsStoreConfig.RollupInterval = cfg.MetricsRollupInterval",
+ } {
+ if !strings.Contains(source, snippet) {
+ t.Fatalf("monitor.go must contain %q", snippet)
+ }
+ }
+}
+
func TestEscalationDeliveryDefersToCanonicalAlertSuppression(t *testing.T) {
requiredSnippets := map[string][]string{
"monitor.go": {
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index af0fa014ee..ed22c6dd61 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -1402,6 +1402,12 @@ func New(cfg *config.Config) (*Monitor, error) {
// Initialize persistent metrics store (SQLite) with configurable retention
var metricsStore *metrics.Store
metricsStoreConfig := metrics.DefaultConfig(cfg.DataPath)
+ if strings.TrimSpace(cfg.MetricsDBPath) != "" {
+ metricsStoreConfig.DBPath = cfg.MetricsDBPath
+ }
+ if cfg.MetricsRollupInterval > 0 {
+ metricsStoreConfig.RollupInterval = cfg.MetricsRollupInterval
+ }
// Override retention settings from config (allows tier-based pricing in future)
if cfg.MetricsRetentionRawHours > 0 {
metricsStoreConfig.RetentionRaw = time.Duration(cfg.MetricsRetentionRawHours) * time.Hour
diff --git a/pkg/metrics/store.go b/pkg/metrics/store.go
index 9d63de2199..cfa0593b10 100644
--- a/pkg/metrics/store.go
+++ b/pkg/metrics/store.go
@@ -44,12 +44,18 @@ type StoreConfig struct {
DBPath string
WriteBufferSize int // Number of records to buffer before batch write
FlushInterval time.Duration // Max time between flushes
+ RollupInterval time.Duration // How often to aggregate raw samples into coarser tiers
RetentionRaw time.Duration // How long to keep raw data
RetentionMinute time.Duration // How long to keep minute data
RetentionHourly time.Duration // How long to keep hourly data
RetentionDaily time.Duration // How long to keep daily data
}
+const (
+ minRollupInterval = 5 * time.Minute
+ defaultRollupInterval = 15 * time.Minute
+)
+
// DefaultConfig returns sensible defaults for metrics storage
func DefaultConfig(dataDir string) StoreConfig {
dbPath := filepath.Join(dataDir, "metrics.db")
@@ -64,6 +70,7 @@ func DefaultConfig(dataDir string) StoreConfig {
// more often, which materially reduces WAL churn on SSD-backed setups.
WriteBufferSize: 500,
FlushInterval: 5 * time.Second,
+ RollupInterval: defaultRollupInterval,
RetentionRaw: 2 * time.Hour,
RetentionMinute: 24 * time.Hour,
RetentionHourly: 7 * 24 * time.Hour,
@@ -91,6 +98,27 @@ func resolveStoreDBPath(dbPath string) (string, error) {
return resolvedPath, nil
}
+func normalizeRollupInterval(interval, rawRetention time.Duration) time.Duration {
+ if interval <= 0 {
+ interval = defaultRollupInterval
+ }
+ if interval < minRollupInterval {
+ interval = minRollupInterval
+ }
+ if rawRetention <= 0 {
+ return interval
+ }
+
+ maxInterval := rawRetention / 2
+ if maxInterval < minRollupInterval {
+ maxInterval = minRollupInterval
+ }
+ if interval > maxInterval {
+ return maxInterval
+ }
+ return interval
+}
+
// bufferedMetric holds a metric waiting to be written
type bufferedMetric struct {
resourceType string
@@ -143,6 +171,7 @@ func NewStore(config StoreConfig) (*Store, error) {
return nil, err
}
config.DBPath = resolvedDBPath
+ config.RollupInterval = normalizeRollupInterval(config.RollupInterval, config.RetentionRaw)
// Ensure directory exists
dir := filepath.Dir(config.DBPath)
@@ -198,6 +227,7 @@ func NewStore(config StoreConfig) (*Store, error) {
log.Info().
Str("path", config.DBPath).
Int("bufferSize", config.WriteBufferSize).
+ Dur("rollupInterval", config.RollupInterval).
Msg("Metrics store initialized")
return store, nil
@@ -1301,7 +1331,7 @@ func (s *Store) backgroundWorker() {
defer close(s.doneCh)
flushTicker := time.NewTicker(s.config.FlushInterval)
- rollupTicker := time.NewTicker(5 * time.Minute)
+ rollupTicker := time.NewTicker(s.config.RollupInterval)
retentionTicker := time.NewTicker(1 * time.Hour)
defer flushTicker.Stop()
diff --git a/pkg/metrics/store_additional_test.go b/pkg/metrics/store_additional_test.go
index e48ffc8796..1fe7e8cba9 100644
--- a/pkg/metrics/store_additional_test.go
+++ b/pkg/metrics/store_additional_test.go
@@ -17,6 +17,63 @@ func TestDefaultConfigUsesLargerWriteBuffer(t *testing.T) {
if cfg.WriteBufferSize != 500 {
t.Fatalf("WriteBufferSize = %d, want 500", cfg.WriteBufferSize)
}
+ if cfg.RollupInterval != defaultRollupInterval {
+ t.Fatalf("RollupInterval = %v, want %v", cfg.RollupInterval, defaultRollupInterval)
+ }
+}
+
+func TestNormalizeRollupInterval(t *testing.T) {
+ tests := []struct {
+ name string
+ interval time.Duration
+ rawRetention time.Duration
+ want time.Duration
+ }{
+ {
+ name: "default",
+ interval: 0,
+ rawRetention: 2 * time.Hour,
+ want: defaultRollupInterval,
+ },
+ {
+ name: "minimum",
+ interval: time.Minute,
+ rawRetention: 2 * time.Hour,
+ want: minRollupInterval,
+ },
+ {
+ name: "configured",
+ interval: 30 * time.Minute,
+ rawRetention: 2 * time.Hour,
+ want: 30 * time.Minute,
+ },
+ {
+ name: "bounded by raw retention",
+ interval: 3 * time.Hour,
+ rawRetention: 2 * time.Hour,
+ want: time.Hour,
+ },
+ {
+ name: "no raw retention bound",
+ interval: 2 * time.Hour,
+ rawRetention: 0,
+ want: 2 * time.Hour,
+ },
+ {
+ name: "short raw retention still honors minimum",
+ interval: 20 * time.Minute,
+ rawRetention: 6 * time.Minute,
+ want: minRollupInterval,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := normalizeRollupInterval(tt.interval, tt.rawRetention); got != tt.want {
+ t.Fatalf("normalizeRollupInterval(%v, %v) = %v, want %v", tt.interval, tt.rawRetention, got, tt.want)
+ }
+ })
+ }
}
func TestStoreCoalesceQueuedBatches(t *testing.T) {