Skip to content

fix: fix concurrent map iteration and map write race condition#162

Closed
mayankpande88 wants to merge 1 commit into
mainfrom
ring-buf-tcp-tracking
Closed

fix: fix concurrent map iteration and map write race condition#162
mayankpande88 wants to merge 1 commit into
mainfrom
ring-buf-tcp-tracking

Conversation

@mayankpande88

Copy link
Copy Markdown
Contributor

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

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>
@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello @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 Collect() method, ensuring proper synchronization and preventing runtime panics. This change significantly improves the stability and reliability of the agent's metrics collection process.

Highlights

  • Race Condition Fix: Addresses a critical 'concurrent map iteration and map write' fatal error that caused the node agent to crash.
  • Synchronization Implementation: Introduces sync.RWMutex read locks (RLock/RUnlock) and write locks (Lock/Unlock) to protect shared map accesses within the Collect() method.
  • Protected Maps: Synchronization has been applied to activeConnections, failedConnectionAttempts, logParsers, and logSamples to ensure thread safety.
  • Snapshot Pattern for Log Parsers: Utilizes a snapshot pattern for logParsers iteration, copying the map under a read lock to avoid holding the lock during potentially slow parser operations.

🧠 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 Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Applying the same snapshot pattern to the failedConnectionAttempts loop to avoid holding a lock during a potentially blocking channel send.
  2. Refining the locking for logSamples to 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.

Comment thread containers/container.go
Comment on lines +424 to +429
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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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)
	}

Comment thread containers/container.go
Comment on lines 468 to 473
if !ok {
sample = common.TruncateUtf8(ctr.Sample, *flags.MaxLabelLength)
c.lock.Lock()
c.logSamples[ctr.Hash] = sample
c.lock.Unlock()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

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()
				}

@mayankpande88 mayankpande88 deleted the ring-buf-tcp-tracking branch May 27, 2026 07:07
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.

2 participants