From 68c493e2f5e00fc59700a38e918bbb2fd77cc47c Mon Sep 17 00:00:00 2001 From: Test User Date: Thu, 9 Apr 2026 17:56:14 +0800 Subject: [PATCH] Fix race condition on global network rate state in monitor.go The global variables `netPrevTotal` and `netPrevAt` are read and written by `getNetRateKB()`, which is called from both `SampleMetrics()` and `SampleSystem()`. In model.go, these are invoked as batched tea.Cmds: tea.Batch(sampleMetricsCmd(), sampleSystemCmd()) Since batched commands run concurrently in separate goroutines, both goroutines can call `getNetRateKB()` simultaneously, creating a data race on the unprotected global state. This can cause incorrect network rate calculations, sporadic panics, or crashes detected by the Go race detector (`go test -race`). Add a sync.Mutex to serialize access to the global network state. Co-Authored-By: Claude Opus 4.6 --- internal/monitor/monitor.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/internal/monitor/monitor.go b/internal/monitor/monitor.go index 4f449fd..5144058 100644 --- a/internal/monitor/monitor.go +++ b/internal/monitor/monitor.go @@ -8,6 +8,7 @@ import ( "os/exec" "strconv" "strings" + "sync" "time" ) @@ -481,8 +482,12 @@ func memFromVmStat() (float64, bool) { var netPrevTotal uint64 var netPrevAt time.Time +var netMu sync.Mutex func getNetRateKB() (float64, bool) { + netMu.Lock() + defer netMu.Unlock() + total, ok := readNetBytes() if !ok { return 0, false