🌐 US-Proxy
class="logged-out env-production page-responsive" style="word-wrap: break-word;" >
Skip to content

Multi-threading issue on server side. #238

Closed

Description

@Thorium

I'm running on this issue when I have a web-server that uses SQLProvider and there are multiple requests at the same time (from different users, or from async JavaScript). e.g.:

  • User A calls let e = query { for m in dbContext.MyTable do where (m.Id = "A") select (m) }
  • User B calls let e = query { for m in dbContext.MyTable do where (m.Id = "B") select (m) }
  • User A continues with e.SetColumn("mycol", 1) and dbContext.SubmitUpdates()
  • User B continues with e.SetColumn("mycol", 2) and dbContext.SubmitUpdates()

Crash Unchanged entity encountered in update list - this should not be possible!

The problem is basically the same as #173 but how should I do a good workaround?
These users are not touching the same rows in the database.

Activity

  1. pezipink commented on Apr 7, 2016

    @pezipink
    Contributor

    I am not 100% sure why this is happening - if it is a sync problem can you not just lock or sync via a mailbox?

    I will look at this when I get back around to doing some work on this type provider.

  2. Thorium commented on Apr 8, 2016

    @Thorium
    MemberAuthor

    Are you suggesting that I would have only one web-user accessing the database at time?

    I would rather like to see some kind of "if this error, refresh the context and retry"-operation...

  3. pezipink commented on Apr 9, 2016

    @pezipink
    Contributor

    You could have multiple data contexts, there is no real disadvantage to this since the connections are closed and reopened with each action, which are pooled via normal ado mechanics - would that sort it ?

  4. Thorium commented on May 2, 2016

    @Thorium
    MemberAuthor

    Ok I think this is a basic problem that gets solved if I wrap my queries to transactions so that both query and the SubmitUpdates are inside of a same transaction. By default, they are not; how could query know anything.

    So basically if I have read-only-operations they are ok to execute as is, but if I have SubmitUpdates then I have to wrap the queries related to this to a transaction. Inside SubmitUpdates is made a new transaction with default options (which is enlist to existing transaction or make a new if none exists) which is good.

    I made a little wrapper to do the transaction:

    
    let dbReadOnlyContext = 
        if cstr = null then TypeProviderConnection.GetDataContext()
        else TypeProviderConnection.GetDataContext cstr
    
    let writeWithDbContextManualComplete() =
        let isMono = Type.GetType ("Mono.Runtime") <> null
        let context = TypeProviderConnection.GetDataContext cstr
        let scope =
            match isMono with
            | true -> new Transactions.TransactionScope()
            | false ->
                // Note1: On Mono, 4.6.1 or newer is requred for compiling TransactionScopeAsyncFlowOption.
                // Note2: We should here also set the transaction option isolation level.
                new Transactions.TransactionScope(System.Transactions.TransactionScopeAsyncFlowOption.Enabled)
    //            new Transactions.TransactionScope(
    //                Transactions.TransactionScopeOption.Required,
    //                new Transactions.TransactionOptions(
    //                    IsolationLevel = Transactions.IsolationLevel.RepeatableRead),
    //                System.Transactions.TransactionScopeAsyncFlowOption.Enabled)    scope, context
        // note that scope.Dispose() will complete the transaction if scope.Complete() is done
    
    open System.Threading.Tasks
    /// Write operations should be wrapped to transaction with this.
    let writeWithDbContext<'T> (func:TypeProviderConnection.dataContext -> Task<'T>) =
        task {
            let transaction, context = writeWithDbContextManualComplete()
            use scope = transaction
            let! res = func context
    
            if not isMono then
                if not (isNull scope) then
                    try
                        scope.Complete()
                        scope.Dispose()
                    with
                    | :? ObjectDisposedException -> ()
            return res
        }
    
    let writeWithDbContextAsync<'T> (func:TypeProviderConnection.dataContext -> Async<'T>) =
        async {
            let transaction, context = writeWithDbContextManualComplete()
            use scope = transaction
            let! res = func context
            if not isMono then
              if not(isNull scope) then
                  try
                      scope.Complete()
                      scope.Dispose()
                  with
                  | :? ObjectDisposedException -> ()
            return res
        }
    
    

    And I use it like this, only add this one extra line of code to the beginning of an existing write-methods:

        let  doStuff () =
          writeWithDbContext <| fun (dbContext:DataContext) ->
            let e = query { for m in dbContext.MyTable do where (m.Id = "A") select (m) } 
            e.SetColumn("mycol", 1) 
            dbContext.SubmitUpdates() 
    

    I'm happy for now, this issue should be ok.

  5. Thorium commented on May 9, 2016

    @Thorium
    MemberAuthor

    Note, in the existing code, this is not thread-safe:
    let pendingChanges = HashSet<SqlEntity>()

  6. Thorium commented on May 29, 2016

    @Thorium
    MemberAuthor

    Much better now!

  7. Thorium commented on Dec 25, 2016

    @Thorium
    MemberAuthor

    Some more tales from production... I'm using currently one context only, the same for all the read operations. And then new contexts (and transactions as described above) for every operation containing also write-operations.

    I'm using separate Azure SQL-database. The network connection to Azure database is not totally reliable. Sometimes the connection creation just throws network exception:

    System.Data.SqlClient.SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) ---> System.ComponentModel.Win32Exception (0x80004005): The network path was not found

    So I had to create a retry like this (actually I'm using Logary for logging but anyways):

    let internal createDbReadOnlyContext() = 
        let rec createCon x =
            try
                if cstr = null then TypeProviderConnection.GetDataContext()
                else TypeProviderConnection.GetDataContext cstr
            with
            | :? System.Data.SqlClient.SqlException as ex when x < 3 ->
                System.Console.WriteLine("Error connecting SQL, retrying... " + ex.Message)
                System.Threading.Thread.Sleep 50
                createCon (x+1)
            | :? System.Data.SqlClient.SqlException as ex when x < 5 ->
                System.Console.WriteLine("Error connecting SQL, retrying... " + ex.Message)
                System.Threading.Thread.Sleep 1500
                createCon (x+1)
        createCon 0

    After that, the connection seems to be more error prone. I'm running my program as a auto-starting Windows service on Azure machine. Then the next problem I faced was that Windows servers on Azure does maintenance boots every now and then. And now, if the database connection is not working when the service starts (which is probable because the database can also be running update at the same time), the connection will be on some kind of failed state: the read-connection won't start working even when the SQL-database goes back online.

    So for that, I changed the read-only connection to have a backing-static-container-variable and replace the connection on failures:

    type DataContext = TypeProviderConnection.dataContext
    
    let mutable internal contextHolder = Unchecked.defaultof<Lazy<DataContext>>
    let dbReadOnlyContext() = 
        if contextHolder = null || not (contextHolder.IsValueCreated) then
            try
                let itm = lazy(createDbReadOnlyContext())
                contextHolder <- itm
            with
            | e -> System.Console.WriteLine("SQL connection failed: " + e.Message)
        contextHolder.Force()

    The sad thing is I have to call my dbReadOnlyContext as a function, even if it's usually not using the function but just fetching a static variable:

    let! items =
        query {
            for item in dbReadOnlyContext().Dbo.MyTable do //...

    but now it seems to be durable enough to start the process without SQL-database connection and then restore the connection after the failure time is over.

    We could include this kind of error tolerance to SQLProvider itself (as there are sometimes some invisible error-management on database-driver-level also), or some extension-module. Now I have the source codes in my project, but they are not at all project-specific codes. What do you think?

  8. giuliohome commented on Feb 24, 2020

    @giuliohome
    Contributor

    We could include this kind of error tolerance to SQLProvider itself (as there are sometimes some invisible error-management on database-driver-level also), or some extension-module. Now I have the source codes in my project, but they are not at all project-specific codes. What do you think?

    Is it already included nowadays or should I introduce such a mechanism in my specific project?

    Last friday a user of mine received the Error: "Unchanged entity encountered in update list - this should not be possible!". Today the situation seems fine anyway, but I'm a bit worried it might happen again...
    In my DB module I have a single, initial
    let context = Sql.GetDataContext // ... conn string from config
    Up till now I haven't had such errors, do you think I can consider it an exceptional case and ignore it for the moment or should I think about some helpers like your writeWithDbContext or dbReadOnlyContext or anything special for updates?
    Actually I see some commits and merge linked above so I guess this sort of "error tolerance" is already part of SQLProvider itself, isn't it? Thanks

    Edit 1
    I see that unfortunately the error is still present in my production env so I actually need to prepare a fix for it in my project. I will share it if anyone is interested as soon as it is ready.

    Edit 2
    In my project I've replaced context.SubmitUpdates() with a safer helper:

        let safeSaveContext msg =
            try
                context.SubmitUpdates()
                Result.Ok msg
            with
            | exc ->
                context.ClearUpdates() |> ignore
                Result.Error exc.Message
    
  9. Thorium commented on Feb 25, 2020

    @Thorium
    MemberAuthor

    I have been using async version, and this has been in my production for a long time already, feel free to copy&modify:

    open System
    open System.Collections.Concurrent
    //... And your logging...
    
    type TypeProviderConnection.dataContext with
      /// SubmitUpdates() but on error ClearUpdates()
      member x.SubmitUpdates2(shouldLogErrors:Logger Option) =
        async {
    
            /// Log SQL events to debug log
            let sqlList = ConcurrentBag<FSharp.Data.Sql.Common.QueryEvents.SqlEventData>()
            use o = FSharp.Data.Sql.Common.QueryEvents.SqlQueryEvent |> Observable.subscribe(fun e -> sqlList.Add e)
            let! res = x.SubmitUpdatesAsync() |> Async.Catch
            match res with
            | Choice1Of2 _ -> ()
            | Choice2Of2 e ->
                let errormsg = (e.ToString() + "\r\n\r\n"+ System.Diagnostics.StackTrace(1, true).ToString())
                let entities = x.GetUpdates() |> List.map (fun entity ->
                    let fields = String.Join("\r\n  ", entity.ColumnValues |> Seq.map(fun (c,v) -> match v with null -> c | _ -> c + " " + v.ToString()) |> Seq.toArray)
                    "Item: \r\n" + fields) |> Seq.toArray
                let ex = new InvalidOperationException(errormsg + "\r\n\r\nDatabase commit failed for entities: " + String.Join("\r\n", entities) + "\r\n", e)
                match shouldLogErrors with
                | None ->
                    Console.WriteLine ex
                | Some logger ->
                    writeLog logger (eventError "SubmitUpdates2 error {err}" |> setField "err" errormsg)
                    sqlList |> Seq.iter(fun e ->
                        writeLog logger (eventError "SQL executed when error" |> setField "sql" (e.ToString()))
                    )
                    try
                        x.ClearUpdates() |> ignore
                    with
                    | ex2 -> writeLog logger (eventError "SubmitUpdates2 clearing error {err}" |> setField "err" (ex2.ToString()))
                    return raise ex
        }
      member x.SubmitUpdates2() =
            let l = logger.Force()
            x.SubmitUpdates2(Some l)
  10. Thorium commented on Feb 25, 2020

    @Thorium
    MemberAuthor

    Also, this is related.

  11. giuliohome commented on Feb 25, 2020

    @giuliohome
    Contributor

    @Thorium Have you ever used the None branch of you match in production? It would need a x.ClearUpdates() there: that's why it is a bad idea having to explicitly call it.

  12. Thorium commented on Feb 25, 2020

    @Thorium
    MemberAuthor

    I haven't, it's only for canopy web-tests, where I don't bother the long run. :-)
    I see your point, however I kind of like SQLProvider to not depend on any logging framework.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions