fix: prevent stale values in averaged stats due to json.Unmarshal reuse

When reusing slices/structs with json.Unmarshal, fields marked with
omitzero that are missing in the JSON are not reset to zero - they
retain values from previous iterations.

This caused containers without bandwidth data to inherit values from
other containers that happened to occupy the same backing array
position in previous records, resulting in inflated 10m averages.

- Set containerStats to nil instead of [:0] to force fresh allocation
- Reset tempStats each iteration in AverageSystemStats
This commit is contained in:
henrygd
2026-01-31 18:07:19 -05:00
parent 83fb67132b
commit db007176fd

View File

@@ -190,6 +190,8 @@ func (rm *RecordManager) AverageSystemStats(db dbx.Builder, records RecordIds) *
id := record.Id id := record.Id
// clear global statsRecord for reuse // clear global statsRecord for reuse
statsRecord.Stats = statsRecord.Stats[:0] statsRecord.Stats = statsRecord.Stats[:0]
// reset tempStats each iteration to avoid omitzero fields retaining stale values
*stats = system.Stats{}
queryParams["id"] = id queryParams["id"] = id
db.NewQuery("SELECT stats FROM system_stats WHERE id = {:id}").Bind(queryParams).One(&statsRecord) db.NewQuery("SELECT stats FROM system_stats WHERE id = {:id}").Bind(queryParams).One(&statsRecord)
@@ -444,9 +446,11 @@ func (rm *RecordManager) AverageContainerStats(db dbx.Builder, records RecordIds
for i := range records { for i := range records {
id := records[i].Id id := records[i].Id
// clear global statsRecord and containerStats for reuse // clear global statsRecord for reuse
statsRecord.Stats = statsRecord.Stats[:0] statsRecord.Stats = statsRecord.Stats[:0]
containerStats = containerStats[:0] // must set to nil (not [:0]) to avoid json.Unmarshal reusing backing array
// which causes omitzero fields to inherit stale values from previous iterations
containerStats = nil
queryParams["id"] = id queryParams["id"] = id
db.NewQuery("SELECT stats FROM container_stats WHERE id = {:id}").Bind(queryParams).One(&statsRecord) db.NewQuery("SELECT stats FROM container_stats WHERE id = {:id}").Bind(queryParams).One(&statsRecord)