fix: fix concurrent map iteration and map write race condition#162
fix: fix concurrent map iteration and map write race condition#162mayankpande88 wants to merge 1 commit into
Conversation
The node agent was crashing with "fatal error: concurrent map iteration and map write" because multiple goroutines were accessing shared maps without proper synchronization in the Collect() method. Fixed by adding read locks around these unprotected map accesses: 1. activeConnections iteration at line 439 2. failedConnectionAttempts iteration at line 424 3. logParsers iteration at line 453 (using snapshot pattern to avoid holding lock during slow parser operations) 4. logSamples reads and writes at lines 456-461 This resolves the crash that occurred during metrics collection when other goroutines were modifying these maps concurrently. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
Summary of ChangesHello @mayankpande88, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request resolves a critical crash in the node agent by addressing concurrent map iteration and write race conditions. The fix involves strategically applying read and write locks around shared map accesses within the Highlights
🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console. Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
There was a problem hiding this comment.
Code Review
This pull request correctly identifies and fixes several race conditions related to concurrent map access in the Collect() method by adding mutex locks. The changes for activeConnections and logParsers are well-implemented, with the latter correctly using a snapshot to minimize lock contention.
My review includes two suggestions for improvement:
- Applying the same snapshot pattern to the
failedConnectionAttemptsloop to avoid holding a lock during a potentially blocking channel send. - Refining the locking for
logSamplesto use a double-checked locking pattern, which will prevent a logical race condition and redundant work.
These changes will make the concurrency handling more robust and performant.
| c.lock.RLock() | ||
| for dst, count := range c.failedConnectionAttempts { | ||
| workload := c.ip_resolver.ResolveIP(dst.IP().String()) | ||
| ch <- counter(metrics.NetConnectionsFailed, float64(count), dst.String(), workload.Name, workload.Namespace, workload.Kind, workload.Name, workload.Namespace, workload.Kind, c.srcWorkload.Region, c.srcWorkload.Zone, workload.Region, workload.Zone, workload.Region, workload.Zone, workload.Instance) | ||
| } | ||
| c.lock.RUnlock() |
There was a problem hiding this comment.
While this change correctly adds a lock to prevent a race condition, holding a read lock for the duration of the loop can lead to lock contention, especially since the ch <- counter(...) operation can block.
A better approach is to create a snapshot of the map while holding the lock, and then iterate over the snapshot. This minimizes the time the lock is held. You've already used this "snapshot pattern" for c.logParsers in this same function.
c.lock.RLock()
failedAttemptsSnapshot := make(map[common.HostPort]int64, len(c.failedConnectionAttempts))
for dst, count := range c.failedConnectionAttempts {
failedAttemptsSnapshot[dst] = count
}
c.lock.RUnlock()
for dst, count := range failedAttemptsSnapshot {
workload := c.ip_resolver.ResolveIP(dst.IP().String())
ch <- counter(metrics.NetConnectionsFailed, float64(count), dst.String(), workload.Name, workload.Namespace, workload.Kind, workload.Name, workload.Namespace, workload.Kind, c.srcWorkload.Region, c.srcWorkload.Zone, workload.Region, workload.Zone, workload.Region, workload.Zone, workload.Instance)
}| if !ok { | ||
| sample = common.TruncateUtf8(ctr.Sample, *flags.MaxLabelLength) | ||
| c.lock.Lock() | ||
| c.logSamples[ctr.Hash] = sample | ||
| c.lock.Unlock() | ||
| } |
There was a problem hiding this comment.
This change correctly adds locking around access to c.logSamples. However, the current implementation has a logical race condition (a form of check-then-act). If two goroutines check for a sample at the same time and find it missing, both will proceed to create and write the sample to the map. This leads to redundant work and one write overwriting the other.
A more robust approach is to use a double-checked locking pattern. After acquiring the write lock, you should check again if the sample has been added by another goroutine before writing.
if !ok {
newSample := common.TruncateUtf8(ctr.Sample, *flags.MaxLabelLength)
c.lock.Lock()
// Re-check if another goroutine has created the sample in the meantime.
if s, ok2 := c.logSamples[ctr.Hash]; ok2 {
sample = s // Use the existing sample.
} else {
c.logSamples[ctr.Hash] = newSample // Create the sample.
sample = newSample
}
c.lock.Unlock()
}
The node agent was crashing with "fatal error: concurrent map iteration and map write" because multiple goroutines were accessing shared maps without proper synchronization in the Collect() method.
Fixed by adding read locks around these unprotected map accesses:
This resolves the crash that occurred during metrics collection when other goroutines were modifying these maps concurrently.
🤖 Generated with Claude Code