mbdavid / LiteDB

LiteDB - A .NET NoSQL Document Store in a single data file
http://www.litedb.org
MIT License
8.62k stars 1.25k forks source link

[BUG] Race condition in BsonMapper #2536

Closed einarmo closed 5 days ago

einarmo commented 2 months ago

Version LiteDB 5.0.21 .NET 8.0.401 Linux (Fedora 38)

Describe the bug Specifically, what I see is an occasional stacktrace:

System.NotSupportedException : Member Id not found on BsonMapper for type MyNamespace.MyType
 Stack Trace:
at LiteDB.LinqExpressionVisitor.ResolveMember(MemberInfo member)
at LiteDB.LinqExpressionVisitor.VisitMember(MemberExpression node)
at LiteDB.LinqExpressionVisitor.ResolvePattern(String pattern, Expression obj, IList`1 args)
at LiteDB.LinqExpressionVisitor.VisitMethodCall(MethodCallExpression node)
at System.Linq.Expressions.ExpressionVisitor.VisitLambda[T](Expression`1 node)
at LiteDB.LinqExpressionVisitor.VisitLambda[T](Expression`1 node)
at LiteDB.LinqExpressionVisitor.Resolve(Boolean predicate)
at LiteDB.BsonMapper.GetExpression[T,K](Expression`1 predicate)
at LiteDB.LiteCollection`1.DeleteMany(Expression`1 predicate)

when running an expression like

collection.DeleteMany(item => idsToDelete.Contains(item.Id))

Code to Reproduce I cannot reproduce this consistently, it only happens once in a while, likely while I am running multiple concurrent transactions not against the same collection, but using the same types.

I believe this is a race condition caused by #2493, here's the possible race I see that this PR introduced:

This code has existed for a long time, and this issue only started after updating to the latest version, which contains this fix. There may be a different cause, though my trace above seems plausible.

JKamsker commented 2 months ago

Oh i see it now. Thats pretty bad, i am sorry for that. Would you mind pr'ing a fix?

einarmo commented 2 months ago

I made a PR with a simple fix, though I'm not sure it is the best solution, since it will come with a performance cost that I think the original author of this code wanted to avoid.

JKamsker commented 2 months ago

Performance < Stability

JKamsker commented 2 months ago

Hey @einarmo can you have a look at my pr and if it solves your issue? My solution doesnt require locking all the time and should still be safe from race conditions