Fix race condition in static validator cache#45
Open
kamilprzyb2 wants to merge 1 commit into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Fix race condition in static
ViesManager.GetValidatorcacheProblem
ViesManager.IsValid(countryCode, vatNumber)can throwArgumentException: An item with the same key has already been added. Key: <code>when called concurrently before the staticVatValidatorscache is warm.Minimal repro:
On a cold process, at least one iteration throws intermittently. I hit this in an ASP.NET service that validates VAT in request handlers — parallel integration tests surface it routinely, and any real workload that calls
IsValidfrom multiple threads before the cache is populated is exposed.Stack trace from a real failure:
Cause
VatValidatorsis aDictionary<string, IVatValidator>, which is documented as not safe for concurrent reads with writes.GetValidatordoes the classic check-then-act:Two threads can both miss
TryGetValue, both build their validator, and both callAdd— the loser throws. ConcurrentAdds with different keys can also corrupt the bucket array; the duplicate-key throw is just the louder failure mode.Fix
Swap
DictionaryforConcurrentDictionaryand useGetOrAdd(key, value). Behaviour is identical for serial callers; concurrent first-access is now safe. The unknown-country-code branch still returnsnullwithout polluting the cache.Plus
using System.Collections.Concurrent;at the top.Why not a
lock?A
lockwould serialise every cache miss.ConcurrentDictionaryis lock-free on the hit path and uses fine-grained striping for inserts — a better fit for what's effectively read-mostly state.Why not eager initialisation?
Populating all 28 validators in a static constructor would also fix the race, but pays the construction cost unconditionally at first use of the class. The lazy + concurrent approach preserves the current "only pay for what you use" behaviour.
Caveat: redundant constructions under contention
Under heavy first-access contention for the same country, two threads can both build a validator; the loser's instance is GC'd. Acceptable here because validator constructors are cheap and side-effect-free.
Tests
Added
ViesManagerConcurrencyTeststhat parallelisesIsValidover all 28 supported country codes from multiple threads. Fails reliably onmaster, passes on this branch.Caveat: because
VatValidatorsis process-static, once any other test in the same xUnit process touchesIsValid, the cache is warm and the race window is gone for that run. The new test is best-effort rather than deterministic; a fully deterministic regression check would need either reflection-based dict-clearing or a refactor to make the cache injectable. Happy to follow up with whichever you'd prefer if that's a blocker.