Skip to content

Add option to control NpgsqlTransaction.Commit() timeout parameter in Npgsql 2.x #1366

Closed

Description

@janagan-net

The NpgsqlTransaction.Commit() command sets 20 second timeout and hasn't options to control it. Note that I found this issue in Npgsql 2.x version (3.x version wasn't tested). I know that it's not supported any more. So, I'm ready to make a pull request.

I know that COMMIT; usually runs fast. So, in general case timeout is a good idea to prevent from deadlocks. But all DEFERRED constraints are checked in the commit stage, and it can take a lot of time. So, option to control commit timeout parameter is important.

A small proof of concept example. Let's create PostgreSql tables:

CREATE TABLE section
(
  id bigint NOT NULL,
  section_name character varying NOT NULL,
  CONSTRAINT section_pkey PRIMARY KEY (id)
);
CREATE TABLE section_items
(
  id bigint NOT NULL,
  section_id bigint NOT NULL,
  item_name character varying NOT NULL,
  previous_item bigint,
  CONSTRAINT section_items_pkey PRIMARY KEY (id),
  CONSTRAINT section_items_previous_item_fkey FOREIGN KEY (previous_item)
	  REFERENCES section_items (id) MATCH SIMPLE
	  ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED,
  CONSTRAINT section_items_section_id_fkey FOREIGN KEY (section_id)
	  REFERENCES section (id) MATCH SIMPLE
	  ON UPDATE RESTRICT ON DELETE CASCADE,
  CONSTRAINT section_items_section_id_excl EXCLUDE 
  USING btree (section_id WITH =) WHERE (previous_item IS NULL)
  DEFERRABLE INITIALLY DEFERRED,
  CONSTRAINT section_items_section_id_previous_item_key UNIQUE (section_id, previous_item),
  CONSTRAINT section_items_check CHECK (id <> previous_item)
);

And run C# program:

using Npgsql;

namespace NpgsqlTest
{
	static class Program
	{
		static void Main(string[] args)
		{
			//We set command timeout to infinity here
			using (var connection = new NpgsqlConnection("User ID=postgres;Password=***;Host=127.0.0.1;Port=5432;Database=test;Timeout=60;CommandTimeout=0;"))
			{
				connection.Open();

				using (var transaction = connection.BeginTransaction())
				{
					using (var command = new NpgsqlCommand(
@"-- Delete all data
TRUNCATE TABLE section CASCADE;

-- We need just one section
INSERT INTO section(id, section_name)
VALUES(1, 'Section1');

-- Let's add the list of items
INSERT INTO section_items(id, section_id, item_name, previous_item)
SELECT id, 1, 'Item' || id, CASE WHEN id <= 1 THEN NULL ELSE id - 1 END FROM generate_series(1, 50000) AS s(id);"
						, connection))
					{
						command.ExecuteNonQuery();
					}

					transaction.Commit();
				}

				using (var transaction = connection.BeginTransaction())
				{
					using (var command = new NpgsqlCommand(
@"-- We would like to use NpgsqlConnection.BeginTransaction() command
--BEGIN;

-- Let's remove every second item...
DELETE FROM section_items WHERE id % 2 = 0;

-- ...and update positions of items in the list
UPDATE section_items SET previous_item = previous_item - 1 WHERE previous_item IS NOT NULL;

--We would like to use NpgsqlTransaction.Commit() command
--COMMIT;"
						, connection))
					{
						command.ExecuteNonQuery();
					}

					//We'll see the timeout NpgsqlException here because CommandTimeout doesn't apply to the NpgsqlTransaction.Commit() command
					//Hint: You can execute BEGIN; and COMMIT; commands manually whithout NpgsqlTransaction. It works fine.
					transaction.Commit();
				}
			}
		}
	}
}

You'll see this NpgsqlException: A timeout has occured. If you were establishing a connection, increase Timeout value in ConnectionString. If you were executing a command, increase the CommandTimeout value in ConnectionString or in your NpgsqlCommand object.

Hint: in this example transaction.Commit(); is too long because index doesn't exist on previous_item column for section_items_previous_item_fkey FOREIGN KEY. So, if add the index, commit will run much faster.

CREATE INDEX section_items_previous_item_idx
  ON section_items
  USING btree
  (previous_item);

Activity

  1. roji commented on Nov 26, 2016

    @roji
    Member

    Npgsql 3.x has the Internal Command Timeout connection string parameter (see the docs), it should allow you to control the timeout for internal commands such as commit. Can you please try it and confirm it works for you?

    Npgsql 2.x is extremely old by now, I don't really plan on releasing a new version for it...

  2. janagan-net commented on Nov 26, 2016

    @janagan-net
    Author

    I know that Npgsql 2.x is extremely old. But I have to use .NET 4.0 because I have to support MS Windows XP. So, migrate to Npgsql 3.x isn't option for me, sorry. It means that I'll fix this issue in any case. I just want to make a pull request for everyone.

    Let's talk about Npgsql 3.x now. It looks like that it has another bug - it totally ignores InternalCommandTimeout parameter in NpgsqlConnection.
    Let's see tests:

    1. CommandTimeout=0; and InternalCommandTimeout=3 - works without exception. Note that commit runs 87 seconds - it's definitely more than 3 seconds (the time was measured by Stopwatch).
    2. CommandTimeout=3; and InternalCommandTimeout=0 - gives NpgsqlException: Exception while reading from stream.
    3. CommandTimeout=3; and InternalCommandTimeout=1000 - gives NpgsqlException: Exception while reading from stream.
    4. CommandTimeout=0; and InternalCommandTimeout wasn't specified - works correctly as expected.
    5. CommandTimeout=0; and InternalCommandTimeout=-1 - works correctly without exception as expected.
    6. CommandTimeout=0; and InternalCommandTimeout=0 - works correctly without exception as expected.
    7. CommandTimeout=0; and InternalCommandTimeout=1000 - works correctly without exception as expected.

    You can try to confirm it yourself. Also, I can try to fix this problem if you haven't any objections.

  3. roji commented on Nov 27, 2016

    @roji
    Member

    @janagan-net thanks for reporting this, it's true that Internal Command Timeout is pretty rarely-used, I'm not totally surprised a bug report on this hasn't come in further. I'll definitely accept a PR for fixing this in 3.1.10 if you want to take a stab at it, otherwise let me know and I'll look into it.

    My sympathies for having to support Windows XP and .NET 4.0... :) I hesitated at the time whether to attempt to keep .NET 4.0 support but ended up dropping it because new features were impossible to support (e.g. async). Regarding Npgsql 2.x, I'm probably not going to have the time to review/merge/release a PR, but you can definitely submit it.

  4. janagan-net commented on Nov 27, 2016

    @janagan-net
    Author

    OK. I'll look at bough 2.x and 3.x bugs when I'll have some time. Probably, it will be at next weekend.

    I just want to ask a question. We have NpgsqlCommand.CommandTimeout property to control CommandTimeout. Should we add NpgsqlCommand.InternalCommandTimeout property to control InternalCommandTimeout? Or do you think that InternalCommandTimeout parameter in NpgsqlConnection should be enough to everybody?

  5. roji commented on Nov 27, 2016

    @roji
    Member

    OK. I'll look at bough 2.x and 3.x bugs when I'll have some time. Probably, it will be at next weekend.

    OK great.

    I just want to ask a question. We have NpgsqlCommand.CommandTimeout property to control CommandTimeout. Should we add NpgsqlCommand.InternalCommandTimeout property to control InternalCommandTimeout? Or do you think that InternalCommandTimeout parameter in NpgsqlConnection should be enough to everybody?

    I guess it's mainly a question of people actually needing it. To be honest, you're the first one to ever complain about Internal Command Timeout not working in the connection string - I think there aren't a lot of people using this.

    I'd say that if someone actually requests this feature on NpgsqlCommand, it would make sense to add it, but let's leave it out for now.

  6. janagan-net commented on Nov 28, 2016

    @janagan-net
    Author

    OK. In that case I'll just fix the bug with Internal Command Timeout in the connection string.

  7. roji commented on Feb 1, 2017

    @roji
    Member

    @janagan-net do you intend to work on a PR for Npgsql 3.x?

  8. janagan-net commented on Apr 20, 2017

    @janagan-net
    Author

    @roji yes, I do. I'm REALLY sorry, but I didn't have free time.

    So, PR for Npgsql 2.x is ready.

    I'll make PR for Npgsql 3.x as soon as possible, but I don't know when it will be ready.

  9. roji commented on Jun 8, 2018

    @roji
    Member

    Closing for inactivity, but will reopen upon request.

  10. emz00 commented on Dec 22, 2021

    @emz00
    Contributor

    I believe I'm running into this now with Npgsql 6.0.2, PG 14.1, Windows 7 (both client and server). I'm also inserting many rows into a table with deferred foreign keys, so committing takes a long time. I tried setting InternalCommandTimeout to 600, but this had no effect: NpgsqlTransaction.Commit() still times out after CommandTimeout (30 seconds by default, but I tried increasing that to 35 and it timed out after 35 seconds). So a workaround is to increase CommandTimeout in the connection string, but of course that's not ideal.

  11. roji commented on Dec 31, 2021

    @roji
    Member

    @loop-evgeny I can indeed see in the code that commit just uses the user timeout, and not the internal command timeout. We have #3045 for tracking problems with the internal timeout, or possibly removing it altogether.

    Can you share some info on why you need a special internal timeout for commits that's different from your command timeout?

  12. emz00 commented on Jan 3, 2022

    @emz00
    Contributor

    In this case I was trying out deferred foreign keys for a command that inserted many rows. Some commands get run using the same connection that should be very fast, so I didn't want to set a long CommandTimeout on the connection by default. Maybe it would be OK to set the per-command CommandTimeout, but as I understood, it had to be set on the connection to apply to NpgsqlTransaction.Commit. In any case, we're probably not going to use deferred FKs in the end, so this won't affect us.

  13. roji commented on Jan 3, 2022

    @roji
    Member

    Thanks for the added context, that makes sense. One problem I have with InternalCommandTimeout is that like the regular CommandTimeout, it's pretty coarse; we could make it affect committing, but it would also affect rolling back, and various other internal stuff. So having a single "internal" value doesn't seem to be considerably more helpful than just using the general timeout on the connection.

    Specifically for transactions, we could add a timeout property to the transaction, and that value would be used when committing and rolling back; this would be similar to how you can set a per-command timeout.

    I'll make a note of this in #3045, but otherwise I'll go ahead and close this for now.

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