Skip to content

Fix race condition between opening and closing - #3247

Merged
roji merged 1 commit into
npgsql:mainfrom
roji:CloseRaceCondition
Oct 21, 2020
Merged

roji merged 1 commit into
npgsql:mainfrom
roji:CloseRaceCondition

Conversation

@roji

@roji roji commented Oct 21, 2020

Copy link
Copy Markdown
Member

The Close code was setting the connector's Connection to null after returning to the pool, so it was in a race condition with opening code taking the same connector out of the pool.

Fixes #3241

For reference, here's test which reproduced this to me. Not committing it since it's highly timing-sensitive etc:

[Test]
public Task RaceCondition()
    => Task.WhenAll(Enumerable.Range(0, 100000).Select(async i =>
    {
        using var conn = await OpenConnectionAsync();
        using var tx = conn.BeginTransaction();
        using var cmd = new NpgsqlCommand("SELECT 1", conn, tx);

        using (var reader = await cmd.ExecuteReaderAsync())
        {
            reader.Read();
            _ = reader.GetInt32(0);
        }

        tx.Commit();
    }));

The Close code was setting the connector's Connection to null *after*
returning to the pool, so it was in a race condition with opening
code taking the same connector out of the pool.

Fixes npgsql#3241
@roji
roji force-pushed the CloseRaceCondition branch from 840f0c1 to ad88342 Compare October 21, 2020 11:48
@roji

roji commented Oct 21, 2020 •

Copy link
Copy Markdown
Member Author

😠 this is smelly. At some point I really want to rethink the relationship between connector and connection.

@roji

roji commented Oct 21, 2020

Copy link
Copy Markdown
Member Author

@vonzshik this is finally passing the build, ready for your review.

@vonzshik vonzshik left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great!

If only there was a way to make a reliable test 😢

@roji

roji commented Oct 21, 2020

Copy link
Copy Markdown
Member Author

If only there was a way to make a reliable test cry

Yeah, testing race conditions is one of the big unsolved problems of software engineering...

@roji
roji merged commit 5c11766 into npgsql:main Oct 21, 2020
@roji
roji deleted the CloseRaceCondition branch October 21, 2020 13:37
roji pushed a commit that referenced this pull request Oct 24, 2020
Backports #3247 for ambient transaction scenario.
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.

Exception "In multiplexing mode, transactions must be started with BeginTransaction" without Multiplexing with 5.0.0-preview1

2 participants