Fix race condition in PrometheusSink during concurrent metric updates #191
      
        
          +171
        
        
          −136
        
        
          
        
      
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Description
The
PrometheusSinkhad a race condition when multiple goroutines concurrently created the same metric for the first time. Each goroutine would create its own separate Prometheus counter/gauge/summary instance, increment it, and then store it using Store(). The last write would win, but all other metric instances with their accumulated values would be lost.This fix uses
LoadOrStore()instead ofStore()to ensure only one metric instance exists per key, then updates that single instance regardless of which goroutine won the creation race.Related Issue
N/A (discovered during testing/usage)
How Has This Been Tested?
TestPrometheusRaceConditionwhich spawns multiple goroutines that concurrently increment the same counter and verifies the final value matches the expected totalBefore the fix:
With this fix applied the test always passes