Skip to content

Fix deserializer cache race - #2219

Open
jnm2 wants to merge 4 commits into
DapperLib:mainfrom
jnm2:fix_deserializer_cache_race
Open

Fix deserializer cache race#2219
jnm2 wants to merge 4 commits into
DapperLib:mainfrom
jnm2:fix_deserializer_cache_race

Conversation

@jnm2

@jnm2 jnm2 commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Fixes #2117. Analysis at #2117 (comment)

Likely fixes #1896.

jnm2 added 4 commits August 6, 2026 21:34
One SQL string, one connection string and one parameter type resolve to a single Identity, so every caller shares one CacheInfo slot. Only the value of @mode changes the result shape - the same thing a branching stored procedure does in production.

CacheInfo.Deserializer holds a multi-field struct published by a plain field write, so a reader can observe a Hash from one shape paired with the Func compiled for another shape. The guard then passes and the wrong deserializer runs, throwing InvalidCastException or silently returning wrong values.

One test per site that reads the cached deserializer. All eight fail on this commit.
DeserializerState was a struct with an int Hash and a Func reference, assigned into CacheInfo.Deserializer by a plain property write. A struct that size is never written or read atomically, so concurrent callers could pair a Hash from one result shape with the Func compiled for another. The Hash then matched the reader in hand, the guard passed, and the wrong deserializer ran.

Making it a sealed class turns publication into one reference store, which is atomic. Writes only happen on a guard miss, so reads get cheaper: one load instead of two.
Making DeserializerState a reference type fixed tearing within the primary deserializer, but multi-map kept its rest-set in a second CacheInfo field. Two fields cannot be assigned together, and the gap between the two writes spans a GenerateDeserializers call and a Skip(1).ToArray(), so a reader could easily take one shape's Deserializer and another shape's OtherDeserializers. The Hash matched, the guard passed, and the mapper ran a rest-set built for a different result shape.

Folding it into DeserializerState makes the whole set move under the single reference write, and removes a field.

The two new tests fail without this change: 15721 and 9752 corrupt reads respectively, versus a handful for the single-type paths - the window here is far wider.
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.

Possible concurrency issues with caches? System.IndexOutOfRangeException inside GetDapperRowDeserializer method

1 participant