pg.ddx.io  pgsql-bugs@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Update with subselect sometimes returns wrong result
24+ messages / 7 participants
[nested] [flat]

* Update with subselect sometimes returns wrong result
@ 2013-11-29 23:08 Oliver Seemann <oseemann@gmail.com>
  2013-11-30 07:32 ` Re: Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 12:12 ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  0 siblings, 3 replies; 24+ messages in thread

From: Oliver Seemann @ 2013-11-29 23:08 UTC (permalink / raw)
  To: pgsql-bugs

Hi!

Given the following table:

CREATE TABLE t1 (id INTEGER);
INSERT INTO t1 VALUES (0), (1);

Then the following UPDATE should return exactly one row:

UPDATE t1 SET id = t1.id
FROM (SELECT id FROM t1 LIMIT 1 FOR UPDATE) AS subset
WHERE t1.id = subset.id
RETURNING t1.id

And it does so, most of of the time. But when run repeatedly in a loop like
in the attached script, then it will occasionally return 2 rows with two
different id values, something the LIMIT 1 should prevent. In my tests it
took from anywhere between 0 to 10 minutes and on average 1 to 2 minutes to
trigger the problem.

I have reproduced the issue on different machines and platforms with PG
9.3.1, 9.1.10, 9.0.14. (See file).

Interesting, and perhaps telling:
When autovacuum=off in postgresql.conf then I could not trigger the problem.


Oliver

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments:

pgbug.py (text/x-python, 1.9K) download #!/usr/bin/env python # -*- coding: utf-8 -*- # vim:set ts=4 sts=4 sw=4 expandtab: """ The UPDATE statement below should always return only 1 row, due to the LIMIT 1 clause in the sub-select and unique values of the joined id column. Most of the time it correctly returns only one row. But when run repeatedly, after on average about 2 minutes, it will return two rows with different id values. This should never happen. This problem has been repeatedly reproduced on the following platforms: PG 9.3.1 on Debian Wheezy, Opteron 2347, Python 2.7.3, psycopg2 2.5.1 PG 9.0.13 on Debian Wheezy, Opteron 2347, Python 2.7.3, psycopg2 2.5.1 PG 9.1.10 on Ubuntu 13.04, Core 2 E8400, Python 2.7.4, psycopg2 2.4.5 PG 9.0.14 on OS X 10.8.5, Core i5, Python 2.7.2, psycopg2 2.5.1 The Debian packages are from the PGDG APT repository. The Ubuntu package is the distribution default. The OS X package is from MacPorts. The Ubuntu and OS X machines were running the default PG config. The issue could not be reproduced when autovacuum is disabled! Run the script with a PG_BUG_CONNSTR environment variable containing a postgresql connection string to an empty database: $ PG_BUG_CONNSTR="dbname=pgbug" python pgbug.py Make sure the psycopg2 module is available. """ import os import psycopg2 def test_bug(): conn = psycopg2.connect(os.environ['PG_BUG_CONNSTR']) conn.autocommit = True cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS t1") cur.execute("CREATE TABLE t1 (id INTEGER)") for i in range(1, 1000000): update(cur, i) def update(cur, i): cur.execute("DELETE FROM t1") cur.execute("INSERT INTO t1 VALUES (0), (1)") cur.execute(""" UPDATE t1 SET id = t1.id FROM (SELECT id FROM t1 LIMIT 1 FOR UPDATE) AS subset WHERE t1.id = subset.id RETURNING t1.id """) rows = cur.fetchall() print(rows, i) assert(len(rows) == 1) if __name__ == '__main__': test_bug()
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
@ 2013-11-30 07:32 ` Oliver Seemann <oseemann@gmail.com>
  2 siblings, 0 replies; 24+ messages in thread

From: Oliver Seemann @ 2013-11-30 07:32 UTC (permalink / raw)
  To: pgsql-bugs; +Cc: jturkel@salsify.com

This looks like the same issue:
http://www.postgresql.org/message-id/E1VN53g-0002Iy-Il@wrigleys.postgresql.org


2013/11/30 Oliver Seemann <oseemann@gmail.com>

> Hi!
>
> Given the following table:
>
> CREATE TABLE t1 (id INTEGER);
> INSERT INTO t1 VALUES (0), (1);
>
> Then the following UPDATE should return exactly one row:
>
> UPDATE t1 SET id = t1.id
> FROM (SELECT id FROM t1 LIMIT 1 FOR UPDATE) AS subset
> WHERE t1.id = subset.id
> RETURNING t1.id
>
> And it does so, most of of the time. But when run repeatedly in a loop
> like in the attached script, then it will occasionally return 2 rows with
> two different id values, something the LIMIT 1 should prevent. In my tests
> it took from anywhere between 0 to 10 minutes and on average 1 to 2 minutes
> to trigger the problem.
>
> I have reproduced the issue on different machines and platforms with PG
> 9.3.1, 9.1.10, 9.0.14. (See file).
>
> Interesting, and perhaps telling:
> When autovacuum=off in postgresql.conf then I could not trigger the
> problem.
>
>
> Oliver
>
>

^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
@ 2013-11-30 17:57 ` Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 20:42   ` Re: Update with subselect sometimes returns wrong result Marko Tiikkaja <marko@joh.to>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2 siblings, 2 replies; 24+ messages in thread

From: Tom Lane @ 2013-11-30 17:57 UTC (permalink / raw)
  To: Oliver Seemann <oseemann@gmail.com>; +Cc: pgsql-bugs

Oliver Seemann <oseemann@gmail.com> writes:
> Given the following table:

> CREATE TABLE t1 (id INTEGER);
> INSERT INTO t1 VALUES (0), (1);

> Then the following UPDATE should return exactly one row:

> UPDATE t1 SET id = t1.id
> FROM (SELECT id FROM t1 LIMIT 1 FOR UPDATE) AS subset
> WHERE t1.id = subset.id
> RETURNING t1.id

> And it does so, most of of the time. But when run repeatedly in a loop like
> in the attached script, then it will occasionally return 2 rows with two
> different id values, something the LIMIT 1 should prevent. In my tests it
> took from anywhere between 0 to 10 minutes and on average 1 to 2 minutes to
> trigger the problem.

I failed to reproduce the claimed misbehavior in git tip of any active
branch.  I'd like to think this means we fixed the problem in the last
two months, but I don't see anything that looks like a promising candidate
in the commit logs.  Perhaps there is some important contributing factor
you've not mentioned --- nondefault postgresql.conf settings, for
instance.

			regards, tom lane


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
@ 2013-11-30 20:42   ` Marko Tiikkaja <marko@joh.to>
  1 sibling, 0 replies; 24+ messages in thread

From: Marko Tiikkaja @ 2013-11-30 20:42 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Oliver Seemann <oseemann@gmail.com>; +Cc: pgsql-bugs

On 11/30/13, 6:57 PM, Tom Lane wrote:
> Oliver Seemann <oseemann@gmail.com> writes:
>> And it does so, most of of the time. But when run repeatedly in a loop like
>> in the attached script, then it will occasionally return 2 rows with two
>> different id values, something the LIMIT 1 should prevent. In my tests it
>> took from anywhere between 0 to 10 minutes and on average 1 to 2 minutes to
>> trigger the problem.
>
> I failed to reproduce the claimed misbehavior in git tip of any active
> branch.  I'd like to think this means we fixed the problem in the last
> two months, but I don't see anything that looks like a promising candidate
> in the commit logs.  Perhaps there is some important contributing factor
> you've not mentioned --- nondefault postgresql.conf settings, for
> instance.

I've managed to reproduce this against REL9_1_STABLE 
(4bdccd8427718f9c468e5e03286252f37ea771b5).  I'm on OS X mavericks, 
configure line: ./configure --enable-debug --with-openssl --with-perl 
--with-libxml --with-readline.  Compiler Apple LLVM version 5.0 
(clang-500.2.79) (based on LLVM 3.3svn).  No changes to postgresql.conf.

Does that help?  Do you need some more information?



Regards,
Marko Tiikkaja


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
@ 2013-11-30 21:40   ` Andres Freund <andres@2ndquadrant.com>
  2013-12-01 03:00     ` Re: Update with subselect sometimes returns wrong result David Johnston <polobo@yahoo.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 2 replies; 24+ messages in thread

From: Andres Freund @ 2013-11-30 21:40 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

On 2013-11-30 12:57:44 -0500, Tom Lane wrote:
> Oliver Seemann <oseemann@gmail.com> writes:
> > Given the following table:
> 
> > CREATE TABLE t1 (id INTEGER);
> > INSERT INTO t1 VALUES (0), (1);
> 
> > Then the following UPDATE should return exactly one row:
> 
> > UPDATE t1 SET id = t1.id
> > FROM (SELECT id FROM t1 LIMIT 1 FOR UPDATE) AS subset
> > WHERE t1.id = subset.id
> > RETURNING t1.id
> 
> > And it does so, most of of the time. But when run repeatedly in a loop like
> > in the attached script, then it will occasionally return 2 rows with two
> > different id values, something the LIMIT 1 should prevent. In my tests it
> > took from anywhere between 0 to 10 minutes and on average 1 to 2 minutes to
> > trigger the problem.
> 
> I failed to reproduce the claimed misbehavior in git tip of any active
> branch.  I'd like to think this means we fixed the problem in the last
> two months, but I don't see anything that looks like a promising candidate
> in the commit logs.  Perhaps there is some important contributing factor
> you've not mentioned --- nondefault postgresql.conf settings, for
> instance.

Looks reproducable here as well, manually executing VACUUMs on the table
greatly speeds things up. Fails within seconds when doing so.


So, it looks like the limit returns more than one row, it's not updating
the same row twice.

Slightly hacked up (probably python 2 only) version of the test script
attached. I'll get to trying to write the release stuff rather then
playing with more interesting things ;)

new row at:  (0,4)
updated row from (0,2) to (0,1) iter 400 
deleted row at:  (0,1)
deleted row at:  (0,5)
new row at:  (0,1)
new row at:  (0,5)
updated row from (0,1) to (0,3) iter 401 
deleted row at:  (0,2)
deleted row at:  (0,3)
new row at:  (0,2)
new row at:  (0,3)
updated row from (0,1) to (0,3) iter 402 
deleted row at:  (0,2)
deleted row at:  (0,3)
new row at:  (0,2)
new row at:  (0,3)
updated row from (0,4) to (0,1) iter 403 
deleted row at:  (0,1)
deleted row at:  (0,5)
new row at:  (0,1)
new row at:  (0,5)
updated row from (0,1) to (0,3) iter 404 
deleted row at:  (0,2)
deleted row at:  (0,3)
new row at:  (0,2)
new row at:  (0,3)
updated row from (0,1) to (0,3) iter 405 
deleted row at:  (0,2)
deleted row at:  (0,3)
new row at:  (0,2)
new row at:  (0,3)
updated row from (0,4) to (0,6) iter 406 
...
deleted row at:  (0,2)
deleted row at:  (0,3)
new row at:  (0,2)
new row at:  (0,3)
updated row from (0,4) to (0,1) iter 447 
updated row from (0,5) to (0,2) iter 447 
Traceback (most recent call last):
  File "/tmp/pgbug.py", line 80, in <module>
    test_bug()
  File "/tmp/pgbug.py", line 51, in test_bug
    update(cur, i)
  File "/tmp/pgbug.py", line 76, in update
    assert(len(rows) == 1)
AssertionError


There's clearly something wrong. (0,4) has been updated several times,
but seems to still be visible.

Greetings,

Andres Freund

-- 
 Andres Freund	                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments:

pgbug.py (text/plain, 2.3K) download #!/usr/bin/env python # -*- coding: utf-8 -*- # vim:set ts=4 sts=4 sw=4 expandtab: """ The UPDATE statement below should always return only 1 row, due to the LIMIT 1 clause in the sub-select and unique values of the joined id column. Most of the time it correctly returns only one row. But when run repeatedly, after on average about 2 minutes, it will return two rows with different id values. This should never happen. This problem has been repeatedly reproduced on the following platforms: PG 9.3.1 on Debian Wheezy, Opteron 2347, Python 2.7.3, psycopg2 2.5.1 PG 9.0.13 on Debian Wheezy, Opteron 2347, Python 2.7.3, psycopg2 2.5.1 PG 9.1.10 on Ubuntu 13.04, Core 2 E8400, Python 2.7.4, psycopg2 2.4.5 PG 9.0.14 on OS X 10.8.5, Core i5, Python 2.7.2, psycopg2 2.5.1 The Debian packages are from the PGDG APT repository. The Ubuntu package is the distribution default. The OS X package is from MacPorts. The Ubuntu and OS X machines were running the default PG config. The issue could not be reproduced when autovacuum is disabled! Run the script with a PG_BUG_CONNSTR environment variable containing a postgresql connection string to an empty database: $ PG_BUG_CONNSTR="dbname=pgbug" python pgbug.py Make sure the psycopg2 module is available. """ import os import psycopg2 def test_bug(): conn = psycopg2.connect(os.environ['PG_BUG_CONNSTR']) conn.autocommit = True cur = conn.cursor() cur.execute("DROP TABLE IF EXISTS t1") cur.execute("CREATE TABLE t1 (id INTEGER)") cur.execute("INSERT INTO t1 VALUES (0), (1) RETURNING ctid") for i in range(1, 1000000): update(cur, i) def update(cur, i): cur.execute("DELETE FROM t1 RETURNING ctid") rows = cur.fetchall() for row in rows: print "deleted row at: ", row[0] assert(len(rows) == 2) cur.execute("INSERT INTO t1 VALUES (0), (1) RETURNING ctid") row2 = cur.fetchall() for row in rows: print "new row at: ", row[0] cur.execute(""" UPDATE t1 SET id = t1.id FROM (SELECT id, ctid FROM t1 LIMIT 1 FOR UPDATE) AS subset WHERE t1.id = subset.id RETURNING t1.id, subset.ctid oldctid, t1.ctid newctid """) rows = cur.fetchall() for row in rows: print "updated row from %s to %s iter %u " % (row[1], row[2], i) assert(len(rows) == 1) if __name__ == '__main__': test_bug()
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
@ 2013-12-01 03:00     ` David Johnston <polobo@yahoo.com>
  1 sibling, 0 replies; 24+ messages in thread

From: David Johnston @ 2013-12-01 03:00 UTC (permalink / raw)
  To: pgsql-bugs

Andres Freund-3 wrote
> deleted row at:  (0,1)
> deleted row at:  (0,5)
> new row at:  (0,1)
> new row at:  (0,5)
> updated row from (0,1) to (0,3) iter 401 
> deleted row at:  (0,2)
> deleted row at:  (0,3)

Am I reading this right?

Rows == ctid(,#)

Rows 1 & 5 exist; are deleted
Add two new rows, store them at 1 & 5 replacing the just deleted rows
--? does auto-vacuum work that fast that these physical locations are
immediately available...

Update row 1, store new value in 3 marking 1 as deleted (not shown here)
Rows 2?  & 3 exist and are now deleted

?Where did Row 2 come from...was expecting row 5...?


> new row at:  (0,2) 
> new row at:  (0,3) 
> updated row from (0,1) to (0,3) iter 405 
> deleted row at:  (0,2) 
> deleted row at:  (0,3) 

Likewise: how did Row 1 come into being (so that it could be updated) when
only 2 and 3 were added on the prior iteration?

Then, at the point of the assertion failure, rows 4 & 5 are updated but rows
2 & 3 were the rows that were added...so neither of the just-inserted rows
were returned...

Sorry I cannot actually debug code but figured my observations might be
helpful none-the-less.

David J.





--
View this message in context: http://postgresql.1045698.n5.nabble.com/Update-with-subselect-sometimes-returns-wrong-result-tp57809...
Sent from the PostgreSQL - bugs mailing list archive at Nabble.com.


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
@ 2013-12-01 06:41     ` Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 07:03       ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 08:19       ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  1 sibling, 2 replies; 24+ messages in thread

From: Tom Lane @ 2013-12-01 06:41 UTC (permalink / raw)
  To: Andres Freund <andres@2ndquadrant.com>; +Cc: Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

Andres Freund <andres@2ndquadrant.com> writes:
> Slightly hacked up (probably python 2 only) version of the test script
> attached.

Ah, deleting and reinserting the rows each time like that makes it a
lot more reproducible.  I don't have the full story but it's got something
to do with screwed-up tuple info flags.  The plan that's generated looks
like

 Update on t1
   ->  Nested Loop
         Join Filter: (t1.id = subset.id)
         ->  Seq Scan on t1
         ->  Subquery Scan on subset
               ->  Limit
                     ->  LockRows
                           ->  Seq Scan on t1 t1_1

so the subquery scan will be executed twice, once for each row in t1.
The first time through, heap_lock_tuple looks at the first tuple and
locks it.  It doesn't get called on the second tuple because the LIMIT
node stops evaluation.  But in the second scan, heap_lock_tuple returns
HeapTupleSelfUpdated for the first tuple, so ExecLockRows ignores it,
moves on to the second tuple, and returns that.  The LIMIT is happy cause
it just got one row back; it doesn't know it's not the same row as
before.  And this row of course passes the join qual with the second
row from the outer scan of t1, so we perform a second update.

Now, the thing about this is that the tuple heap_lock_tuple is rejecting
in the second pass is the one that we just updated, up at the ModifyTable
plan node.  So I can't find it exactly surprising that it says
HeapTupleSelfUpdated.  But tracing through tqual.c shows that the tuple
has got the HEAP_XMAX_IS_MULTI bit set, which might be thought a bit
peculiar.  There's not multiple transactions involved.

Anyway, at this point I'm not so much wondering why it fails as why it
(seems to) work *any* of the time.  And how is it that VACUUM sometimes
manages to flip it from working state to not-working state?  (Once you're
in the state where the UPDATE will say it updated two rows, it's 100%
reproducible.)

Anyway, it seems pretty clear that the explanation is down somewhere in
the tuple visibility and multixact logic that you and Alvaro have been
hacking on with such vim lately.  I'm out of steam for tonight, over
to you ...

			regards, tom lane


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
@ 2013-12-01 07:03       ` Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 12:24         ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  1 sibling, 1 reply; 24+ messages in thread

From: Tom Lane @ 2013-12-01 07:03 UTC (permalink / raw)
  To: Andres Freund <andres@2ndquadrant.com>; +Cc: Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

I wrote:
> Anyway, at this point I'm not so much wondering why it fails as why it
> (seems to) work *any* of the time.  And how is it that VACUUM sometimes
> manages to flip it from working state to not-working state?  (Once you're
> in the state where the UPDATE will say it updated two rows, it's 100%
> reproducible.)

Oh, hah; the case where it works is where the generated plan is the other
way around:

 Update on t1
   ->  Nested Loop
         Join Filter: (t1.id = subset.id)
         ->  Subquery Scan on subset
               ->  Limit
                     ->  LockRows
                           ->  Seq Scan on t1 t1_1
         ->  Seq Scan on t1

so that we never rescan the LockRows node.  heap_lock_tuple followed by
heap_update works sanely, the other way round not so much.

The apparent dependency on VACUUM is probably coming from updating the
table's relpages/reltuples counts to new values in a way that causes the
planner to think one version or the other is a bit cheaper.

I'd still kind of like to know how HEAP_XMAX_IS_MULTI is getting involved,
but it seems that the fundamental problem here is we haven't thought
through what the interactions of LockRows and ModifyTable operations in
the same query ought to be.

			regards, tom lane


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 07:03       ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
@ 2013-12-01 12:24         ` Andres Freund <andres@2ndquadrant.com>
  2013-12-01 17:39           ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 24+ messages in thread

From: Andres Freund @ 2013-12-01 12:24 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

On 2013-12-01 02:03:55 -0500, Tom Lane wrote:
> The apparent dependency on VACUUM is probably coming from updating the
> table's relpages/reltuples counts to new values in a way that causes the
> planner to think one version or the other is a bit cheaper.

Hah, didn't realize that for a good bit... Even though I had reproduced
the problem with just concurrently ANALYZEing the table. Things could
have clicked at that point...

> I'd still kind of like to know how HEAP_XMAX_IS_MULTI is getting
> involved,

Hopefully answered nearby.

> but it seems that the fundamental problem here is we haven't thought
> through what the interactions of LockRows and ModifyTable operations in
> the same query ought to be.

I think it's more that we haven't actually thought about the case where
both happen in the same plan at all ;). I think most of that code is
from the time where it was only possible to get there when using UPDATE
... WHERE CURRENT OF cursor_name because FOR .. wasn't allowed in
subselects.

The reason it reproducably fails is:
/*
 * The target tuple was already updated or deleted by the
 * current command, or by a later command in the current
 * transaction.  We *must* ignore the tuple in the former
 * case, so as to avoid the "Halloween problem" of repeated
 * update attempts.  In the latter case it might be sensible
 * to fetch the updated tuple instead, but doing so would
 * require changing heap_lock_tuple as well as heap_update and
 * heap_delete to not complain about updating "invisible"
 * tuples, which seems pretty scary.  So for now, treat the
 * tuple as deleted and do not process.
 */
goto lnext;

in ExecLockRows(), right? Is there actually a real "Halloween problem"
type of situation here?

But either way, even if we would manage to finagle some meaning into
that case, that query would still not be safe in any way, since there's
no determinism in which row the subselect will return.
On a green field, I'd say we should forbid using FOR UPDATE below an
UPDATE/DELETE and just allow combining them via a CTE. But that's
probably hard to do now.

Greetings,

Andres Freund

-- 
 Andres Freund	                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 07:03       ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 12:24         ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
@ 2013-12-01 17:39           ` Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 0 replies; 24+ messages in thread

From: Tom Lane @ 2013-12-01 17:39 UTC (permalink / raw)
  To: Andres Freund <andres@2ndquadrant.com>; +Cc: Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

Andres Freund <andres@2ndquadrant.com> writes:
> The reason it reproducably fails is:
> /*
>  * The target tuple was already updated or deleted by the
>  * current command, or by a later command in the current
>  * transaction.  We *must* ignore the tuple in the former
>  * case, so as to avoid the "Halloween problem" of repeated
>  * update attempts.  In the latter case it might be sensible
>  * to fetch the updated tuple instead, but doing so would
>  * require changing heap_lock_tuple as well as heap_update and
>  * heap_delete to not complain about updating "invisible"
>  * tuples, which seems pretty scary.  So for now, treat the
>  * tuple as deleted and do not process.
>  */
> goto lnext;

> in ExecLockRows(), right? Is there actually a real "Halloween problem"
> type of situation here?

That's the $64 question at this point.  In this example, at least,
it seems like we'd want heap_lock_tuple to say that you *can* lock
a tuple that's already updated by the current command.  But that
seems like a pretty scary solution --- I'm not sure there aren't
other cases where it'd be the wrong thing.

> But either way, even if we would manage to finagle some meaning into
> that case, that query would still not be safe in any way, since there's
> no determinism in which row the subselect will return.

It's indeterminate to start with (and I guess the OP doesn't care).
But once the first execution has chosen some row, what we want is
for a rescan to return the same row as before.  We definitely don't
want heap_lock_tuple to *create* nondetermininism in a scan that
otherwise didn't have any.

Maybe the solution is to retain enough state to be able to tell that
the tuple was locked, then updated, in the current command, and then
return "already locked" in that case.

> On a green field, I'd say we should forbid using FOR UPDATE below an
> UPDATE/DELETE and just allow combining them via a CTE. But that's
> probably hard to do now.

Yeah, I was thinking the same thing.  In any case, sticking the 
SELECT FOR UPDATE into a WITH should provide an adequate workaround
for now, at least for cases where the outer UPDATE doesn't ever
try to update rows it's not read from the WITH.  (If it does, then
you have the same nondeterminism about whether the WITH would've
returned those rows if it'd gotten to them first.)

			regards, tom lane


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
@ 2013-12-01 08:19       ` Andres Freund <andres@2ndquadrant.com>
  2013-12-01 11:45         ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  1 sibling, 1 reply; 24+ messages in thread

From: Andres Freund @ 2013-12-01 08:19 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

On 2013-12-01 01:41:02 -0500, Tom Lane wrote:
> Now, the thing about this is that the tuple heap_lock_tuple is rejecting
> in the second pass is the one that we just updated, up at the ModifyTable
> plan node.  So I can't find it exactly surprising that it says
> HeapTupleSelfUpdated.  But tracing through tqual.c shows that the tuple
> has got the HEAP_XMAX_IS_MULTI bit set, which might be thought a bit
> peculiar.  There's not multiple transactions involved.

Hm. Haven't looked at that, but if so that seems like an independent bug.

> Anyway, it seems pretty clear that the explanation is down somewhere in
> the tuple visibility and multixact logic that you and Alvaro have been
> hacking on with such vim lately.  I'm out of steam for tonight, over
> to you ...

Will look at it for a bit, but I kinda doubt the multixact logic is,
especially anything we've changed, overly much involved. It's
reproducing on 9.1 after all.

Greetings,

Andres Freund

-- 
 Andres Freund	                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 08:19       ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
@ 2013-12-01 11:45         ` Andres Freund <andres@2ndquadrant.com>
  2013-12-01 11:53           ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-18 22:13           ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  0 siblings, 2 replies; 24+ messages in thread

From: Andres Freund @ 2013-12-01 11:45 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

On 2013-12-01 09:19:19 +0100, Andres Freund wrote:
> On 2013-12-01 01:41:02 -0500, Tom Lane wrote:
> > Now, the thing about this is that the tuple heap_lock_tuple is rejecting
> > in the second pass is the one that we just updated, up at the ModifyTable
> > plan node.  So I can't find it exactly surprising that it says
> > HeapTupleSelfUpdated.  But tracing through tqual.c shows that the tuple
> > has got the HEAP_XMAX_IS_MULTI bit set, which might be thought a bit
> > peculiar.  There's not multiple transactions involved.
> 
> Hm. Haven't looked at that, but if so that seems like an independent bug.

Afaics it's a missed optimization, nothing more. There's a branch in
compute_new_xmax_infomask() where it considers xmax == add_to_xmax with
imo somewhat strange conditions for the optimization:

/*
 * If the existing lock mode is identical to or weaker than the new
 * one, we can act as though there is no existing lock, so set
 * XMAX_INVALID and restart.
 */
if (xmax == add_to_xmax)
{
    LockTupleMode old_mode = TUPLOCK_from_mxstatus(status);
    bool        old_isupd = ISUPDATE_from_mxstatus(status);

    /*
     * We can do this if the new LockTupleMode is higher or equal than
     * the old one; and if there was previously an update, we need an
     * update, but if there wasn't, then we can accept there not being
     * one.
     */
    if ((mode >= old_mode) && (is_update || !old_isupd))
    {
        /*
         * Note that the infomask might contain some other dirty bits.
         * However, since the new infomask is reset to zero, we only
         * set what's minimally necessary, and that the case that
         * checks HEAP_XMAX_INVALID is the very first above, there is
         * no need for extra cleanup of the infomask here.
         */
        old_infomask |= HEAP_XMAX_INVALID;
        goto l5;
    }
}

Several things:
a) If the old lockmode is stronger than the new one, we can just promote
   the new one. That's fine.
b) the old xmax cannot be an update, we wouldn't see the row version in that
   case. And in any way, ISUPDATE_from_mxstatus() isn't sufficient to
   determine whether the old row was an update, one needs to look at
   LOCK_ONLY as well, no?
c) Any reason we can't apply this optimization for subtransactions in
   some scenarios?

a), b) are relatively easy. Patch attached. Being a clear regression, I
think it should be backpatched, but I'm not sure if it has to be this
point release. It's simple enough, but ...

The reason we didn't hit the (mode == old_mode && is_update) case above
is that the UPDATE uses only LockTupleNoKeyExclusive since there are no
keys, but FOR UPDATE was used before.

I am not awake enough to think about c) and it seems somewhat
more complicated. I think we can only optimize it if the previous lock
was in a subcommited subtransaction and not if it's a transaction higher
up the chain.

On the note of superflous MultiXactIdCreate() calls, the latter contains
the following assert:
   Assert(!TransactionIdEquals(xid1, xid2) || (status1 != status2));
Is there any reason we *ever* should add two times the same xid? Afaics
there's several code paths to get there today, but imo we should work
towards that never happening.

Greetings,

Andres Freund

-- 
 Andres Freund	                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments:

0001-Avoid-MultiXacts-in-more-situations-when-updating-a-.patch (text/x-patch, 3.2K) download From 4c7fda01078c368478fbc1ffa916e689cc61ef91 Mon Sep 17 00:00:00 2001 From: Andres Freund <andres@anarazel.de> Date: Sun, 1 Dec 2013 12:32:59 +0100 Subject: [PATCH] Avoid MultiXacts in more situations when updating a previously locked row. Since the introduction of the foreign key locking feature, when updating a row previously locked in the same transaction, we generated a MultiXact when the new lock was weaker than the old one. This could easily happen in applications using explicit FOR UPDATE clauses before UPDATEing, since an UPDATE now often only uses the NO KEY UPDATE lock level. To do so, simply promote the new lock to the old, stronger, lock level when computing the new infomask for the updated tuple. --- src/backend/access/heap/heapam.c | 42 +++++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 20 deletions(-) diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c index c13f87c..c03ff80 100644 --- a/src/backend/access/heap/heapam.c +++ b/src/backend/access/heap/heapam.c @@ -4725,33 +4725,35 @@ l5: new_status = get_mxact_status_for_lock(mode, is_update); /* - * If the existing lock mode is identical to or weaker than the new - * one, we can act as though there is no existing lock, so set - * XMAX_INVALID and restart. + * Already locked by the current transaction, so we can take a + * shortcut: If the existing lock mode is identical to or weaker than + * the new one, we can act as though there is no existing lock. If the + * old lock mode is stronger than the new one, we just promote the new + * lock mode. To do so, set XMAX_INVALID and restart. */ if (xmax == add_to_xmax) { LockTupleMode old_mode = TUPLOCK_from_mxstatus(status); - bool old_isupd = ISUPDATE_from_mxstatus(status); /* - * We can do this if the new LockTupleMode is higher or equal than - * the old one; and if there was previously an update, we need an - * update, but if there wasn't, then we can accept there not being - * one. + * The old xmax cannot not be an update, since otherwise this row + * version would have been invisible. */ - if ((mode >= old_mode) && (is_update || !old_isupd)) - { - /* - * Note that the infomask might contain some other dirty bits. - * However, since the new infomask is reset to zero, we only - * set what's minimally necessary, and that the case that - * checks HEAP_XMAX_INVALID is the very first above, there is - * no need for extra cleanup of the infomask here. - */ - old_infomask |= HEAP_XMAX_INVALID; - goto l5; - } + Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)); + + /* Promote lockmode if necessary. */ + if (mode < old_mode) + mode = old_mode; + + /* + * Note that the infomask might contain some other dirty bits. + * However, since the new infomask is reset to zero, we only set + * what's minimally necessary. The case that checks + * HEAP_XMAX_INVALID is the very first above, there is no need for + * extra cleanup of the infomask here. + */ + old_infomask |= HEAP_XMAX_INVALID; + goto l5; } new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status); GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2); -- 1.8.3.251.g1462b67
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 08:19       ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 11:45         ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
@ 2013-12-01 11:53           ` Andres Freund <andres@2ndquadrant.com>
  1 sibling, 0 replies; 24+ messages in thread

From: Andres Freund @ 2013-12-01 11:53 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

On 2013-12-01 12:45:14 +0100, Andres Freund wrote:
> b) the old xmax cannot be an update, we wouldn't see the row version in that
>    case. And in any way, ISUPDATE_from_mxstatus() isn't sufficient to
>    determine whether the old row was an update, one needs to look at
>    LOCK_ONLY as well, no?

That part's bogus, I missed part of the branch above the quoted code.

Greetings,

Andres Freund

-- 
 Andres Freund	                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 08:19       ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 11:45         ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
@ 2013-12-18 22:13           ` Alvaro Herrera <alvherre@2ndquadrant.com>
  2013-12-18 22:39             ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  1 sibling, 1 reply; 24+ messages in thread

From: Alvaro Herrera @ 2013-12-18 22:13 UTC (permalink / raw)
  To: Andres Freund <andres@2ndquadrant.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

Andres Freund escribió:

> Several things:
> a) If the old lockmode is stronger than the new one, we can just promote
>    the new one. That's fine.
> b) the old xmax cannot be an update, we wouldn't see the row version in that
>    case. And in any way, ISUPDATE_from_mxstatus() isn't sufficient to
>    determine whether the old row was an update, one needs to look at
>    LOCK_ONLY as well, no?
> c) Any reason we can't apply this optimization for subtransactions in
>    some scenarios?
> 
> a), b) are relatively easy. Patch attached. Being a clear regression, I
> think it should be backpatched, but I'm not sure if it has to be this
> point release. It's simple enough, but ...

Nice idea.  I modified the patch slightly, please see attached.

I'm not sure about the added assert that the tuple cannot possibly be
locked.  I fear cursors provide strange ways to access at tuples.  I
haven't been able to reproduce a problem but consider an example such as
the one below.  Is it possible, I wonder, to arrive at the problematic
scenario considering that we might try to traverse an update chain to
lock future versions of the tuple?  I suspect not, because if the tuple
was updated (so that there is an update chain to traverse in the first
place) then we wouldn't be able to update the original anyway.  (I guess
I'm mainly talking to myself to assure me that there's no real problem
here.)

In any case I think it's easy to handle the case by doing something like
	is_update |= ISUPDATE_from_mxstatus(old_status);
and remove the Assert().


alvherre=# create table f (a int primary key, b text);
CREATE TABLE
alvherre=# insert into f values (1, 'one');
INSERT 0 1

alvherre=# begin;
BEGIN
alvherre=# select * from f for update;
 a |   b   
---+-------
 1 | three
(1 fila)

alvherre=# declare f cursor for select * from f;
DECLARE CURSOR
alvherre=# fetch 1 from f;
 a |   b   
---+-------
 1 | three
(1 fila)

alvherre=# update f set b = 'two';
UPDATE 1
alvherre=# move backward all from f;
MOVE 0
alvherre=# fetch 1 from f;
 a |   b   
---+-------
 1 | three
(1 fila)

alvherre=# update f set b = 'four' where current of f;
UPDATE 1
alvherre=# select * from f;
 a |  b   
---+------
 1 | four
(1 fila)

alvherre=# commit;

-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments:

0001-Optimize-updating-a-row-that-s-locked-by-same-xact.patch (text/x-diff, 3.9K) download From 04004c045204e1dcf1ce0125a890423bbefe9ae4 Mon Sep 17 00:00:00 2001 From: Alvaro Herrera <alvherre@alvh.no-ip.org> Date: Wed, 18 Dec 2013 18:26:57 -0300 Subject: [PATCH] Optimize updating a row that's locked by same xact MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Updating or locking a row that was already locked by the same transaction caused a MultiXact to be created; but this is unnecessary, because there's no usefulness in being able to differentiate two locks by the same transaction. In particular, if an application does SELECT FOR UPDATE followed by an UPDATE that does not modify columns of the key, we would represent this as a multixact. Optimize the case so that only the strongest of both locks/updates is represented in Xmax. This can save some operations from acquiring MultiXacts, which is a significant optimization. This missed optimization opportunity was spotted by Andres Freund while investigating a bug reported by Oliver Seemann in message CANCipfpfzoYnOz5jj=UZ70_R=CwDHv36dqWSpwsi27vpm1z5sA@mail.gmail.com and also directly as a performance regression reported by Dong Ye in message d54b8387.000012d8.00000010@YED-DEVD1.vmware.com Reportedly, this patch fixes the performance regression. Andres Freund, tweaked by Álvaro Herrera --- src/backend/access/heap/heapam.c | 45 +++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c index 70748e5..6b78783 100644 --- a/src/backend/access/heap/heapam.c +++ b/src/backend/access/heap/heapam.c @@ -4541,6 +4541,11 @@ l5: { /* * No previous locker; we just insert our own TransactionId. + * + * Note that it's critical that this case be the first one checked, + * because there are several blocks below that come back to this one + * to implement certain optimizations; old_infomask might contain + * other dirty bits in those cases, but we don't really care. */ if (is_update) { @@ -4705,37 +4710,30 @@ l5: status = MultiXactStatusNoKeyUpdate; } - new_status = get_mxact_status_for_lock(mode, is_update); - /* - * If the existing lock mode is identical to or weaker than the new - * one, we can act as though there is no existing lock, so set - * XMAX_INVALID and restart. + * If the lock to be acquired is from the same transaction as the + * existing lock, there's an additional optimization: consider only + * the strongest of both locks as the only one present, and restart. */ if (xmax == add_to_xmax) { LockTupleMode old_mode = TUPLOCK_from_mxstatus(status); - bool old_isupd = ISUPDATE_from_mxstatus(status); /* - * We can do this if the new LockTupleMode is higher or equal than - * the old one; and if there was previously an update, we need an - * update, but if there wasn't, then we can accept there not being - * one. + * The old xmax cannot possibly be an update, since otherwise this + * row version would have been invisible. */ - if ((mode >= old_mode) && (is_update || !old_isupd)) - { - /* - * Note that the infomask might contain some other dirty bits. - * However, since the new infomask is reset to zero, we only - * set what's minimally necessary, and that the case that - * checks HEAP_XMAX_INVALID is the very first above, there is - * no need for extra cleanup of the infomask here. - */ - old_infomask |= HEAP_XMAX_INVALID; - goto l5; - } + Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)); + + /* acquire the strongest of both */ + if (mode < old_mode) + mode = old_mode; + + old_infomask |= HEAP_XMAX_INVALID; + goto l5; } + + new_status = get_mxact_status_for_lock(mode, is_update); new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status); GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2); } -- 1.7.10.4
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 08:19       ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 11:45         ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-18 22:13           ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
@ 2013-12-18 22:39             ` Andres Freund <andres@2ndquadrant.com>
  2013-12-19 00:58               ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  0 siblings, 1 reply; 24+ messages in thread

From: Andres Freund @ 2013-12-18 22:39 UTC (permalink / raw)
  To: Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

On 2013-12-18 19:13:43 -0300, Alvaro Herrera wrote:
> I'm not sure about the added assert that the tuple cannot possibly be
> locked.  I fear cursors provide strange ways to access at tuples.

I don't see how, the EPQ machinery should have ensured we're looking at
the most recent version. Also, pretty fundamentally, we have to be the
only locker, otherwise the optimization wouldn't be applicable in this
way.

> In any case I think it's easy to handle the case by doing something like
> 	is_update |= ISUPDATE_from_mxstatus(old_status);
> and remove the Assert().

I think I'd rather have the chance to see the pathway to that, than try
to handle it. I think we have pretty little chance of doing so correctly
if we don't know how it can happen.

Greetings,

Andres Freund

-- 
 Andres Freund	                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 08:19       ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 11:45         ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-18 22:13           ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  2013-12-18 22:39             ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
@ 2013-12-19 00:58               ` Alvaro Herrera <alvherre@2ndquadrant.com>
  2013-12-19 15:58                 ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  0 siblings, 1 reply; 24+ messages in thread

From: Alvaro Herrera @ 2013-12-19 00:58 UTC (permalink / raw)
  To: Andres Freund <andres@2ndquadrant.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

Andres Freund escribió:
> On 2013-12-18 19:13:43 -0300, Alvaro Herrera wrote:
> > I'm not sure about the added assert that the tuple cannot possibly be
> > locked.  I fear cursors provide strange ways to access at tuples.
> 
> I don't see how, the EPQ machinery should have ensured we're looking at
> the most recent version. Also, pretty fundamentally, we have to be the
> only locker, otherwise the optimization wouldn't be applicable in this
> way.

EPQ works funny with cursors in the WHERE CURRENT OF stuff; the fact
that it behaves differently in FOR UPDATE case than when there's no
locking clause makes this whole thing pretty misterious.

Anyway I think this whole optimization can be formulated more clearly if
we separate the case into its own block by checking
XidIsCurrentTransaction instead of cramming it into the XidIsInProgress
case as the original is doing; see attached.

Any ideas on possible tests for this stuff?  Nothing comes to mind that
doesn't involve pageinspect ...
 
-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments:

0001-Optimize-updating-a-row-that-s-locked-by-same-xact.patch (text/x-diff, 4.7K) download From e0520c881bea653e33d9b5ef5bff065840ebacb5 Mon Sep 17 00:00:00 2001 From: Alvaro Herrera <alvherre@alvh.no-ip.org> Date: Wed, 18 Dec 2013 21:51:41 -0300 Subject: [PATCH] Optimize updating a row that's locked by same xact MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Updating or locking a row that was already locked by the same transaction caused a MultiXact to be created; but this is unnecessary, because there's no usefulness in being able to differentiate two locks by the same transaction. In particular, if an application does SELECT FOR UPDATE followed by an UPDATE that does not modify columns of the key, we would represent this as a multixact. Optimize the case so that only the strongest of both locks/updates is represented in Xmax. This can save some operations from acquiring MultiXacts, which is a significant optimization. This missed optimization opportunity was spotted by Andres Freund while investigating a bug reported by Oliver Seemann in message CANCipfpfzoYnOz5jj=UZ70_R=CwDHv36dqWSpwsi27vpm1z5sA@mail.gmail.com and also directly as a performance regression reported by Dong Ye in message d54b8387.000012d8.00000010@YED-DEVD1.vmware.com Reportedly, this patch fixes the performance regression. Andres Freund, tweaked by Álvaro Herrera --- src/backend/access/heap/heapam.c | 64 ++++++++++++++++++++------------------ 1 file changed, 34 insertions(+), 30 deletions(-) diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c index 70748e5..023db6a 100644 --- a/src/backend/access/heap/heapam.c +++ b/src/backend/access/heap/heapam.c @@ -4541,6 +4541,11 @@ l5: { /* * No previous locker; we just insert our own TransactionId. + * + * Note that it's critical that this case be the first one checked, + * because there are several blocks below that come back to this one + * to implement certain optimizations; old_infomask might contain + * other dirty bits in those cases, but we don't really care. */ if (is_update) { @@ -4659,6 +4664,33 @@ l5: new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status); GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2); } + else if (xmax == add_to_xmax && TransactionIdIsCurrentTransactionId(xmax)) + + { + LockTupleMode old_mode = TUPLOCK_from_mxstatus(status); + + /* + * If the lock to be acquired is from the same transaction as the + * existing lock, there's an additional optimization: consider only + * the strongest of both locks as the only one present, and restart. + * + * Note that it's not possible for the original tuple to be updated: + * we wouldn't be here because the tuple would have been invisible and + * we wouldn't try to update it. As a subtlety, this code can also + * run when traversing an update chain to lock future versions of a + * tuple. But we wouldn't be here either, because the add_to_xmax + * would be different from the original updater. + */ + Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)); + + /* acquire the strongest of both */ + if (mode < old_mode) + mode = old_mode; + /* don't need to touch is_update */ + + old_infomask |= HEAP_XMAX_INVALID; + goto l5; + } else if (TransactionIdIsInProgress(xmax)) { /* @@ -4669,6 +4701,8 @@ l5: MultiXactStatus status; MultiXactStatus new_status; + Assert(xmax != add_to_xmax); + if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)) { if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask)) @@ -4706,36 +4740,6 @@ l5: } new_status = get_mxact_status_for_lock(mode, is_update); - - /* - * If the existing lock mode is identical to or weaker than the new - * one, we can act as though there is no existing lock, so set - * XMAX_INVALID and restart. - */ - if (xmax == add_to_xmax) - { - LockTupleMode old_mode = TUPLOCK_from_mxstatus(status); - bool old_isupd = ISUPDATE_from_mxstatus(status); - - /* - * We can do this if the new LockTupleMode is higher or equal than - * the old one; and if there was previously an update, we need an - * update, but if there wasn't, then we can accept there not being - * one. - */ - if ((mode >= old_mode) && (is_update || !old_isupd)) - { - /* - * Note that the infomask might contain some other dirty bits. - * However, since the new infomask is reset to zero, we only - * set what's minimally necessary, and that the case that - * checks HEAP_XMAX_INVALID is the very first above, there is - * no need for extra cleanup of the infomask here. - */ - old_infomask |= HEAP_XMAX_INVALID; - goto l5; - } - } new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status); GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2); } -- 1.7.10.4
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 08:19       ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 11:45         ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-18 22:13           ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  2013-12-18 22:39             ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-19 00:58               ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
@ 2013-12-19 15:58                 ` Alvaro Herrera <alvherre@2ndquadrant.com>
  2013-12-20 02:44                   ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  0 siblings, 1 reply; 24+ messages in thread

From: Alvaro Herrera @ 2013-12-19 15:58 UTC (permalink / raw)
  To: Andres Freund <andres@2ndquadrant.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

Actually, the original coding is better because it enables easier
writing of other optimizations, such as in the attached which should
also cure the performance regression noted in bug #8470.

-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments:

multixact-optimize.patch (text/x-diff, 8.7K) download diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c index 023db6a..2d6f57d 100644 --- a/src/backend/access/heap/heapam.c +++ b/src/backend/access/heap/heapam.c @@ -4534,6 +4534,8 @@ compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask, uint16 new_infomask, new_infomask2; + Assert(TransactionIdIsCurrentTransactionId(add_to_xmax)); + l5: new_infomask = 0; new_infomask2 = 0; @@ -4584,6 +4586,9 @@ l5: else if (old_infomask & HEAP_XMAX_IS_MULTI) { MultiXactStatus new_status; + MultiXactMember *members; + int nmembers; + bool keepmulti = false; /* * Currently we don't allow XMAX_COMMITTED to be set for multis, so @@ -4607,37 +4612,70 @@ l5: } /* - * If the XMAX is already a MultiXactId, then we need to expand it to - * include add_to_xmax; but if all the members were lockers and are - * all gone, we can do away with the IS_MULTI bit and just set - * add_to_xmax as the only locker/updater. If all lockers are gone - * and we have an updater that aborted, we can also do without a - * multi. - * - * The cost of doing GetMultiXactIdMembers would be paid by - * MultiXactIdExpand if we weren't to do this, so this check is not - * incurring extra work anyhow. + * Examine the Multixact members. If any of them is the current + * transaction and holds a lock at least as strong as we are + * requesting, then the lock request can be satisfied with the + * existing MultiXactId; there's no need to create a new one. */ - if (!MultiXactIdIsRunning(xmax)) + nmembers = GetMultiXactIdMembers(xmax, &members, true); + if (nmembers > 0) { - if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) || - TransactionIdDidAbort(MultiXactIdGetUpdateXid(xmax, - old_infomask))) + int i; + + for (i = 0; i < nmembers; i++) { - /* - * Reset these bits and restart; otherwise fall through to - * create a new multi below. - */ - old_infomask &= ~HEAP_XMAX_IS_MULTI; - old_infomask |= HEAP_XMAX_INVALID; - goto l5; + if (TransactionIdIsCurrentTransactionId(members[i].xid) && + (TUPLOCK_from_mxstatus(members[i].status) >= mode) && + (!is_update || ISUPDATE_from_mxstatus(members[i].status))) + { + keepmulti = true; + break; + } } + pfree(members); } - new_status = get_mxact_status_for_lock(mode, is_update); + if (keepmulti) + { + new_status = get_mxact_status_for_lock(mode, is_update); + new_xmax = xmax; + } + else + { + /* + * If the XMAX is already a MultiXactId, then we need to expand it + * to include add_to_xmax; but if all the members were lockers and + * are all gone, we can do away with the IS_MULTI bit and just set + * add_to_xmax as the only locker/updater. If all lockers are + * gone and we have an updater that aborted, we can also do + * without a multi. + * + * The cost of doing GetMultiXactIdMembers would be paid by + * MultiXactIdExpand if we weren't to do this, so this check is + * not incurring extra work anyhow. + */ + if (!MultiXactIdIsRunning(xmax)) + { + if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) || + TransactionIdDidAbort(MultiXactIdGetUpdateXid(xmax, + old_infomask))) + { + /* + * Reset these bits and restart; otherwise fall through to + * create a new multi below. + */ + old_infomask &= ~HEAP_XMAX_IS_MULTI; + old_infomask |= HEAP_XMAX_INVALID; + goto l5; + } + } + + new_status = get_mxact_status_for_lock(mode, is_update); + + new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax, + new_status); + } - new_xmax = MultiXactIdExpand((MultiXactId) xmax, add_to_xmax, - new_status); GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2); } else if (old_infomask & HEAP_XMAX_COMMITTED) @@ -4664,33 +4702,6 @@ l5: new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status); GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2); } - else if (xmax == add_to_xmax && TransactionIdIsCurrentTransactionId(xmax)) - - { - LockTupleMode old_mode = TUPLOCK_from_mxstatus(status); - - /* - * If the lock to be acquired is from the same transaction as the - * existing lock, there's an additional optimization: consider only - * the strongest of both locks as the only one present, and restart. - * - * Note that it's not possible for the original tuple to be updated: - * we wouldn't be here because the tuple would have been invisible and - * we wouldn't try to update it. As a subtlety, this code can also - * run when traversing an update chain to lock future versions of a - * tuple. But we wouldn't be here either, because the add_to_xmax - * would be different from the original updater. - */ - Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)); - - /* acquire the strongest of both */ - if (mode < old_mode) - mode = old_mode; - /* don't need to touch is_update */ - - old_infomask |= HEAP_XMAX_INVALID; - goto l5; - } else if (TransactionIdIsInProgress(xmax)) { /* @@ -4698,23 +4709,22 @@ l5: * create a new MultiXactId that includes both the old locker or * updater and our own TransactionId. */ - MultiXactStatus status; MultiXactStatus new_status; - - Assert(xmax != add_to_xmax); + MultiXactStatus old_status; + LockTupleMode old_mode; if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)) { if (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask)) - status = MultiXactStatusForKeyShare; + old_status = MultiXactStatusForKeyShare; else if (HEAP_XMAX_IS_SHR_LOCKED(old_infomask)) - status = MultiXactStatusForShare; + old_status = MultiXactStatusForShare; else if (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask)) { if (old_infomask2 & HEAP_KEYS_UPDATED) - status = MultiXactStatusForUpdate; + old_status = MultiXactStatusForUpdate; else - status = MultiXactStatusForNoKeyUpdate; + old_status = MultiXactStatusForNoKeyUpdate; } else { @@ -4734,13 +4744,72 @@ l5: { /* it's an update, but which kind? */ if (old_infomask2 & HEAP_KEYS_UPDATED) - status = MultiXactStatusUpdate; + old_status = MultiXactStatusUpdate; else - status = MultiXactStatusNoKeyUpdate; + old_status = MultiXactStatusNoKeyUpdate; } + old_mode = TUPLOCK_from_mxstatus(old_status); + + /* + * If the lock to be acquired is for the same TransactionId as the + * existing lock, there's an optimization possible: consider only the + * strongest of both locks as the only one present, and restart. + */ + if (xmax == add_to_xmax) + { + /* + * Note that it's not possible for the original tuple to be updated: + * we wouldn't be here because the tuple would have been invisible and + * we wouldn't try to update it. As a subtlety, this code can also + * run when traversing an update chain to lock future versions of a + * tuple. But we wouldn't be here either, because the add_to_xmax + * would be different from the original updater. + */ + Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)); + + /* acquire the strongest of both */ + if (mode < old_mode) + mode = old_mode; + /* musn't touch is_update */ + + old_infomask |= HEAP_XMAX_INVALID; + goto l5; + } + + /* + * Another possibility is that xmax is not identical to add_to_xmax, + * but that it is an ancestor. We can simply piggy-back on the + * existing lock, without requiring that a new lock be taken. In this + * case, we require the lock mode being requested to be equal or + * weaker than the original; no upgrading of mode is allowed. + * (otherwise, a third party wanting to acquire a lock that conflicts + * with the stronger new lock but not with the old one would not be + * released if the new subtransaction aborts). + * + * To implement this, make it appear that there is no existing lock, + * and re-request what was present. + * + * Since we know add_to_xmax is the current transaction, then xmax is + * an ancestor of add_to_xmax if it is also a current transaction Id. + */ + if (TransactionIdIsCurrentTransactionId(xmax) && old_mode >= mode) + { + /* as above, the tuple cannot possibly be updated */ + Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)); + + add_to_xmax = xmax; + /* acquire the strongest of both */ + mode = old_mode; + /* musn't touch is_update */ + old_infomask |= HEAP_XMAX_INVALID; + goto l5; + } + + /* otherwise, just fall back to creating a new multixact */ new_status = get_mxact_status_for_lock(mode, is_update); - new_xmax = MultiXactIdCreate(xmax, status, add_to_xmax, new_status); + new_xmax = MultiXactIdCreate(xmax, old_status, + add_to_xmax, new_status); GetMultiXactIdHintBits(new_xmax, &new_infomask, &new_infomask2); } else if (!HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) &&
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 08:19       ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 11:45         ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-18 22:13           ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  2013-12-18 22:39             ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-19 00:58               ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  2013-12-19 15:58                 ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
@ 2013-12-20 02:44                   ` Alvaro Herrera <alvherre@2ndquadrant.com>
  2014-02-05 14:22                     ` Re: Update with subselect sometimes returns wrong result Robert Haas <robertmhaas@gmail.com>
  0 siblings, 1 reply; 24+ messages in thread

From: Alvaro Herrera @ 2013-12-20 02:44 UTC (permalink / raw)
  To: Andres Freund <andres@2ndquadrant.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

Alvaro Herrera escribió:
> Actually, the original coding is better because it enables easier
> writing of other optimizations, such as in the attached which should
> also cure the performance regression noted in bug #8470.

While trying to apply the second bit of this patch (where we try to skip
acquiring a lock that an ancestor subxact already holds), I noticed that
it doesn't work at all; moreover, the whole idea of locking a tuple
twice by another subaxt of the same transaction doesn't work. For
example:

BEGIN;
SELECT tuple FOR NO KEY UPDATE;
SAVEPOINT f;
SELECT tuple FOR UPDATE;
...

This fails to acquire the second lock completely; only the NO KEY UPDATE
lock is stored in the tuple.  The reason this happens is that
HeapTupleSatisfiesUpdate returns MayBeUpdated if the Xmax is a plain Xid
LOCK_ONLY by our own transaction.  We already commented in some other
thread that maybe we should change this bit of HTSU behavior; but when I
tried to do so to enable this optimization, I found that other routines
die while trying to apply XactLockTableWait to the current transaction.
This sorta makes sense --- it means that if we want to change this, we
will need further surgery to callers of HTSU.

There's another problem which is that this optimization would be
applicable to locks only, not updates.  Given this limitation I think it
would be rather pointless to try to do this.

I will keep working at the other part, involving multixacts.

-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 08:19       ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 11:45         ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-18 22:13           ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  2013-12-18 22:39             ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-19 00:58               ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  2013-12-19 15:58                 ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  2013-12-20 02:44                   ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
@ 2014-02-05 14:22                     ` Robert Haas <robertmhaas@gmail.com>
  2014-02-05 15:39                       ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  0 siblings, 1 reply; 24+ messages in thread

From: Robert Haas @ 2014-02-05 14:22 UTC (permalink / raw)
  To: Alvaro Herrera <alvherre@2ndquadrant.com>; +Cc: Andres Freund <andres@2ndquadrant.com>; Tom Lane <tgl@sss.pgh.pa.us>; Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

On Thu, Dec 19, 2013 at 9:44 PM, Alvaro Herrera
<alvherre@2ndquadrant.com> wrote:
> Alvaro Herrera escribió:
>> Actually, the original coding is better because it enables easier
>> writing of other optimizations, such as in the attached which should
>> also cure the performance regression noted in bug #8470.
>
> While trying to apply the second bit of this patch (where we try to skip
> acquiring a lock that an ancestor subxact already holds), I noticed that
> it doesn't work at all; moreover, the whole idea of locking a tuple
> twice by another subaxt of the same transaction doesn't work. For
> example:
>
> BEGIN;
> SELECT tuple FOR NO KEY UPDATE;
> SAVEPOINT f;
> SELECT tuple FOR UPDATE;
> ...
>
> This fails to acquire the second lock completely; only the NO KEY UPDATE
> lock is stored in the tuple.  The reason this happens is that
> HeapTupleSatisfiesUpdate returns MayBeUpdated if the Xmax is a plain Xid
> LOCK_ONLY by our own transaction.  We already commented in some other
> thread that maybe we should change this bit of HTSU behavior; but when I
> tried to do so to enable this optimization, I found that other routines
> die while trying to apply XactLockTableWait to the current transaction.
> This sorta makes sense --- it means that if we want to change this, we
> will need further surgery to callers of HTSU.
>
> There's another problem which is that this optimization would be
> applicable to locks only, not updates.  Given this limitation I think it
> would be rather pointless to try to do this.
>
> I will keep working at the other part, involving multixacts.

Did anything come of this?

-- 
Robert Haas
EnterpriseDB: http://www.enterprisedb.com
The Enterprise PostgreSQL Company


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-11-30 17:57 ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-11-30 21:40   ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 06:41     ` Re: Update with subselect sometimes returns wrong result Tom Lane <tgl@sss.pgh.pa.us>
  2013-12-01 08:19       ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-01 11:45         ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-18 22:13           ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  2013-12-18 22:39             ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-19 00:58               ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  2013-12-19 15:58                 ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  2013-12-20 02:44                   ` Re: Update with subselect sometimes returns wrong result Alvaro Herrera <alvherre@2ndquadrant.com>
  2014-02-05 14:22                     ` Re: Update with subselect sometimes returns wrong result Robert Haas <robertmhaas@gmail.com>
@ 2014-02-05 15:39                       ` Alvaro Herrera <alvherre@2ndquadrant.com>
  0 siblings, 0 replies; 24+ messages in thread

From: Alvaro Herrera @ 2014-02-05 15:39 UTC (permalink / raw)
  To: Robert Haas <robertmhaas@gmail.com>; +Cc: Andres Freund <andres@2ndquadrant.com>; Tom Lane <tgl@sss.pgh.pa.us>; Oliver Seemann <oseemann@gmail.com>; pgsql-bugs

Robert Haas escribió:
> On Thu, Dec 19, 2013 at 9:44 PM, Alvaro Herrera
> <alvherre@2ndquadrant.com> wrote:
> > Alvaro Herrera escribió:
> >> Actually, the original coding is better because it enables easier
> >> writing of other optimizations, such as in the attached which should
> >> also cure the performance regression noted in bug #8470.
> >
> > While trying to apply the second bit of this patch (where we try to skip
> > acquiring a lock that an ancestor subxact already holds), I noticed that
> > it doesn't work at all; moreover, the whole idea of locking a tuple
> > twice by another subaxt of the same transaction doesn't work. For
> > example:
> >
> > BEGIN;
> > SELECT tuple FOR NO KEY UPDATE;
> > SAVEPOINT f;
> > SELECT tuple FOR UPDATE;
> > ...
> >
> > This fails to acquire the second lock completely; only the NO KEY UPDATE
> > lock is stored in the tuple.  The reason this happens is that
> > HeapTupleSatisfiesUpdate returns MayBeUpdated if the Xmax is a plain Xid
> > LOCK_ONLY by our own transaction.  We already commented in some other
> > thread that maybe we should change this bit of HTSU behavior; but when I
> > tried to do so to enable this optimization, I found that other routines
> > die while trying to apply XactLockTableWait to the current transaction.
> > This sorta makes sense --- it means that if we want to change this, we
> > will need further surgery to callers of HTSU.
> >
> > There's another problem which is that this optimization would be
> > applicable to locks only, not updates.  Given this limitation I think it
> > would be rather pointless to try to do this.
> >
> > I will keep working at the other part, involving multixacts.
> 
> Did anything come of this?

I have paged out the details of all this stuff by now, but (as quoted
above) this is closely related to bug #8470.  I had a patch which was
supposed to fix the performance problem, but at some point I noticed
that there was a serious problem with it, so I put it aside.  (Of
course, there was also the small matter that I needed to focus on other
patches.) Now that I skim that patch again, I *think* there's a portion
of it that should be applied to 9.3 and HEAD.

I see that in bug #8470's thread I didn't post the latest version I had.
This is it (including the serious problem I mentioned above, which is
related to acquiring a lock we already own in a previos subxact, i.e.
more or less exactly the case we're trying to optimize.)

-- 
Álvaro Herrera                http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training & Services

-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs

Attachments:

optimize-bug-8470.patch (text/x-diff, 36.6K) download *** a/contrib/pgrowlocks/pgrowlocks.c --- b/contrib/pgrowlocks/pgrowlocks.c *************** *** 138,151 **** pgrowlocks(PG_FUNCTION_ARGS) infomask = tuple->t_data->t_infomask; /* ! * a tuple is locked if HTSU returns BeingUpdated, and if it returns ! * MayBeUpdated but the Xmax is valid and pointing at us. */ ! if (htsu == HeapTupleBeingUpdated || ! (htsu == HeapTupleMayBeUpdated && ! !(infomask & HEAP_XMAX_INVALID) && ! !(infomask & HEAP_XMAX_IS_MULTI) && ! (xmax == GetCurrentTransactionIdIfAny()))) { char **values; --- 138,146 ---- infomask = tuple->t_data->t_infomask; /* ! * A tuple is locked if HTSU returns BeingUpdated. */ ! if (htsu == HeapTupleBeingUpdated) { char **values; *** a/src/backend/access/heap/heapam.c --- b/src/backend/access/heap/heapam.c *************** *** 2596,2672 **** l1: TransactionId xwait; uint16 infomask; - /* must copy state data before unlocking buffer */ - xwait = HeapTupleHeaderGetRawXmax(tp.t_data); - infomask = tp.t_data->t_infomask; - - LockBuffer(buffer, BUFFER_LOCK_UNLOCK); - /* ! * Acquire tuple lock to establish our priority for the tuple (see ! * heap_lock_tuple). LockTuple will release us when we are ! * next-in-line for the tuple. * ! * If we are forced to "start over" below, we keep the tuple lock; ! * this arranges that we stay at the head of the line while rechecking ! * tuple state. */ ! if (!have_tuple_lock) { ! LockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive); ! have_tuple_lock = true; } ! ! /* ! * Sleep until concurrent transaction ends. Note that we don't care ! * which lock mode the locker has, because we need the strongest one. ! */ ! ! if (infomask & HEAP_XMAX_IS_MULTI) { ! /* wait for multixact */ ! MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, ! NULL, infomask); ! LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE); ! /* ! * If xwait had just locked the tuple then some other xact could ! * update this tuple before we get to this point. Check for xmax ! * change, and start over if so. ! */ ! if (!(tp.t_data->t_infomask & HEAP_XMAX_IS_MULTI) || ! !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data), ! xwait)) ! goto l1; /* ! * You might think the multixact is necessarily done here, but not ! * so: it could have surviving members, namely our own xact or ! * other subxacts of this backend. It is legal for us to delete ! * the tuple in either case, however (the latter case is ! * essentially a situation of upgrading our former shared lock to ! * exclusive). We don't bother changing the on-disk hint bits ! * since we are about to overwrite the xmax altogether. */ ! } ! else ! { ! /* wait for regular transaction to end */ ! XactLockTableWait(xwait); ! LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE); /* ! * xwait is done, but if xwait had just locked the tuple then some ! * other xact could update this tuple before we get to this point. ! * Check for xmax change, and start over if so. */ - if ((tp.t_data->t_infomask & HEAP_XMAX_IS_MULTI) || - !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data), - xwait)) - goto l1; ! /* Otherwise check if it committed or aborted */ ! UpdateXmaxHintBits(tp.t_data, buffer, xwait); } /* --- 2596,2697 ---- TransactionId xwait; uint16 infomask; /* ! * If any subtransaction of the current top transaction already holds ! * a lock on this tuple, (and no one else does,) we must skip sleeping ! * on the xwait; that would lead to us sleeping on our own ! * transaction, which is unlikely to end up well. * ! * Note we don't need to do anything about this when the xwait is a ! * multixact, because that code is already prepared to ignore ! * subtransactions of the current top transaction. ! * ! * This must be done before acquiring our tuple lock, to avoid ! * deadlocks with other transaction that are already waiting on the ! * lock we hold. */ ! if (!(tp.t_data->t_infomask & HEAP_XMAX_IS_MULTI) && ! TransactionIdIsCurrentTransactionId( ! HeapTupleHeaderGetRawXmax(tp.t_data))) { ! Assert(HEAP_XMAX_IS_LOCKED_ONLY(tp.t_data->t_infomask)); } ! else { ! /* must copy state data before unlocking buffer */ ! xwait = HeapTupleHeaderGetRawXmax(tp.t_data); ! infomask = tp.t_data->t_infomask; ! LockBuffer(buffer, BUFFER_LOCK_UNLOCK); /* ! * Acquire tuple lock to establish our priority for the tuple (see ! * heap_lock_tuple). LockTuple will release us when we are ! * next-in-line for the tuple. ! * ! * If we are forced to "start over" below, we keep the tuple lock; ! * this arranges that we stay at the head of the line while ! * rechecking tuple state. */ ! if (!have_tuple_lock) ! { ! LockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive); ! have_tuple_lock = true; ! } /* ! * Sleep until concurrent transaction ends. Note that we don't ! * care which lock mode the locker has, because we need the ! * strongest one. */ ! if (infomask & HEAP_XMAX_IS_MULTI) ! { ! /* wait for multixact */ ! MultiXactIdWait((MultiXactId) xwait, MultiXactStatusUpdate, ! NULL, infomask); ! LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE); ! ! /* ! * If xwait had just locked the tuple then some other xact ! * could update this tuple before we get to this point. Check ! * for xmax change, and start over if so. ! */ ! if (!(tp.t_data->t_infomask & HEAP_XMAX_IS_MULTI) || ! !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data), ! xwait)) ! goto l1; ! ! /* ! * You might think the multixact is necessarily done here, but ! * not so: it could have surviving members, namely our own ! * xact or other subxacts of this backend. It is legal for ! * us to delete the tuple in either case, however (the latter ! * case is essentially a situation of upgrading our former ! * shared lock to exclusive). We don't bother changing the ! * on-disk hint bits since we are about to overwrite the xmax ! * altogether. ! */ ! } ! else ! { ! /* wait for regular transaction to end */ ! XactLockTableWait(xwait); ! LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE); ! ! /* ! * xwait is done, but if xwait had just locked the tuple then ! * some other xact could update this tuple before we get to ! * this point. Check for xmax change, and start over if so. ! */ ! if ((tp.t_data->t_infomask & HEAP_XMAX_IS_MULTI) || ! !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tp.t_data), ! xwait)) ! goto l1; ! ! /* Otherwise check if it committed or aborted */ ! UpdateXmaxHintBits(tp.t_data, buffer, xwait); ! } } /* *************** *** 3070,3077 **** l2: } else if (result == HeapTupleBeingUpdated && wait) { - TransactionId xwait; - uint16 infomask; bool can_continue = false; checked_lockers = true; --- 3095,3100 ---- *************** *** 3089,3225 **** l2: * heap_update directly. */ - /* must copy state data before unlocking buffer */ - xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data); - infomask = oldtup.t_data->t_infomask; - - LockBuffer(buffer, BUFFER_LOCK_UNLOCK); - /* ! * Acquire tuple lock to establish our priority for the tuple (see ! * heap_lock_tuple). LockTuple will release us when we are ! * next-in-line for the tuple. * ! * If we are forced to "start over" below, we keep the tuple lock; ! * this arranges that we stay at the head of the line while rechecking ! * tuple state. */ ! if (!have_tuple_lock) { ! LockTupleTuplock(relation, &(oldtup.t_self), *lockmode); ! have_tuple_lock = true; ! } ! /* ! * Now we have to do something about the existing locker. If it's a ! * multi, sleep on it; we might be awakened before it is completely ! * gone (or even not sleep at all in some cases); we need to preserve ! * it as locker, unless it is gone completely. ! * ! * If it's not a multi, we need to check for sleeping conditions ! * before actually going to sleep. If the update doesn't conflict ! * with the locks, we just continue without sleeping (but making sure ! * it is preserved). ! */ ! if (infomask & HEAP_XMAX_IS_MULTI) { ! TransactionId update_xact; ! int remain; ! /* wait for multixact */ ! MultiXactIdWait((MultiXactId) xwait, mxact_status, &remain, ! infomask); ! LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE); ! /* ! * If xwait had just locked the tuple then some other xact could ! * update this tuple before we get to this point. Check for xmax ! * change, and start over if so. ! */ ! if (!(oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI) || ! !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data), ! xwait)) ! goto l2; /* ! * Note that the multixact may not be done by now. It could have ! * surviving members; our own xact or other subxacts of this ! * backend, and also any other concurrent transaction that locked ! * the tuple with KeyShare if we only got TupleLockUpdate. If ! * this is the case, we have to be careful to mark the updated ! * tuple with the surviving members in Xmax. * ! * Note that there could have been another update in the ! * MultiXact. In that case, we need to check whether it committed ! * or aborted. If it aborted we are safe to update it again; ! * otherwise there is an update conflict, and we have to return ! * HeapTupleUpdated below. ! * ! * In the LockTupleExclusive case, we still need to preserve the ! * surviving members: those would include the tuple locks we had ! * before this one, which are important to keep in case this ! * subxact aborts. */ ! update_xact = InvalidTransactionId; ! if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask)) ! update_xact = HeapTupleGetUpdateXid(oldtup.t_data); ! ! /* ! * There was no UPDATE in the MultiXact; or it aborted. No ! * TransactionIdIsInProgress() call needed here, since we called ! * MultiXactIdWait() above. ! */ ! if (!TransactionIdIsValid(update_xact) || ! TransactionIdDidAbort(update_xact)) ! can_continue = true; - locker_remains = remain != 0; - } - else - { /* ! * If it's just a key-share locker, and we're not changing the key ! * columns, we don't need to wait for it to end; but we need to ! * preserve it as locker. */ ! if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact) { LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE); /* ! * recheck the locker; if someone else changed the tuple while ! * we weren't looking, start over. */ ! if ((oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI) || ! !TransactionIdEquals( ! HeapTupleHeaderGetRawXmax(oldtup.t_data), ! xwait)) goto l2; ! can_continue = true; ! locker_remains = true; } else { - /* wait for regular transaction to end */ - XactLockTableWait(xwait); - LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE); - /* ! * xwait is done, but if xwait had just locked the tuple then ! * some other xact could update this tuple before we get to ! * this point. Check for xmax change, and start over if so. */ ! if ((oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI) || ! !TransactionIdEquals( HeapTupleHeaderGetRawXmax(oldtup.t_data), ! xwait)) ! goto l2; - /* Otherwise check if it committed or aborted */ - UpdateXmaxHintBits(oldtup.t_data, buffer, xwait); - if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) can_continue = true; } } --- 3112,3279 ---- * heap_update directly. */ /* ! * If any subtransaction of the current top transaction already holds ! * a lock on this tuple, (and no one else does,) we must skip sleeping ! * on the xwait; that would lead to us sleeping on our own ! * transaction, which is unlikely to end up well. * ! * Note we don't need to do anything about this when the xwait is a ! * multixact, because that code is already prepared to ignore ! * subtransactions of the current top transaction. ! * ! * This must be done before acquiring our tuple lock, to avoid ! * deadlocks with other transaction that are already waiting on the ! * lock we hold. */ ! if (!(oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI) && ! TransactionIdIsCurrentTransactionId( ! HeapTupleHeaderGetRawXmax(oldtup.t_data))) { ! Assert(HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask)); ! can_continue = true; ! locker_remains = true; ! } ! else { ! TransactionId xwait; ! uint16 infomask; ! /* must copy state data before unlocking buffer */ ! xwait = HeapTupleHeaderGetRawXmax(oldtup.t_data); ! infomask = oldtup.t_data->t_infomask; ! LockBuffer(buffer, BUFFER_LOCK_UNLOCK); /* ! * Acquire tuple lock to establish our priority for the tuple (see ! * heap_lock_tuple). LockTuple will release us when we are ! * next-in-line for the tuple. * ! * If we are forced to "start over" below, we keep the tuple lock; ! * this arranges that we stay at the head of the line while ! * rechecking tuple state. */ ! if (!have_tuple_lock) ! { ! LockTupleTuplock(relation, &(oldtup.t_self), *lockmode); ! have_tuple_lock = true; ! } /* ! * Now we have to do something about the existing locker. If it's ! * a multi, sleep on it; we might be awakened before it is ! * completely gone (or even not sleep at all in some cases); we ! * need to preserve it as locker, unless it is gone completely. ! * ! * If it's not a multi, we need to check for sleeping conditions ! * before actually going to sleep. If the update doesn't conflict ! * with the locks, we just continue without sleeping (but making ! * sure it is preserved). */ ! if (infomask & HEAP_XMAX_IS_MULTI) { + TransactionId update_xact; + int remain; + + /* wait for multixact */ + MultiXactIdWait((MultiXactId) xwait, mxact_status, &remain, + infomask); LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE); /* ! * If xwait had just locked the tuple then some other xact ! * could update this tuple before we get to this point. Check ! * for xmax change, and start over if so. */ ! if (!(oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI) || ! !TransactionIdEquals(HeapTupleHeaderGetRawXmax(oldtup.t_data), ! xwait)) goto l2; ! /* ! * Note that the multixact may not be done by now. It could ! * have surviving members; our own xact or other subxacts of ! * this backend, and also any other concurrent transaction ! * that locked the tuple with KeyShare if we only got ! * TupleLockUpdate. If this is the case, we have to be ! * careful to mark the updated tuple with the surviving ! * members in Xmax. ! * ! * Note that there could have been another update in the ! * MultiXact. In that case, we need to check whether it ! * committed or aborted. If it aborted we are safe to update ! * it again; otherwise there is an update conflict, and we ! * have to return HeapTupleUpdated below. ! * ! * In the LockTupleExclusive case, we still need to preserve ! * the surviving members: those would include the tuple locks ! * we had before this one, which are important to keep in case ! * this subxact aborts. ! */ ! update_xact = InvalidTransactionId; ! if (!HEAP_XMAX_IS_LOCKED_ONLY(oldtup.t_data->t_infomask)) ! update_xact = HeapTupleGetUpdateXid(oldtup.t_data); ! ! /* ! * There was no UPDATE in the MultiXact; or it aborted. No ! * TransactionIdIsInProgress() call needed here, since we ! * called MultiXactIdWait() above. ! */ ! if (!TransactionIdIsValid(update_xact) || ! TransactionIdDidAbort(update_xact)) ! can_continue = true; ! ! locker_remains = remain != 0; } else { /* ! * If it's just a key-share locker, and we're not changing the ! * key columns, we don't need to wait for it to end; but we ! * need to preserve it as locker. */ ! if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) && key_intact) ! { ! LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE); ! ! /* ! * recheck the locker; if someone else changed the tuple ! * while we weren't looking, start over. ! */ ! if ((oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI) || ! !TransactionIdEquals( HeapTupleHeaderGetRawXmax(oldtup.t_data), ! xwait)) ! goto l2; can_continue = true; + locker_remains = true; + } + else + { + /* wait for regular transaction to end */ + XactLockTableWait(xwait); + LockBuffer(buffer, BUFFER_LOCK_EXCLUSIVE); + + /* + * xwait is done, but if xwait had just locked the tuple + * then some other xact could update this tuple before we + * get to this point. Check for xmax change, and start + * over if so. + */ + if ((oldtup.t_data->t_infomask & HEAP_XMAX_IS_MULTI) || + !TransactionIdEquals( + HeapTupleHeaderGetRawXmax(oldtup.t_data), + xwait)) + goto l2; + + /* Otherwise check if it committed or aborted */ + UpdateXmaxHintBits(oldtup.t_data, buffer, xwait); + if (oldtup.t_data->t_infomask & HEAP_XMAX_INVALID) + can_continue = true; + } } } *************** *** 3856,3862 **** simple_heap_update(Relation relation, ItemPointer otid, HeapTuple tup) static MultiXactStatus get_mxact_status_for_lock(LockTupleMode mode, bool is_update) { ! int retval; if (is_update) retval = tupleLockExtraInfo[mode].updstatus; --- 3910,3916 ---- static MultiXactStatus get_mxact_status_for_lock(LockTupleMode mode, bool is_update) { ! int retval; if (is_update) retval = tupleLockExtraInfo[mode].updstatus; *************** *** 3997,4002 **** l3: --- 4051,4072 ---- pfree(members); } + else if (TransactionIdIsCurrentTransactionId(xwait)) + { + if (mode == LockTupleKeyShare) + return HeapTupleMayBeUpdated; + if (mode == LockTupleShare && + (HEAP_XMAX_IS_SHR_LOCKED(infomask) || + HEAP_XMAX_IS_EXCL_LOCKED(infomask))) + return HeapTupleMayBeUpdated; + if (HEAP_XMAX_IS_EXCL_LOCKED(infomask)) + { + if (mode == LockTupleNoKeyExclusive) + return HeapTupleMayBeUpdated; + if (infomask2 & HEAP_KEYS_UPDATED) + return HeapTupleMayBeUpdated; + } + } /* * Acquire tuple lock to establish our priority for the tuple. *************** *** 4036,4048 **** l3: * continue if the key hasn't been modified. * * However, if there are updates, we need to walk the update chain ! * to mark future versions of the row as locked, too. That way, ! * if somebody deletes that future version, we're protected ! * against the key going away. This locking of future versions ! * could block momentarily, if a concurrent transaction is ! * deleting a key; or it could return a value to the effect that ! * the transaction deleting the key has already committed. So we ! * do this before re-locking the buffer; otherwise this would be * prone to deadlocks. * * Note that the TID we're locking was grabbed before we unlocked --- 4106,4118 ---- * continue if the key hasn't been modified. * * However, if there are updates, we need to walk the update chain ! * to mark future versions of the row as locked, too. That way, if ! * somebody deletes that future version, we're protected against ! * the key going away. This locking of future versions could ! * block momentarily, if a concurrent transaction is deleting a ! * key; or it could return a value to the effect that the ! * transaction deleting the key has already committed. So we do ! * this before re-locking the buffer; otherwise this would be * prone to deadlocks. * * Note that the TID we're locking was grabbed before we unlocked *************** *** 4144,4150 **** l3: * been the case, HeapTupleSatisfiesUpdate would have returned * MayBeUpdated and we wouldn't be here. */ ! nmembers = GetMultiXactIdMembers(xwait, &members, false); if (nmembers <= 0) { --- 4214,4221 ---- * been the case, HeapTupleSatisfiesUpdate would have returned * MayBeUpdated and we wouldn't be here. */ ! nmembers = ! GetMultiXactIdMembers(xwait, &members, false); if (nmembers <= 0) { *************** *** 4175,4181 **** l3: */ LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE); if (!(tuple->t_data->t_infomask & HEAP_XMAX_IS_MULTI) || ! !TransactionIdEquals(HeapTupleHeaderGetRawXmax(tuple->t_data), xwait)) { pfree(members); --- 4246,4253 ---- */ LockBuffer(*buffer, BUFFER_LOCK_EXCLUSIVE); if (!(tuple->t_data->t_infomask & HEAP_XMAX_IS_MULTI) || ! !TransactionIdEquals( ! HeapTupleHeaderGetRawXmax(tuple->t_data), xwait)) { pfree(members); *************** *** 4365,4401 **** failed: old_infomask = tuple->t_data->t_infomask; /* - * We might already hold the desired lock (or stronger), possibly under a - * different subtransaction of the current top transaction. If so, there - * is no need to change state or issue a WAL record. We already handled - * the case where this is true for xmax being a MultiXactId, so now check - * for cases where it is a plain TransactionId. - * - * Note in particular that this covers the case where we already hold - * exclusive lock on the tuple and the caller only wants key share or - * share lock. It would certainly not do to give up the exclusive lock. - */ - if (!(old_infomask & (HEAP_XMAX_INVALID | - HEAP_XMAX_COMMITTED | - HEAP_XMAX_IS_MULTI)) && - (mode == LockTupleKeyShare ? - (HEAP_XMAX_IS_KEYSHR_LOCKED(old_infomask) || - HEAP_XMAX_IS_SHR_LOCKED(old_infomask) || - HEAP_XMAX_IS_EXCL_LOCKED(old_infomask)) : - mode == LockTupleShare ? - (HEAP_XMAX_IS_SHR_LOCKED(old_infomask) || - HEAP_XMAX_IS_EXCL_LOCKED(old_infomask)) : - (HEAP_XMAX_IS_EXCL_LOCKED(old_infomask))) && - TransactionIdIsCurrentTransactionId(xmax)) - { - LockBuffer(*buffer, BUFFER_LOCK_UNLOCK); - /* Probably can't hold tuple lock here, but may as well check */ - if (have_tuple_lock) - UnlockTupleTuplock(relation, tid, mode); - return HeapTupleMayBeUpdated; - } - - /* * If this is the first possibly-multixact-able operation in the current * transaction, set my per-backend OldestMemberMXactId setting. We can be * certain that the transaction will never become a member of any older --- 4437,4442 ---- *************** *** 4623,4629 **** l5: if (!MultiXactIdIsRunning(xmax)) { if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) || ! TransactionIdDidAbort(MultiXactIdGetUpdateXid(xmax, old_infomask))) { /* --- 4664,4670 ---- if (!MultiXactIdIsRunning(xmax)) { if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask) || ! !TransactionIdDidCommit(MultiXactIdGetUpdateXid(xmax, old_infomask))) { /* *************** *** 4675,4681 **** l5: */ MultiXactStatus new_status; MultiXactStatus old_status; ! LockTupleMode old_mode; if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)) { --- 4716,4722 ---- */ MultiXactStatus new_status; MultiXactStatus old_status; ! LockTupleMode old_mode; if (HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)) { *************** *** 4723,4734 **** l5: if (xmax == add_to_xmax) { /* ! * Note that it's not possible for the original tuple to be updated: ! * we wouldn't be here because the tuple would have been invisible and ! * we wouldn't try to update it. As a subtlety, this code can also ! * run when traversing an update chain to lock future versions of a ! * tuple. But we wouldn't be here either, because the add_to_xmax ! * would be different from the original updater. */ Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)); --- 4764,4776 ---- if (xmax == add_to_xmax) { /* ! * Note that it's not possible for the original tuple to be ! * updated: we wouldn't be here because the tuple would have been ! * invisible and we wouldn't try to update it. As a subtlety, ! * this code can also run when traversing an update chain to lock ! * future versions of a tuple. But we wouldn't be here either, ! * because the add_to_xmax would be different from the original ! * updater. */ Assert(HEAP_XMAX_IS_LOCKED_ONLY(old_infomask)); *************** *** 4807,4813 **** static HTSU_Result test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid, LockTupleMode mode, bool *needwait) { ! MultiXactStatus wantedstatus; *needwait = false; wantedstatus = get_mxact_status_for_lock(mode, false); --- 4849,4855 ---- test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid, LockTupleMode mode, bool *needwait) { ! MultiXactStatus wantedstatus; *needwait = false; wantedstatus = get_mxact_status_for_lock(mode, false); *************** *** 4820,4837 **** test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid, if (TransactionIdIsCurrentTransactionId(xid)) { /* ! * Updated by our own transaction? Just return failure. This shouldn't ! * normally happen. */ return HeapTupleSelfUpdated; } else if (TransactionIdIsInProgress(xid)) { /* ! * If the locking transaction is running, what we do depends on whether ! * the lock modes conflict: if they do, then we must wait for it to ! * finish; otherwise we can fall through to lock this tuple version ! * without waiting. */ if (DoLockModesConflict(LOCKMODE_from_mxstatus(status), LOCKMODE_from_mxstatus(wantedstatus))) --- 4862,4879 ---- if (TransactionIdIsCurrentTransactionId(xid)) { /* ! * Updated by our own transaction? Just return failure. This ! * shouldn't normally happen. */ return HeapTupleSelfUpdated; } else if (TransactionIdIsInProgress(xid)) { /* ! * If the locking transaction is running, what we do depends on ! * whether the lock modes conflict: if they do, then we must wait for ! * it to finish; otherwise we can fall through to lock this tuple ! * version without waiting. */ if (DoLockModesConflict(LOCKMODE_from_mxstatus(status), LOCKMODE_from_mxstatus(wantedstatus))) *************** *** 4840,4847 **** test_lockmode_for_conflict(MultiXactStatus status, TransactionId xid, } /* ! * If we set needwait above, then this value doesn't matter; otherwise, ! * this value signals to caller that it's okay to proceed. */ return HeapTupleMayBeUpdated; } --- 4882,4889 ---- } /* ! * If we set needwait above, then this value doesn't matter; ! * otherwise, this value signals to caller that it's okay to proceed. */ return HeapTupleMayBeUpdated; } *************** *** 4927,4934 **** l4: LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE); /* ! * Check the tuple XMIN against prior XMAX, if any. If we reached ! * the end of the chain, we're done, so return success. */ if (TransactionIdIsValid(priorXmax) && !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data), --- 4969,4976 ---- LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE); /* ! * Check the tuple XMIN against prior XMAX, if any. If we reached the ! * end of the chain, we're done, so return success. */ if (TransactionIdIsValid(priorXmax) && !TransactionIdEquals(HeapTupleHeaderGetXmin(mytup.t_data), *************** *** 4956,4969 **** l4: rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data); if (old_infomask & HEAP_XMAX_IS_MULTI) { ! int nmembers; ! int i; MultiXactMember *members; nmembers = GetMultiXactIdMembers(rawxmax, &members, false); for (i = 0; i < nmembers; i++) { ! HTSU_Result res; res = test_lockmode_for_conflict(members[i].status, members[i].xid, --- 4998,5011 ---- rawxmax = HeapTupleHeaderGetRawXmax(mytup.t_data); if (old_infomask & HEAP_XMAX_IS_MULTI) { ! int nmembers; ! int i; MultiXactMember *members; nmembers = GetMultiXactIdMembers(rawxmax, &members, false); for (i = 0; i < nmembers; i++) { ! HTSU_Result res; res = test_lockmode_for_conflict(members[i].status, members[i].xid, *************** *** 4988,4994 **** l4: } else { ! HTSU_Result res; MultiXactStatus status; /* --- 5030,5036 ---- } else { ! HTSU_Result res; MultiXactStatus status; /* *************** *** 5011,5019 **** l4: else { /* ! * LOCK_ONLY present alone (a pg_upgraded tuple ! * marked as share-locked in the old cluster) shouldn't ! * be seen in the middle of an update chain. */ elog(ERROR, "invalid lock status in tuple"); } --- 5053,5061 ---- else { /* ! * LOCK_ONLY present alone (a pg_upgraded tuple marked ! * as share-locked in the old cluster) shouldn't be ! * seen in the middle of an update chain. */ elog(ERROR, "invalid lock status in tuple"); } *************** *** 5396,5402 **** FreezeMultiXactId(MultiXactId multi, uint16 t_infomask, */ if (ISUPDATE_from_mxstatus(members[i].status)) { ! TransactionId xid = members[i].xid; /* * It's an update; should we keep it? If the transaction is known --- 5438,5444 ---- */ if (ISUPDATE_from_mxstatus(members[i].status)) { ! TransactionId xid = members[i].xid; /* * It's an update; should we keep it? If the transaction is known *************** *** 5595,5605 **** heap_prepare_freeze_tuple(HeapTupleHeader tuple, TransactionId cutoff_xid, else if (flags & FRM_RETURN_IS_XID) { /* ! * NB -- some of these transformations are only valid because ! * we know the return Xid is a tuple updater (i.e. not merely a * locker.) Also note that the only reason we don't explicitely ! * worry about HEAP_KEYS_UPDATED is because it lives in t_infomask2 ! * rather than t_infomask. */ frz->t_infomask &= ~HEAP_XMAX_BITS; frz->xmax = newxmax; --- 5637,5647 ---- else if (flags & FRM_RETURN_IS_XID) { /* ! * NB -- some of these transformations are only valid because we ! * know the return Xid is a tuple updater (i.e. not merely a * locker.) Also note that the only reason we don't explicitely ! * worry about HEAP_KEYS_UPDATED is because it lives in ! * t_infomask2 rather than t_infomask. */ frz->t_infomask &= ~HEAP_XMAX_BITS; frz->xmax = newxmax; *************** *** 5609,5616 **** heap_prepare_freeze_tuple(HeapTupleHeader tuple, TransactionId cutoff_xid, } else if (flags & FRM_RETURN_IS_MULTI) { ! uint16 newbits; ! uint16 newbits2; /* * We can't use GetMultiXactIdHintBits directly on the new multi --- 5651,5658 ---- } else if (flags & FRM_RETURN_IS_MULTI) { ! uint16 newbits; ! uint16 newbits2; /* * We can't use GetMultiXactIdHintBits directly on the new multi *** a/src/backend/access/transam/multixact.c --- b/src/backend/access/transam/multixact.c *************** *** 1282,1320 **** retry: } /* - * MultiXactHasRunningRemoteMembers - * Does the given multixact have still-live members from - * transactions other than our own? - */ - bool - MultiXactHasRunningRemoteMembers(MultiXactId multi) - { - MultiXactMember *members; - int nmembers; - int i; - - nmembers = GetMultiXactIdMembers(multi, &members, true); - if (nmembers <= 0) - return false; - - for (i = 0; i < nmembers; i++) - { - /* not interested in our own members */ - if (TransactionIdIsCurrentTransactionId(members[i].xid)) - continue; - - if (TransactionIdIsInProgress(members[i].xid)) - { - pfree(members); - return true; - } - } - - pfree(members); - return false; - } - - /* * mxactMemberComparator * qsort comparison function for MultiXactMember * --- 1282,1287 ---- *** a/src/backend/utils/time/tqual.c --- b/src/backend/utils/time/tqual.c *************** *** 688,694 **** HeapTupleSatisfiesUpdate(HeapTupleHeader tuple, CommandId curcid, if (HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask)) { ! TransactionId xmax; xmax = HeapTupleHeaderGetRawXmax(tuple); --- 688,694 ---- if (HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask)) { ! TransactionId xmax; xmax = HeapTupleHeaderGetRawXmax(tuple); *************** *** 701,720 **** HeapTupleSatisfiesUpdate(HeapTupleHeader tuple, CommandId curcid, if (tuple->t_infomask & HEAP_XMAX_IS_MULTI) { ! if (MultiXactHasRunningRemoteMembers(xmax)) return HeapTupleBeingUpdated; else return HeapTupleMayBeUpdated; } ! /* if locker is gone, all's well */ if (!TransactionIdIsInProgress(xmax)) return HeapTupleMayBeUpdated; ! ! if (!TransactionIdIsCurrentTransactionId(xmax)) ! return HeapTupleBeingUpdated; ! else ! return HeapTupleMayBeUpdated; } if (tuple->t_infomask & HEAP_XMAX_IS_MULTI) --- 701,720 ---- if (tuple->t_infomask & HEAP_XMAX_IS_MULTI) { ! if (MultiXactIdIsRunning(xmax)) return HeapTupleBeingUpdated; else return HeapTupleMayBeUpdated; } ! /* ! * If the locker is gone, then there is nothing of interest ! * left in this Xmax; otherwise, report the tuple as ! * locked/updated. ! */ if (!TransactionIdIsInProgress(xmax)) return HeapTupleMayBeUpdated; ! return HeapTupleBeingUpdated; } if (tuple->t_infomask & HEAP_XMAX_IS_MULTI) *************** *** 726,735 **** HeapTupleSatisfiesUpdate(HeapTupleHeader tuple, CommandId curcid, /* not LOCKED_ONLY, so it has to have an xmax */ Assert(TransactionIdIsValid(xmax)); ! /* updating subtransaction must have aborted */ if (!TransactionIdIsCurrentTransactionId(xmax)) { ! if (MultiXactHasRunningRemoteMembers(HeapTupleHeaderGetRawXmax(tuple))) return HeapTupleBeingUpdated; return HeapTupleMayBeUpdated; } --- 726,735 ---- /* not LOCKED_ONLY, so it has to have an xmax */ Assert(TransactionIdIsValid(xmax)); ! /* deleting subtransaction must have aborted */ if (!TransactionIdIsCurrentTransactionId(xmax)) { ! if (MultiXactIdIsRunning(HeapTupleHeaderGetRawXmax(tuple))) return HeapTupleBeingUpdated; return HeapTupleMayBeUpdated; } *************** *** 846,852 **** HeapTupleSatisfiesUpdate(HeapTupleHeader tuple, CommandId curcid, if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetRawXmax(tuple))) { if (HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask)) ! return HeapTupleMayBeUpdated; if (HeapTupleHeaderGetCmax(tuple) >= curcid) return HeapTupleSelfUpdated; /* updated after scan started */ else --- 846,852 ---- if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetRawXmax(tuple))) { if (HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_infomask)) ! return HeapTupleBeingUpdated; if (HeapTupleHeaderGetCmax(tuple) >= curcid) return HeapTupleSelfUpdated; /* updated after scan started */ else *** a/src/include/access/multixact.h --- b/src/include/access/multixact.h *************** *** 90,96 **** extern bool MultiXactIdIsRunning(MultiXactId multi); extern void MultiXactIdSetOldestMember(void); extern int GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **xids, bool allow_old); - extern bool MultiXactHasRunningRemoteMembers(MultiXactId multi); extern bool MultiXactIdPrecedes(MultiXactId multi1, MultiXactId multi2); extern bool MultiXactIdPrecedesOrEquals(MultiXactId multi1, MultiXactId multi2); --- 90,95 ---- *** a/src/tools/pgindent/typedefs.list --- b/src/tools/pgindent/typedefs.list *************** *** 2419,2424 **** xl_heap_clean --- 2419,2425 ---- xl_heap_cleanup_info xl_heap_delete xl_heap_freeze + xl_heap_freeze_tuple xl_heap_header xl_heap_inplace xl_heap_insert
^ permalink raw reply [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
@ 2013-12-01 12:12 ` Andres Freund <andres@2ndquadrant.com>
  2013-12-01 17:26   ` Re: Update with subselect sometimes returns wrong result David Johnston <polobo@yahoo.com>
  2013-12-02 21:55   ` Re: Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2 siblings, 2 replies; 24+ messages in thread

From: Andres Freund @ 2013-12-01 12:12 UTC (permalink / raw)
  To: Oliver Seemann <oseemann@gmail.com>; +Cc: pgsql-bugs

Hi,

On 2013-11-30 00:08:14 +0100, Oliver Seemann wrote:
> Then the following UPDATE should return exactly one row:
> 
> UPDATE t1 SET id = t1.id
> FROM (SELECT id FROM t1 LIMIT 1 FOR UPDATE) AS subset
> WHERE t1.id = subset.id
> RETURNING t1.id

It turns out, this currently (as Tom points out) is a question of how
the query is planned. UPDATEs with a FROM essentially are a join between
the involved tables. Roughly, this query can either be planned as
a) Scan all rows in subset, check whether it matches a row in t1.
or
b) Scan all rows in t1, check for each whether it matches a row in subset.

a) is perfectly fine for what you want, it will only return one row. But
b) is problematic since it will execute the subselect multiple
times, once for each row in t1. "FOR locklevel" currently has the property
of ignoring rows that the current command has modified, so you'll always
get a different row back...

To get rid of that ambiguity, I suggest rewriting the query to look
like:
WITH locked_row AS (
    SELECT id FROM t1 LIMIT 1 FOR UPDATE
)
UPDATE t1 SET id = t1.id
FROM (SELECT * FROM locked_row) locked
WHERE t1.id = locked.id
RETURNING t1.id;

that should always be safe and indeed, I cannot reproduce the problem
that way.

Greetings,

Andres Freund

-- 
 Andres Freund	                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-12-01 12:12 ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
@ 2013-12-01 17:26   ` David Johnston <polobo@yahoo.com>
  1 sibling, 0 replies; 24+ messages in thread

From: David Johnston @ 2013-12-01 17:26 UTC (permalink / raw)
  To: pgsql-bugs

Andres Freund-3 wrote
> Hi,
> 
> On 2013-11-30 00:08:14 +0100, Oliver Seemann wrote:
>> Then the following UPDATE should return exactly one row:
>> 
>> UPDATE t1 SET id = t1.id
>> FROM (SELECT id FROM t1 LIMIT 1 FOR UPDATE) AS subset
>> WHERE t1.id = subset.id
>> RETURNING t1.id
> 
> It turns out, this currently (as Tom points out) is a question of how
> the query is planned. UPDATEs with a FROM essentially are a join between
> the involved tables. Roughly, this query can either be planned as
> a) Scan all rows in subset, check whether it matches a row in t1.
> or
> b) Scan all rows in t1, check for each whether it matches a row in subset.
> 
> a) is perfectly fine for what you want, it will only return one row. But
> b) is problematic since it will execute the subselect multiple
> times, once for each row in t1. "FOR locklevel" currently has the property
> of ignoring rows that the current command has modified, so you'll always
> get a different row back...



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-12-01 12:12 ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
@ 2013-12-02 21:55   ` Oliver Seemann <oseemann@gmail.com>
  2013-12-02 22:41     ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  1 sibling, 1 reply; 24+ messages in thread

From: Oliver Seemann @ 2013-12-02 21:55 UTC (permalink / raw)
  To: Andres Freund <andres@2ndquadrant.com>; +Cc: pgsql-bugs

2013/12/1 Andres Freund <andres@2ndquadrant.com>:
> To get rid of that ambiguity, I suggest rewriting the query to look
> like:
> WITH locked_row AS (
>     SELECT id FROM t1 LIMIT 1 FOR UPDATE
> )
> UPDATE t1 SET id = t1.id
> FROM (SELECT * FROM locked_row) locked
> WHERE t1.id = locked.id
> RETURNING t1.id;

Thanks for looking into this and even providing a workaround!

The patch you posted previously is incomplete, right? Because I can
still trigger the problem with the patch applied on top of git master.
(I use autovacuum_naptime = 1s to reliably trigger within 1-5 seconds).


Oliver


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread

* Re: Update with subselect sometimes returns wrong result
  2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
  2013-12-01 12:12 ` Re: Update with subselect sometimes returns wrong result Andres Freund <andres@2ndquadrant.com>
  2013-12-02 21:55   ` Re: Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
@ 2013-12-02 22:41     ` Andres Freund <andres@2ndquadrant.com>
  0 siblings, 0 replies; 24+ messages in thread

From: Andres Freund @ 2013-12-02 22:41 UTC (permalink / raw)
  To: Oliver Seemann <oseemann@gmail.com>; +Cc: pgsql-bugs

On 2013-12-02 22:55:30 +0100, Oliver Seemann wrote:
> 2013/12/1 Andres Freund <andres@2ndquadrant.com>:
> > To get rid of that ambiguity, I suggest rewriting the query to look
> > like:
> > WITH locked_row AS (
> >     SELECT id FROM t1 LIMIT 1 FOR UPDATE
> > )
> > UPDATE t1 SET id = t1.id
> > FROM (SELECT * FROM locked_row) locked
> > WHERE t1.id = locked.id
> > RETURNING t1.id;
> 
> Thanks for looking into this and even providing a workaround!
> 
> The patch you posted previously is incomplete, right? Because I can
> still trigger the problem with the patch applied on top of git master.
> (I use autovacuum_naptime = 1s to reliably trigger within 1-5 seconds).

The patch isn't for this issue, it's for something Tom noticed while
investigating it. Purely a performance optimization/fix for a
performance regression - albeit a noticeable one.
I'd judge that there's about zero chance that the issue can be fixed in
the stable branches, the likelihood of breaking other working code due
to the require semantic changes are far too great.

Greetings,

Andres Freund

-- 
 Andres Freund	                   http://www.2ndQuadrant.com/
 PostgreSQL Development, 24x7 Support, Training & Services


-- 
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs



^ permalink  raw  reply  [nested|flat] 24+ messages in thread


end of thread, other threads:[~2014-02-05 15:39 UTC | newest]

Thread overview: 24+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2013-11-29 23:08 Update with subselect sometimes returns wrong result Oliver Seemann <oseemann@gmail.com>
2013-11-30 07:32 ` Oliver Seemann <oseemann@gmail.com>
2013-11-30 17:57 ` Tom Lane <tgl@sss.pgh.pa.us>
2013-11-30 20:42   ` Marko Tiikkaja <marko@joh.to>
2013-11-30 21:40   ` Andres Freund <andres@2ndquadrant.com>
2013-12-01 03:00     ` David Johnston <polobo@yahoo.com>
2013-12-01 06:41     ` Tom Lane <tgl@sss.pgh.pa.us>
2013-12-01 07:03       ` Tom Lane <tgl@sss.pgh.pa.us>
2013-12-01 12:24         ` Andres Freund <andres@2ndquadrant.com>
2013-12-01 17:39           ` Tom Lane <tgl@sss.pgh.pa.us>
2013-12-01 08:19       ` Andres Freund <andres@2ndquadrant.com>
2013-12-01 11:45         ` Andres Freund <andres@2ndquadrant.com>
2013-12-01 11:53           ` Andres Freund <andres@2ndquadrant.com>
2013-12-18 22:13           ` Alvaro Herrera <alvherre@2ndquadrant.com>
2013-12-18 22:39             ` Andres Freund <andres@2ndquadrant.com>
2013-12-19 00:58               ` Alvaro Herrera <alvherre@2ndquadrant.com>
2013-12-19 15:58                 ` Alvaro Herrera <alvherre@2ndquadrant.com>
2013-12-20 02:44                   ` Alvaro Herrera <alvherre@2ndquadrant.com>
2014-02-05 14:22                     ` Robert Haas <robertmhaas@gmail.com>
2014-02-05 15:39                       ` Alvaro Herrera <alvherre@2ndquadrant.com>
2013-12-01 12:12 ` Andres Freund <andres@2ndquadrant.com>
2013-12-01 17:26   ` David Johnston <polobo@yahoo.com>
2013-12-02 21:55   ` Oliver Seemann <oseemann@gmail.com>
2013-12-02 22:41     ` Andres Freund <andres@2ndquadrant.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox