Skip to content

Fix race condition on global network rate state#3

Open
hobostay wants to merge 1 commit intosumant1122:mainfrom
hobostay:fix/net-rate-race-condition
Open

Fix race condition on global network rate state#3
hobostay wants to merge 1 commit intosumant1122:mainfrom
hobostay:fix/net-rate-race-condition

Conversation

@hobostay
Copy link
Copy Markdown

@hobostay hobostay commented Apr 9, 2026

Summary

Fixes a data race on the global variables netPrevTotal and netPrevAt in internal/monitor/monitor.go.

Bug

getNetRateKB() reads and writes two package-level variables without synchronization:

var netPrevTotal uint64
var netPrevAt time.Time

This function is called from both SampleMetrics() and getNetSummary()SampleSystem(). In model.go, these are dispatched as batched tea.Cmds:

tea.Batch(sampleMetricsCmd(), sampleSystemCmd())

Batched commands in Bubble Tea execute concurrently in separate goroutines, so both goroutines can call getNetRateKB() at the same time, creating a data race on the unprotected globals.

This can cause:

  • Incorrect network rate calculations
  • Sporadic panics
  • Failures detected by go test -race

Fix

Add a sync.Mutex to serialize access to the global network state in getNetRateKB().

How to verify

# Run with race detector (before fix, this will report a race)
go test -race ./...

🤖 Generated with Claude Code

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 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant