pg.ddx.io  pgsql-bugs@postgresql.org mailing list archive  
help / color / mirror / Atom feed
BUG #15324: Non-deterministic behaviour from parallelised sub-query
38+ messages / 11 participants
[nested] [flat]

Commits from this thread:
  2018-09-14 75f9c4ca5a 830d756590 1ceb103e7d 568b4e1fde  Don't allow LIMIT/OFFSET clause within sub-selects to be pushed to workers.
  2018-09-14 271b678436  Back-patch "Fix parallel hash join path search."
  2018-09-04 2ce253cf57 14e9b2a752 bf61873ae3 f658235a44  Prohibit pushing subqueries containing window function calculation to
* BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-13 16:14  PG Bug reporting form <noreply@postgresql.org>
  0 siblings, 1 reply; 38+ messages in thread

From: PG Bug reporting form @ 2018-08-13 16:14 UTC (permalink / raw)
  To: pgsql-bugs@lists.postgresql.org; +Cc: andy@prestigedigital.com

The following bug has been logged on the website:

Bug reference:      15324
Logged by:          Andrew Fletcher
Email address:      andy@prestigedigital.com
PostgreSQL version: 10.5
Operating system:   macOS High Sierra 10.13.6
Description:        

Reproductions - 

Make sure postgresql.conf sets max_parallel_workers_per_gather to 2 or
more

max_parallel_workers_per_gather = 2

Repro 1:

Create table from the following sql file -

https://www.dropbox.com/s/3cm643vmugcgkxh/events.sql.zip?dl=0

Execute this query (multiple times!)

select * from events where account in (select account from events where
data->>'page' = 'success.html' limit 3);

Incorrect output -

 account |   type   |           data           
---------+----------+--------------------------
  304873 | pageview | {"page": "success.html"}
  304875 | pageview | {"page": "c.html"}
  304875 | pageview | {"page": "success.html"}
  304885 | pageview | {"page": "a.html"}
  304885 | pageview | {"page": "success.html"}
(5 rows)

Correct output -

 account |   type   |           data           
---------+----------+--------------------------
  304873 | pageview | {"page": "success.html"}
  304875 | pageview | {"page": "c.html"}
  304875 | pageview | {"page": "success.html"}
  304885 | pageview | {"page": "a.html"}
  304885 | pageview | {"page": "success.html"}
  304873 | pageview | {"page": "b.html"}
(6 rows)


Repro 2 -

Create table from the following sql file -

https://www.dropbox.com/s/mzglgm4a5x1mqno/repro1.sql.zip?dl=0

Execute this query (multiple times!)

select * from repro1 where account in (select account from repro1 where page
= 'success.html' limit 3);

Incorrect Output -

 account |     page     
---------+--------------
      14 | a.html
      14 | success.html
      65 | b.html
      65 | success.html
      80 | b.html
      80 | success.html
   24084 | a.html
   24084 | success.html
   24085 | c.html
   24085 | success.html
   24095 | a.html
   24095 | success.html
(12 rows)

Correct output -

 account |     page     
---------+--------------
      14 | a.html
      14 | success.html
      65 | b.html
      65 | success.html
      80 | b.html
      80 | success.html
(6 rows)


Full version string -

PostgreSQL 10.5 on x86_64-apple-darwin17.7.0, compiled by Apple LLVM version
9.1.0 (clang-902.0.39.2), 64-bit

Also reproduced (with slightly different non-determinism) on -

PostgreSQL 9.6.3, compiled by Visual C++ build 1800, 32-bit on Windows 10
Pro 1709, build 16299.547


Known workarounds -

1.  max_parallel_workers_per_gather = 0
2.  Add order by account asc to the subquery (works for both repros)



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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-13 16:35  Andres Freund <andres@anarazel.de>
  parent: PG Bug reporting form <noreply@postgresql.org>
  0 siblings, 2 replies; 38+ messages in thread

From: Andres Freund @ 2018-08-13 16:35 UTC (permalink / raw)
  To: andy@prestigedigital.com; pgsql-bugs@lists.postgresql.org

Hi,

On 2018-08-13 16:14:03 +0000, PG Bug reporting form wrote:
> Execute this query (multiple times!)
> 
> select * from events where account in (select account from events where
> data->>'page' = 'success.html' limit 3);

Well, the subselect with thelimit going to return different results from
run to run. Unless you add an ORDER BY there's no guaranteed order in
which tuples are returned.  So I don't think it's surprising that you're
getting results that differ between runs.

Greetings,

Andres Freund




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-13 16:40  Andrew Fletcher <andy@prestigedigital.com>
  parent: Andres Freund <andres@anarazel.de>
  1 sibling, 0 replies; 38+ messages in thread

From: Andrew Fletcher @ 2018-08-13 16:40 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: pgsql-bugs@lists.postgresql.org

Sorry the bug report was unclear.

Its not just that its returning different accounts from the subquery.

In the first repro you can see account 304873 appears twice in the correct
result but only once in the incorrect one.  Even though its the same data,
same query etc.  If account 304873 is selected within the limit of the
subquery then all the results for it should be returned in the outer query.

In the second repro you can see more than 3 accounts in the outer query,
even though the inner one is limited to 3.

Hope that makes it clearer.

Cheers,

Andy


On Mon, Aug 13, 2018 at 5:35 PM, Andres Freund <andres@anarazel.de> wrote:

> Hi,
>
> On 2018-08-13 16:14:03 +0000, PG Bug reporting form wrote:
> > Execute this query (multiple times!)
> >
> > select * from events where account in (select account from events where
> > data->>'page' = 'success.html' limit 3);
>
> Well, the subselect with thelimit going to return different results from
> run to run. Unless you add an ORDER BY there's no guaranteed order in
> which tuples are returned.  So I don't think it's surprising that you're
> getting results that differ between runs.
>
> Greetings,
>
> Andres Freund
>

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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-13 16:43  Marko Tiikkaja <marko@joh.to>
  parent: Andres Freund <andres@anarazel.de>
  1 sibling, 1 reply; 38+ messages in thread

From: Marko Tiikkaja @ 2018-08-13 16:43 UTC (permalink / raw)
  To: Andres Freund <andres@anarazel.de>; +Cc: andy@prestigedigital.com; pgsql-bugs@lists.postgresql.org

On Mon, Aug 13, 2018 at 7:35 PM, Andres Freund <andres@anarazel.de> wrote:

> On 2018-08-13 16:14:03 +0000, PG Bug reporting form wrote:
> > Execute this query (multiple times!)
> >
> > select * from events where account in (select account from events where
> > data->>'page' = 'success.html' limit 3);
>
> Well, the subselect with thelimit going to return different results from
> run to run. Unless you add an ORDER BY there's no guaranteed order in
> which tuples are returned.  So I don't think it's surprising that you're
> getting results that differ between runs.
>

While this is true, that's missing the point.  This output, for example:

 account |     page
---------+--------------
      14 | a.html
      14 | success.html
      65 | b.html
      65 | success.html
      80 | b.html
      80 | success.html
   24084 | a.html
   24084 | success.html
   24085 | c.html
   24085 | success.html
   24095 | a.html
   24095 | success.html
(12 rows)

contains data from six different accounts, which should surely be
impossible regardless of which three accounts the subquery returns.

The one in repro1 is also problematic, because it shows that 304873, 304875
and 304885 were all selected, but not all rows for those accounts were
returned.


.m

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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-13 17:26  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Marko Tiikkaja <marko@joh.to>
  0 siblings, 2 replies; 38+ messages in thread

From: Tom Lane @ 2018-08-13 17:26 UTC (permalink / raw)
  To: Marko Tiikkaja <marko@joh.to>; +Cc: Andres Freund <andres@anarazel.de>; andy@prestigedigital.com; pgsql-bugs@lists.postgresql.org

Marko Tiikkaja <marko@joh.to> writes:
> On Mon, Aug 13, 2018 at 7:35 PM, Andres Freund <andres@anarazel.de> wrote:
>> Well, the subselect with thelimit going to return different results from
>> run to run. Unless you add an ORDER BY there's no guaranteed order in
>> which tuples are returned.  So I don't think it's surprising that you're
>> getting results that differ between runs.

> While this is true, that's missing the point.

Yeah, I agree.  I think probably what's happening is that the sub-select
is getting pushed down to the parallel workers and they are not all
computing the same set of sub-select results, leading to inconsistent
answers at the top level.

Likely, we need to treat the presence of a LIMIT/OFFSET in a sub-select
as making it parallel-unsafe, for exactly the reason that that makes
its results non-deterministic.

			regards, tom lane




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-13 17:47  Pavel Stehule <pavel.stehule@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 38+ messages in thread

From: Pavel Stehule @ 2018-08-13 17:47 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; andy@prestigedigital.com; pgsql-bugs@lists.postgresql.org

2018-08-13 19:26 GMT+02:00 Tom Lane <tgl@sss.pgh.pa.us>:

> Marko Tiikkaja <marko@joh.to> writes:
> > On Mon, Aug 13, 2018 at 7:35 PM, Andres Freund <andres@anarazel.de>
> wrote:
> >> Well, the subselect with thelimit going to return different results from
> >> run to run. Unless you add an ORDER BY there's no guaranteed order in
> >> which tuples are returned.  So I don't think it's surprising that you're
> >> getting results that differ between runs.
>
> > While this is true, that's missing the point.
>
> Yeah, I agree.  I think probably what's happening is that the sub-select
> is getting pushed down to the parallel workers and they are not all
> computing the same set of sub-select results, leading to inconsistent
> answers at the top level.
>
> Likely, we need to treat the presence of a LIMIT/OFFSET in a sub-select
> as making it parallel-unsafe, for exactly the reason that that makes
> its results non-deterministic.
>

Isn't it default behave of LIMIT/OFFSET without ORDER BY clause?

If we don't need to solve order of rows, then parallel unsafe is not
necessary.

Regards

Pavel


>                         regards, tom lane
>
>

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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-13 18:04  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Pavel Stehule <pavel.stehule@gmail.com>
  0 siblings, 1 reply; 38+ messages in thread

From: Tom Lane @ 2018-08-13 18:04 UTC (permalink / raw)
  To: Pavel Stehule <pavel.stehule@gmail.com>; +Cc: Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; andy@prestigedigital.com; pgsql-bugs@lists.postgresql.org

Pavel Stehule <pavel.stehule@gmail.com> writes:
> 2018-08-13 19:26 GMT+02:00 Tom Lane <tgl@sss.pgh.pa.us>:
>> Likely, we need to treat the presence of a LIMIT/OFFSET in a sub-select
>> as making it parallel-unsafe, for exactly the reason that that makes
>> its results non-deterministic.

> Isn't it default behave of LIMIT/OFFSET without ORDER BY clause?

In principle, the planner could prove in some cases that the results
were deterministic even with LIMIT/OFFSET.  BuT I doubt it's worth
the trouble.  I certainly wouldn't advocate for such logic to be
part of a back-patched bug fix.

			regards, tom lane




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-13 20:25  David G. Johnston <david.g.johnston@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 38+ messages in thread

From: David G. Johnston @ 2018-08-13 20:25 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Pavel Stehule <pavel.stehule@gmail.com>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; andy@prestigedigital.com <andy@prestigedigital.com>; pgsql-bugs@lists.postgresql.org <pgsql-bugs@lists.postgresql.org>

On Monday, August 13, 2018, Tom Lane <tgl@sss.pgh.pa.us> wrote:

> Pavel Stehule <pavel.stehule@gmail.com> writes:
> > 2018-08-13 19:26 GMT+02:00 Tom Lane <tgl@sss.pgh.pa.us>:
> >> Likely, we need to treat the presence of a LIMIT/OFFSET in a sub-select
> >> as making it parallel-unsafe, for exactly the reason that that makes
> >> its results non-deterministic.
>
> > Isn't it default behave of LIMIT/OFFSET without ORDER BY clause?
>
> In principle, the planner could prove in some cases that the results
> were deterministic even with LIMIT/OFFSET.  BuT I doubt it's worth
> the trouble.  I certainly wouldn't advocate for such logic to be
> part of a back-patched bug fix.
>
>
Could the planner stick a materialize node there that feeds the same set of
originally selected records to any parallel executors that end up pulling
from it?

David J.

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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-13 22:38  Tom Lane <tgl@sss.pgh.pa.us>
  parent: David G. Johnston <david.g.johnston@gmail.com>
  0 siblings, 0 replies; 38+ messages in thread

From: Tom Lane @ 2018-08-13 22:38 UTC (permalink / raw)
  To: David G. Johnston <david.g.johnston@gmail.com>; +Cc: Pavel Stehule <pavel.stehule@gmail.com>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; andy@prestigedigital.com <andy@prestigedigital.com>; pgsql-bugs@lists.postgresql.org <pgsql-bugs@lists.postgresql.org>

"David G. Johnston" <david.g.johnston@gmail.com> writes:
> Could the planner stick a materialize node there that feeds the same set of
> originally selected records to any parallel executors that end up pulling
> from it?

No.  At least, Materialize as it stands doesn't help.  There's no
provision for pushing rowsets to parallel workers, only pulling
from them, and it would be an extremely nontrivial thing to add
AFAICS (for one thing, it'd make the leader process even more of
a bottleneck than it is already).

Maybe you could do something with dumping a rowset into a tuplestore
and forcing that out to temp files on-disk before starting any of
the parallel workers, then letting them read it in from the temp
files.  But that still looks like a lot of new work and completely
not fit for back-patching, even if we had it.

			regards, tom lane




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-14 04:10  Amit Kapila <amit.kapila16@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 2 replies; 38+ messages in thread

From: Amit Kapila @ 2018-08-14 04:10 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; andy@prestigedigital.com, PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Mon, Aug 13, 2018 at 10:56 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Marko Tiikkaja <marko@joh.to> writes:
>> On Mon, Aug 13, 2018 at 7:35 PM, Andres Freund <andres@anarazel.de> wrote:
>>> Well, the subselect with thelimit going to return different results from
>>> run to run. Unless you add an ORDER BY there's no guaranteed order in
>>> which tuples are returned.  So I don't think it's surprising that you're
>>> getting results that differ between runs.
>
>> While this is true, that's missing the point.
>
> Yeah, I agree.  I think probably what's happening is that the sub-select
> is getting pushed down to the parallel workers and they are not all
> computing the same set of sub-select results, leading to inconsistent
> answers at the top level.
>

Your analysis is correct.  The plan for one of the reported query is as follows:

postgres=# explain select * from repro1 where account in (select
account from repro1 where page
postgres(# = 'success.html' limit 3);
                                          QUERY PLAN
-----------------------------------------------------------------------------------------------
 Gather  (cost=1000.71..12727.24 rows=3 width=11)
   Workers Planned: 2
   ->  Hash Semi Join  (cost=0.71..11726.94 rows=1 width=11)
         Hash Cond: (repro1.account = repro1_1.account)
         ->  Parallel Seq Scan on repro1  (cost=0.00..10532.50
rows=454750 width=11)
         ->  Hash  (cost=0.67..0.67 rows=3 width=4)
               ->  Limit  (cost=0.00..0.64 rows=3 width=4)
                     ->  Seq Scan on repro1 repro1_1
(cost=0.00..19627.50 rows=91823 width=4)
                           Filter: ((page)::text = 'success.html'::text)
(9 rows)


As Tom said, it is evident from the plan that the Limit clause is
pushed in the inner-side of the parallel plan and not all the workers
compute the same result set for the inner side.

> Likely, we need to treat the presence of a LIMIT/OFFSET in a sub-select
> as making it parallel-unsafe, for exactly the reason that that makes
> its results non-deterministic.
>

Yeah, one idea could be that we detect this in
max_parallel_hazard_walker during the very first pass it performs on
query-tree.  Basically, in the SubLink node check, we can detect
whether the subselect has Limit/Offset clause and if so, then we can
treat it as parallel_unsafe.  I have tried that way and it prohibits
the parallel plan for the reported queries.  However, I think more
analysis and verification is required to see if it can happen in any
other related cases.  BTW, will there be any problem if we allow
sub-selects which have sortclause even if the Limit/Offset is present?

Let me know if you have already started working on it, otherwise, I
will prepare an initial patch.

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-14 07:36  Amit Kapila <amit.kapila16@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 0 replies; 38+ messages in thread

From: Amit Kapila @ 2018-08-14 07:36 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; andy@prestigedigital.com, PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Tue, Aug 14, 2018 at 9:40 AM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Mon, Aug 13, 2018 at 10:56 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> As Tom said, it is evident from the plan that the Limit clause is
> pushed in the inner-side of the parallel plan and not all the workers
> compute the same result set for the inner side.
>
>> Likely, we need to treat the presence of a LIMIT/OFFSET in a sub-select
>> as making it parallel-unsafe, for exactly the reason that that makes
>> its results non-deterministic.
>>
>
> Yeah, one idea could be that we detect this in
> max_parallel_hazard_walker during the very first pass it performs on
> query-tree.
>

I have written a patch along those lines.  This is still a WIP patch
and it is mainly to demonstrate what I have in mind.  There is one
test in select_parallel.sql failing after this patch, but I think that
is expected and we need to adjust that test.   Let me know if you see
a flaw in this approach?

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com

Attachments:

prohibit_parallel_limit_subselect_v1.patch (application/octet-stream, 2.1K) download diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index a04ad6e99e6..aecb6dfa72b 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -1208,12 +1208,25 @@ max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context) /* * Really we should not see SubLink during a max_interesting == restricted - * scan, but if we do, return true. + * scan, but if we do, return true. Also, we can't push sub-select + * containing LIMIT/OFFSET to workers as that can change the results + * depending on what is beneath LIMIT node. So, consider that case as + * parallel-unsafe. */ else if (IsA(node, SubLink)) { + Query *subquery; + SubLink *sublink = (SubLink *) node; + if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context)) return true; + + subquery = castNode(Query, sublink->subselect); + if (subquery->limitOffset || subquery->limitCount) + { + context->max_hazard = PROPARALLEL_UNSAFE; + return true; + } } /* @@ -1274,6 +1287,7 @@ max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context) else if (IsA(node, Query)) { Query *query = (Query *) node; + ListCell *rt; /* SELECT FOR UPDATE/SHARE must be treated as unsafe */ if (query->rowMarks != NULL) @@ -1282,6 +1296,27 @@ max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context) return true; } + /* + * We can't push sub-select containing LIMIT/OFFSET to workers as that + * can change the results depending on what is beneath LIMIT node. + * So, consider that case as parallel-unsafe. + */ + foreach(rt, query->rtable) + { + RangeTblEntry *rte = (RangeTblEntry *) lfirst(rt); + + if (rte->rtekind == RTE_SUBQUERY) + { + Query *subquery = castNode(Query, rte->subquery); + + if (subquery->limitOffset || subquery->limitCount) + { + context->max_hazard = PROPARALLEL_UNSAFE; + return true; + } + } + } + /* Recurse into subselects */ return query_tree_walker(query, max_parallel_hazard_walker,
^ permalink raw reply [nested|flat] 38+ messages in thread

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-14 10:22  Marko Tiikkaja <marko@joh.to>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 1 reply; 38+ messages in thread

From: Marko Tiikkaja @ 2018-08-14 10:22 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Tue, Aug 14, 2018 at 7:10 AM, Amit Kapila <amit.kapila16@gmail.com>
wrote:

> Yeah, one idea could be that we detect this in
> max_parallel_hazard_walker during the very first pass it performs on
> query-tree.  Basically, in the SubLink node check, we can detect
> whether the subselect has Limit/Offset clause and if so, then we can
> treat it as parallel_unsafe.  I have tried that way and it prohibits
> the parallel plan for the reported queries.  However, I think more
> analysis and verification is required to see if it can happen in any
> other related cases.
>

This seems broken as well:

    create table qwr(a int not null, b int not null, c text not null);
    insert into qwr select i, i, (select prosrc from pg_proc where
oid=11734) from generate_series(1, 128000) i;
    set parallel_setup_cost to 0;
    analyze qwr;
    select count(*) from qwr where (a, b) in (select a, row_number() over()
from qwr);


.m

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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-14 11:09  Amit Kapila <amit.kapila16@gmail.com>
  parent: Marko Tiikkaja <marko@joh.to>
  0 siblings, 1 reply; 38+ messages in thread

From: Amit Kapila @ 2018-08-14 11:09 UTC (permalink / raw)
  To: Marko Tiikkaja <marko@joh.to>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Tue, Aug 14, 2018 at 3:52 PM, Marko Tiikkaja <marko@joh.to> wrote:
> On Tue, Aug 14, 2018 at 7:10 AM, Amit Kapila <amit.kapila16@gmail.com>
> wrote:
>>
>> Yeah, one idea could be that we detect this in
>> max_parallel_hazard_walker during the very first pass it performs on
>> query-tree.  Basically, in the SubLink node check, we can detect
>> whether the subselect has Limit/Offset clause and if so, then we can
>> treat it as parallel_unsafe.  I have tried that way and it prohibits
>> the parallel plan for the reported queries.  However, I think more
>> analysis and verification is required to see if it can happen in any
>> other related cases.
>
>
> This seems broken as well:
>
>     create table qwr(a int not null, b int not null, c text not null);
>     insert into qwr select i, i, (select prosrc from pg_proc where
> oid=11734) from generate_series(1, 128000) i;
>     set parallel_setup_cost to 0;
>     analyze qwr;
>     select count(*) from qwr where (a, b) in (select a, row_number() over()
> from qwr);
>

I am getting below error in above steps:

postgres=#     insert into qwr select i, i, (select prosrc from
pg_proc where oid=11734) from generate_series(1, 128000) i;
ERROR:  null value in column "c" violates not-null constraint
DETAIL:  Failing row contains (1, 1, null).

If I remove 'not null' constraint from column c, then the above
statement works fine, but I am getting below plan which is a serial
plan:

postgres=# Explain select count(*) from qwr where (a, b) in (select a,
row_number() over() from qwr)
                                       QUERY PLAN
-----------------------------------------------------------------------------------------
 Aggregate  (cost=12360.00..12360.01 rows=1 width=8)
   ->  Hash Semi Join  (cost=7272.00..12200.00 rows=64000 width=0)
         Hash Cond: ((qwr.a = qwr_1.a) AND (qwr.b = (row_number() OVER (?))))
         ->  Seq Scan on qwr  (cost=0.00..1847.00 rows=128000 width=8)
         ->  Hash  (cost=4727.00..4727.00 rows=128000 width=12)
               ->  WindowAgg  (cost=0.00..3447.00 rows=128000 width=12)
                     ->  Seq Scan on qwr qwr_1  (cost=0.00..1847.00
rows=128000 width=4)
(7 rows)

I am not sure why I am not seeing the same problem as you.

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-14 11:12  Marko Tiikkaja <marko@joh.to>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 38+ messages in thread

From: Marko Tiikkaja @ 2018-08-14 11:12 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

Hi Amit,

On Tue, Aug 14, 2018 at 2:09 PM, Amit Kapila <amit.kapila16@gmail.com>
wrote:

> On Tue, Aug 14, 2018 at 3:52 PM, Marko Tiikkaja <marko@joh.to> wrote:
> > On Tue, Aug 14, 2018 at 7:10 AM, Amit Kapila <amit.kapila16@gmail.com>
> > wrote:
> >>
> >> Yeah, one idea could be that we detect this in
> >> max_parallel_hazard_walker during the very first pass it performs on
> >> query-tree.  Basically, in the SubLink node check, we can detect
> >> whether the subselect has Limit/Offset clause and if so, then we can
> >> treat it as parallel_unsafe.  I have tried that way and it prohibits
> >> the parallel plan for the reported queries.  However, I think more
> >> analysis and verification is required to see if it can happen in any
> >> other related cases.
> >
> >
> > This seems broken as well:
> >
> >     create table qwr(a int not null, b int not null, c text not null);
> >     insert into qwr select i, i, (select prosrc from pg_proc where
> > oid=11734) from generate_series(1, 128000) i;
> >     set parallel_setup_cost to 0;
> >     analyze qwr;
> >     select count(*) from qwr where (a, b) in (select a, row_number()
> over()
> > from qwr);
> >
>
> I am getting below error in above steps:
>
> postgres=#     insert into qwr select i, i, (select prosrc from
> pg_proc where oid=11734) from generate_series(1, 128000) i;
> ERROR:  null value in column "c" violates not-null constraint
> DETAIL:  Failing row contains (1, 1, null).
>

Sorry, try this instead:

 insert into qwr select i, i, (select prosrc from pg_proc where
oid='ts_debug(regconfig,text)'::regprocedure) from generate_series(1,
128000) i;


.m

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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-14 11:50  Amit Kapila <amit.kapila16@gmail.com>
  parent: Marko Tiikkaja <marko@joh.to>
  0 siblings, 1 reply; 38+ messages in thread

From: Amit Kapila @ 2018-08-14 11:50 UTC (permalink / raw)
  To: Marko Tiikkaja <marko@joh.to>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Tue, Aug 14, 2018 at 4:42 PM, Marko Tiikkaja <marko@joh.to> wrote:
> Hi Amit,
>
>> >
>> > This seems broken as well:
>> >
>> >     create table qwr(a int not null, b int not null, c text not null);
>> >     insert into qwr select i, i, (select prosrc from pg_proc where
>> > oid=11734) from generate_series(1, 128000) i;
>> >     set parallel_setup_cost to 0;
>> >     analyze qwr;
>> >     select count(*) from qwr where (a, b) in (select a, row_number()
>> > over()
>> > from qwr);
>> >
>>
>> I am getting below error in above steps:
>>
>> postgres=#     insert into qwr select i, i, (select prosrc from
>> pg_proc where oid=11734) from generate_series(1, 128000) i;
>> ERROR:  null value in column "c" violates not-null constraint
>> DETAIL:  Failing row contains (1, 1, null).
>
>
> Sorry, try this instead:
>
>  insert into qwr select i, i, (select prosrc from pg_proc where
> oid='ts_debug(regconfig,text)'::regprocedure) from generate_series(1,
> 128000) i;
>

This looks related, but I think this is a different issue.  The real
reason for this case is that row_number is marked as parallel_safe
which seems to be wrong.  I think it should be marked as
parallel_unsafe.   This needs some more analysis w.r.t which other
Window functions has a similar problem.

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-14 12:20  Marko Tiikkaja <marko@joh.to>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 38+ messages in thread

From: Marko Tiikkaja @ 2018-08-14 12:20 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Tue, Aug 14, 2018 at 2:50 PM, Amit Kapila <amit.kapila16@gmail.com>
wrote:

> This looks related, but I think this is a different issue.


Sure.


> The real
> reason for this case is that row_number is marked as parallel_safe
> which seems to be wrong.  I think it should be marked as
> parallel_unsafe.


Marking the function parallel safe doesn't seem wrong to me.  The
non-parallel-safe part is that the input gets fed to it in different order
in different workers.  And I don't really think that to be the function's
fault.


.m

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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-14 15:44  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Marko Tiikkaja <marko@joh.to>
  0 siblings, 2 replies; 38+ messages in thread

From: Tom Lane @ 2018-08-14 15:44 UTC (permalink / raw)
  To: Marko Tiikkaja <marko@joh.to>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

Marko Tiikkaja <marko@joh.to> writes:
> Marking the function parallel safe doesn't seem wrong to me.  The
> non-parallel-safe part is that the input gets fed to it in different order
> in different workers.  And I don't really think that to be the function's
> fault.

So that basically opens the question of whether *any* window function
calculation can safely be pushed down to parallel workers.

Somewhat like the LIMIT/OFFSET case, it seems to me that we could only
expect to do this safely if the row ordering induced by the WINDOW clause
can be proven to be fully deterministic.  The planner has no such smarts
at the moment AFAIR.  In principle you could do it if there were
partitioning/ordering by a primary key, but I'm not excited about the
prospects of that being true often enough in practice to justify making
the check.

			regards, tom lane




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-15 00:44  Andrew Gierth <andrew@tao11.riddles.org.uk>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 0 replies; 38+ messages in thread

From: Andrew Gierth @ 2018-08-15 00:44 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Marko Tiikkaja <marko@joh.to>; Amit Kapila <amit.kapila16@gmail.com>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

>>>>> "Tom" == Tom Lane <tgl@sss.pgh.pa.us> writes:

 >> Marking the function parallel safe doesn't seem wrong to me. The
 >> non-parallel-safe part is that the input gets fed to it in different
 >> order in different workers. And I don't really think that to be the
 >> function's fault.

 Tom> So that basically opens the question of whether *any* window
 Tom> function calculation can safely be pushed down to parallel
 Tom> workers.

Grepping the spec for the phrase "possibly non-deterministic" is quite
enlightening. Leaving out non-determinisms caused by timezone or actual
volatility, leaving out cases of non-determinism that we'd call
"stable", and leaving out features like multisets that we don't support
at all, here's the list of interesting cases (comments after each quoted
paragraph are mine):

6.28 <value expression>

  d) An <array value constructor by query>.

i.e. ARRAY(select)

  o) An <aggregate function> that specifies MIN or MAX and that simply
     contains a <value expression> whose declared type is based on a
     character string type, user-defined type, or datetime with time
     zone type.

i.e. MIN(x) is non-deterministic if "x" can have distinguishable values
that compare equal. PG doesn't have that for text or timestamptz, unlike
the spec, but it does for citext or other user-defined types.

  q) An <array aggregate function>.

i.e. array_agg()

  u) A <window function> that specifies ROW_NUMBER, FIRST_VALUE,
     LAST_VALUE, NTH_VALUE, NTILE, LEAD, or LAG, or whose associated
     <window specification> specifies ROWS.

This covers those cases where window functions don't treat peer rows
together.

7.6 <table reference>

  27) A <table reference> is possibly non-deterministic if the simply
      contained <table primary> or <joined table> is possibly
      non-deterministic or if <sample clause> is specified.

i.e. TABLESAMPLE is non-deterministic

7.16 <query specification>

  a) The <set quantifier> DISTINCT is specified and one of the columns
     of T has a data type of character string, user-defined type, TIME
     WITH TIME ZONE, or TIMESTAMP WITH TIME ZONE.

  c) The <select list>, <having clause>, or <window clause> contains a
     reference to a column C of T that has a data type of character
     string, user-defined type, TIME WITH TIME ZONE, or TIMESTAMP WITH
     TIME ZONE, and the functional dependency G C, where G is the set
     consisting of the grouping columns of T, holds in T.

For both the above two cases, if distinguishable values of a type
compare equal, it's non-deterministic which gets into the result.

7.17 <query expression>

  a) The <query expression> contains a <result offset clause>.

  b) The <query expression> contains a <fetch first clause>.

  f) Both of the following are true:

    i) T contains a set operator UNION and ALL is not specified, or T
       contains either of the set operators EXCEPT or INTERSECT.

   ii) At least one of the following is true:

       1) The first or second operand contains a column that has a
          declared type of character string.

       2) The first or second operand contains a column that has a
          declared type of datetime with time zone.

       3) The first or second operand contains a column that has a
          declared type that is a user-defined type.

(I've left out the many clauses which just amount to "if $thing contains
something which is possibly non-deterministic then it is possibly
non-deterministic")

-- 
Andrew (irc:RhodiumToad)




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-15 06:51  Amit Kapila <amit.kapila16@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  1 sibling, 1 reply; 38+ messages in thread

From: Amit Kapila @ 2018-08-15 06:51 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Tue, Aug 14, 2018 at 9:14 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Marko Tiikkaja <marko@joh.to> writes:
>> Marking the function parallel safe doesn't seem wrong to me.  The
>> non-parallel-safe part is that the input gets fed to it in different order
>> in different workers.  And I don't really think that to be the function's
>> fault.
>
> So that basically opens the question of whether *any* window function
> calculation can safely be pushed down to parallel workers.
>

I think we can consider it as a parallel-restricted operation.  For
the purpose of testing, I have marked row_number as
parallel-restricted in pg_proc and I get the below plan:

postgres=# Explain select count(*) from qwr where (a, b) in (select a,
row_number() over() from qwr);
                                               QUERY PLAN
--------------------------------------------------------------------------------------------------------
 Aggregate  (cost=46522.12..46522.13 rows=1 width=8)
   ->  Hash Semi Join  (cost=24352.08..46362.12 rows=64001 width=0)
         Hash Cond: ((qwr.a = qwr_1.a) AND (qwr.b = (row_number() OVER (?))))
         ->  Gather  (cost=0.00..18926.01 rows=128002 width=8)
               Workers Planned: 2
               ->  Parallel Seq Scan on qwr  (cost=0.00..18926.01
rows=64001 width=8)
         ->  Hash  (cost=21806.06..21806.06 rows=128002 width=12)
               ->  WindowAgg  (cost=0.00..20526.04 rows=128002 width=12)
                     ->  Gather  (cost=0.00..18926.01 rows=128002 width=4)
                           Workers Planned: 2
                           ->  Parallel Seq Scan on qwr qwr_1
(cost=0.00..18926.01 rows=64001 width=4)
(11 rows)

This seems okay, though the results of the above parallel-execution
are not same as serial-execution.  I think the reason for it is that
we don't get rows in predictable order from workers.

> Somewhat like the LIMIT/OFFSET case, it seems to me that we could only
> expect to do this safely if the row ordering induced by the WINDOW clause
> can be proven to be fully deterministic.  The planner has no such smarts
> at the moment AFAIR.  In principle you could do it if there were
> partitioning/ordering by a primary key, but I'm not excited about the
> prospects of that being true often enough in practice to justify making
> the check.
>

Yeah, I am also not sure if it is worth adding the additional checks.
So, for now, we can treat any window function calculation as
parallel-restricted and if later anybody has a reason strong enough to
relax the restriction for some particular case, we will consider it.

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-15 11:10  Stephen Frost <sfrost@snowman.net>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 38+ messages in thread

From: Stephen Frost @ 2018-08-15 11:10 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

Greetings,

* Amit Kapila (amit.kapila16@gmail.com) wrote:
> On Tue, Aug 14, 2018 at 9:14 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> > Marko Tiikkaja <marko@joh.to> writes:
> >> Marking the function parallel safe doesn't seem wrong to me.  The
> >> non-parallel-safe part is that the input gets fed to it in different order
> >> in different workers.  And I don't really think that to be the function's
> >> fault.
> >
> > So that basically opens the question of whether *any* window function
> > calculation can safely be pushed down to parallel workers.
> 
> I think we can consider it as a parallel-restricted operation.  For
> the purpose of testing, I have marked row_number as
> parallel-restricted in pg_proc and I get the below plan:
> 
> postgres=# Explain select count(*) from qwr where (a, b) in (select a,
> row_number() over() from qwr);
>                                                QUERY PLAN
> --------------------------------------------------------------------------------------------------------
>  Aggregate  (cost=46522.12..46522.13 rows=1 width=8)
>    ->  Hash Semi Join  (cost=24352.08..46362.12 rows=64001 width=0)
>          Hash Cond: ((qwr.a = qwr_1.a) AND (qwr.b = (row_number() OVER (?))))
>          ->  Gather  (cost=0.00..18926.01 rows=128002 width=8)
>                Workers Planned: 2
>                ->  Parallel Seq Scan on qwr  (cost=0.00..18926.01
> rows=64001 width=8)
>          ->  Hash  (cost=21806.06..21806.06 rows=128002 width=12)
>                ->  WindowAgg  (cost=0.00..20526.04 rows=128002 width=12)
>                      ->  Gather  (cost=0.00..18926.01 rows=128002 width=4)
>                            Workers Planned: 2
>                            ->  Parallel Seq Scan on qwr qwr_1
> (cost=0.00..18926.01 rows=64001 width=4)
> (11 rows)
> 
> This seems okay, though the results of the above parallel-execution
> are not same as serial-execution.  I think the reason for it is that
> we don't get rows in predictable order from workers.

You wouldn't get them in a predictable order even without
parallelization due to the lack of an ordering, so this hardly seems
like an issue.

> > Somewhat like the LIMIT/OFFSET case, it seems to me that we could only
> > expect to do this safely if the row ordering induced by the WINDOW clause
> > can be proven to be fully deterministic.  The planner has no such smarts
> > at the moment AFAIR.  In principle you could do it if there were
> > partitioning/ordering by a primary key, but I'm not excited about the
> > prospects of that being true often enough in practice to justify making
> > the check.
> 
> Yeah, I am also not sure if it is worth adding the additional checks.
> So, for now, we can treat any window function calculation as
> parallel-restricted and if later anybody has a reason strong enough to
> relax the restriction for some particular case, we will consider it.

Seems likely that we'll want this at some point, but certainly seems
like new work and not a small bit of it.

Thanks!

Stephen

Attachments:

  signature.asc (application/pgp-signature, 818B) download

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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-16 03:55  Amit Kapila <amit.kapila16@gmail.com>
  parent: Stephen Frost <sfrost@snowman.net>
  0 siblings, 2 replies; 38+ messages in thread

From: Amit Kapila @ 2018-08-16 03:55 UTC (permalink / raw)
  To: Stephen Frost <sfrost@snowman.net>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Wed, Aug 15, 2018 at 4:40 PM, Stephen Frost <sfrost@snowman.net> wrote:
> Greetings,
>
> * Amit Kapila (amit.kapila16@gmail.com) wrote:
>> On Tue, Aug 14, 2018 at 9:14 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
>> > Marko Tiikkaja <marko@joh.to> writes:
>> >> Marking the function parallel safe doesn't seem wrong to me.  The
>> >> non-parallel-safe part is that the input gets fed to it in different order
>> >> in different workers.  And I don't really think that to be the function's
>> >> fault.
>> >
>> > So that basically opens the question of whether *any* window function
>> > calculation can safely be pushed down to parallel workers.
>>
>> I think we can consider it as a parallel-restricted operation.  For
>> the purpose of testing, I have marked row_number as
>> parallel-restricted in pg_proc and I get the below plan:
>>
>> postgres=# Explain select count(*) from qwr where (a, b) in (select a,
>> row_number() over() from qwr);
>>                                                QUERY PLAN
>> --------------------------------------------------------------------------------------------------------
>>  Aggregate  (cost=46522.12..46522.13 rows=1 width=8)
>>    ->  Hash Semi Join  (cost=24352.08..46362.12 rows=64001 width=0)
>>          Hash Cond: ((qwr.a = qwr_1.a) AND (qwr.b = (row_number() OVER (?))))
>>          ->  Gather  (cost=0.00..18926.01 rows=128002 width=8)
>>                Workers Planned: 2
>>                ->  Parallel Seq Scan on qwr  (cost=0.00..18926.01
>> rows=64001 width=8)
>>          ->  Hash  (cost=21806.06..21806.06 rows=128002 width=12)
>>                ->  WindowAgg  (cost=0.00..20526.04 rows=128002 width=12)
>>                      ->  Gather  (cost=0.00..18926.01 rows=128002 width=4)
>>                            Workers Planned: 2
>>                            ->  Parallel Seq Scan on qwr qwr_1
>> (cost=0.00..18926.01 rows=64001 width=4)
>> (11 rows)
>>
>> This seems okay, though the results of the above parallel-execution
>> are not same as serial-execution.  I think the reason for it is that
>> we don't get rows in predictable order from workers.
>
> You wouldn't get them in a predictable order even without
> parallelization due to the lack of an ordering, so this hardly seems
> like an issue.
>

Right.

>> > Somewhat like the LIMIT/OFFSET case, it seems to me that we could only
>> > expect to do this safely if the row ordering induced by the WINDOW clause
>> > can be proven to be fully deterministic.  The planner has no such smarts
>> > at the moment AFAIR.  In principle you could do it if there were
>> > partitioning/ordering by a primary key, but I'm not excited about the
>> > prospects of that being true often enough in practice to justify making
>> > the check.
>>
>> Yeah, I am also not sure if it is worth adding the additional checks.
>> So, for now, we can treat any window function calculation as
>> parallel-restricted and if later anybody has a reason strong enough to
>> relax the restriction for some particular case, we will consider it.
>
> Seems likely that we'll want this at some point, but certainly seems
> like new work and not a small bit of it.
>

Yeah, let me summarize the problems which require patches:
(a) Consider the presence of a LIMIT/OFFSET in a sub-select as making
it parallel-unsafe.
(b) Consider the presence of any window function calculation as
parallel-restricted operation.

Initially, I will prepare two separate patches for them and then we
will see if we want to combine them into one before committing.  It
might take me few days to come up with patches, so if anyone else
wants to take a lead, feel free to do so.

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-16 06:17  Andrew Fletcher <andy@prestigedigital.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 1 reply; 38+ messages in thread

From: Andrew Fletcher @ 2018-08-16 06:17 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Stephen Frost <sfrost@snowman.net>; Tom Lane <tgl@sss.pgh.pa.us>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

>
> (a) Consider the presence of a LIMIT/OFFSET in a sub-select as making
> it parallel-unsafe.


Presence of a LIMIT/OFFSET in a sub-select without an ORDER BY?

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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-16 06:59  Amit Kapila <amit.kapila16@gmail.com>
  parent: Andrew Fletcher <andy@prestigedigital.com>
  0 siblings, 0 replies; 38+ messages in thread

From: Amit Kapila @ 2018-08-16 06:59 UTC (permalink / raw)
  To: Andrew Fletcher <andy@prestigedigital.com>; +Cc: Stephen Frost <sfrost@snowman.net>; Tom Lane <tgl@sss.pgh.pa.us>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Thu, Aug 16, 2018 at 11:47 AM, Andrew Fletcher
<andy@prestigedigital.com> wrote:
>> (a) Consider the presence of a LIMIT/OFFSET in a sub-select as making
>> it parallel-unsafe.
>
>
> Presence of a LIMIT/OFFSET in a sub-select without an ORDER BY?
>

Yes, I wanted to do that, but Tom doesn't seem to like that especially
for back-branches.  Let me try to prepare a patch and then we can see
based on the complexity of fix.

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-20 10:50  Amit Kapila <amit.kapila16@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 2 replies; 38+ messages in thread

From: Amit Kapila @ 2018-08-20 10:50 UTC (permalink / raw)
  To: Stephen Frost <sfrost@snowman.net>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Thu, Aug 16, 2018 at 9:25 AM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Wed, Aug 15, 2018 at 4:40 PM, Stephen Frost <sfrost@snowman.net> wrote:
>> Greetings,
>>
>
> Yeah, let me summarize the problems which require patches:
> (a) Consider the presence of a LIMIT/OFFSET in a sub-select as making
> it parallel-unsafe.
>

As mentioned up-thread, I have considered adding a check in
max_parallel_hazard_walker, but it turns out that it will make the
whole query parallel-unsafe even if one of the sub-selects has
Limit/Offset.  I think the better idea is to detect that during
set_rel_consider_parallel.  Attached patch
prohibit_parallel_limit_subselect_v2 implements the fix for same.

I have also tried to consider waving off the case when Order By is
present in the sub-select, but for that, I think we need to ensure
that Order By is on the same column as the target list.  It is not
clear to me whether adding additional code checks to detect that is
valuable because it can consume planner time for some cases.  Also, I
think it is not advisable to have such checks for the back-branches as
pointed by Tom as well.  So, I didn't do anything about it.

> (b) Consider the presence of any window function calculation as
> parallel-restricted operation.
>

For this, we need to mark all the window functions like row_number,
rank, dense_rank, etc as parallel-restricted.   Additionally, we also
need to detect the presence of aggregate functions that act as window
functions (when an OVER clause follows the call).   Attached patch
treat_window_func_calc_parallel_restricted_v1 implements the fix.

> Initially, I will prepare two separate patches for them and then we
> will see if we want to combine them into one before committing.
>

One can apply patches in the order
prohibit_parallel_limit_subselect_v2 and
treat_window_func_calc_parallel_restricted_v1.

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com

Attachments: download all (2 files, .tar.gz)

prohibit_parallel_limit_subselect_v2.patch (application/octet-stream, 3.9K) download diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index 0e80aeb..39c73ec 100644 --- a/src/backend/optimizer/path/allpaths.c +++ b/src/backend/optimizer/path/allpaths.c @@ -620,7 +620,17 @@ set_rel_consider_parallel(PlannerInfo *root, RelOptInfo *rel, * the SubqueryScanPath as not parallel-safe. (Note that * set_subquery_pathlist() might push some of these quals down * into the subquery itself, but that doesn't change anything.) + * + * We can't push sub-select containing LIMIT/OFFSET to workers as + * that can change the results depending on what is beneath LIMIT + * node. So, consider that case as parallel-unsafe. */ + { + Query *subquery = castNode(Query, rte->subquery); + + if (limit_needed(subquery)) + return; + } break; case RTE_JOIN: diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 96bf060..e589471 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -123,7 +123,6 @@ static void preprocess_rowmarks(PlannerInfo *root); static double preprocess_limit(PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est); -static bool limit_needed(Query *parse); static void remove_useless_groupby_columns(PlannerInfo *root); static List *preprocess_groupclause(PlannerInfo *root, List *force); static List *extract_rollup_sets(List *groupingSets); @@ -2870,7 +2869,7 @@ preprocess_limit(PlannerInfo *root, double tuple_fraction, * a key distinction: here we need hard constants in OFFSET/LIMIT, whereas * in preprocess_limit it's good enough to consider estimated values. */ -static bool +bool limit_needed(Query *parse) { Node *node; diff --git a/src/include/optimizer/planner.h b/src/include/optimizer/planner.h index c090396..3e733b3 100644 --- a/src/include/optimizer/planner.h +++ b/src/include/optimizer/planner.h @@ -47,6 +47,8 @@ extern bool is_dummy_plan(Plan *plan); extern RowMarkType select_rowmark_type(RangeTblEntry *rte, LockClauseStrength strength); +extern bool limit_needed(Query *parse); + extern void mark_partial_aggref(Aggref *agg, AggSplit aggsplit); extern Path *get_cheapest_fractional_path(RelOptInfo *rel, diff --git a/src/test/regress/expected/select_parallel.out b/src/test/regress/expected/select_parallel.out index f1b8cd4..ad03807 100644 --- a/src/test/regress/expected/select_parallel.out +++ b/src/test/regress/expected/select_parallel.out @@ -958,6 +958,25 @@ select count(*) from tenk1; reset force_parallel_mode; reset role; +-- LIMIT/OFFSET within sub-selects can't be pushed to workers. +explain (costs off) +select * from tenk1 where two in + (select two from tenk1 where stringu1 like '%AAAA' limit 3); + QUERY PLAN +--------------------------------------------------------------- + Hash Semi Join + Hash Cond: (tenk1.two = tenk1_1.two) + -> Gather + Workers Planned: 4 + -> Parallel Seq Scan on tenk1 + -> Hash + -> Limit + -> Gather + Workers Planned: 4 + -> Parallel Seq Scan on tenk1 tenk1_1 + Filter: (stringu1 ~~ '%AAAA'::text) +(11 rows) + -- to increase the parallel query test coverage SAVEPOINT settings; SET LOCAL force_parallel_mode = 1; diff --git a/src/test/regress/sql/select_parallel.sql b/src/test/regress/sql/select_parallel.sql index 7771e05..aea2461 100644 --- a/src/test/regress/sql/select_parallel.sql +++ b/src/test/regress/sql/select_parallel.sql @@ -362,6 +362,11 @@ select count(*) from tenk1; reset force_parallel_mode; reset role; +-- LIMIT/OFFSET within sub-selects can't be pushed to workers. +explain (costs off) +select * from tenk1 where two in + (select two from tenk1 where stringu1 like '%AAAA' limit 3); + -- to increase the parallel query test coverage SAVEPOINT settings; SET LOCAL force_parallel_mode = 1;
treat_window_func_calc_parallel_restricted_v1.patch (application/octet-stream, 10.9K) download diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index a04ad6e..1c7136f 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -1197,6 +1197,19 @@ max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context) } /* + * Treat window functions as parallel-restricted as the row ordering + * induced by them is non-deterministic. We can relax this condition for + * cases where the row ordering can be deterministic like when there is + * an ORDER BY on the primary key, but those cases don't seem to be + * interesting enough to have additional checks. + */ + if (IsA(node, WindowFunc)) + { + if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context)) + return true; + } + + /* * As a notational convenience for callers, look through RestrictInfo. */ else if (IsA(node, RestrictInfo)) diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index a146510..a641b8c 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -9413,51 +9413,62 @@ # SQL-spec window functions { oid => '3100', descr => 'row number within partition', proname => 'row_number', prokind => 'w', proisstrict => 'f', - prorettype => 'int8', proargtypes => '', prosrc => 'window_row_number' }, + proparallel => 'r', prorettype => 'int8', proargtypes => '', + prosrc => 'window_row_number' }, { oid => '3101', descr => 'integer rank with gaps', - proname => 'rank', prokind => 'w', proisstrict => 'f', prorettype => 'int8', - proargtypes => '', prosrc => 'window_rank' }, + proname => 'rank', prokind => 'w', proisstrict => 'f', proparallel => 'r', + prorettype => 'int8', proargtypes => '', prosrc => 'window_rank' }, { oid => '3102', descr => 'integer rank without gaps', proname => 'dense_rank', prokind => 'w', proisstrict => 'f', - prorettype => 'int8', proargtypes => '', prosrc => 'window_dense_rank' }, + proparallel => 'r', prorettype => 'int8', proargtypes => '', + prosrc => 'window_dense_rank' }, { oid => '3103', descr => 'fractional rank within partition', proname => 'percent_rank', prokind => 'w', proisstrict => 'f', - prorettype => 'float8', proargtypes => '', prosrc => 'window_percent_rank' }, + proparallel => 'r', prorettype => 'float8', proargtypes => '', + prosrc => 'window_percent_rank' }, { oid => '3104', descr => 'fractional row number within partition', proname => 'cume_dist', prokind => 'w', proisstrict => 'f', - prorettype => 'float8', proargtypes => '', prosrc => 'window_cume_dist' }, + proparallel => 'r', prorettype => 'float8', proargtypes => '', + prosrc => 'window_cume_dist' }, { oid => '3105', descr => 'split rows into N groups', - proname => 'ntile', prokind => 'w', prorettype => 'int4', - proargtypes => 'int4', prosrc => 'window_ntile' }, + proname => 'ntile', prokind => 'w', proparallel => 'r', + prorettype => 'int4', proargtypes => 'int4', prosrc => 'window_ntile' }, { oid => '3106', descr => 'fetch the preceding row value', - proname => 'lag', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement', prosrc => 'window_lag' }, + proname => 'lag', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement', + prosrc => 'window_lag' }, { oid => '3107', descr => 'fetch the Nth preceding row value', - proname => 'lag', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement int4', prosrc => 'window_lag_with_offset' }, + proname => 'lag', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement int4', + prosrc => 'window_lag_with_offset' }, { oid => '3108', descr => 'fetch the Nth preceding row value with default', - proname => 'lag', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement int4 anyelement', + proname => 'lag', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement int4 anyelement', prosrc => 'window_lag_with_offset_and_default' }, { oid => '3109', descr => 'fetch the following row value', - proname => 'lead', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement', prosrc => 'window_lead' }, + proname => 'lead', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement', + prosrc => 'window_lead' }, { oid => '3110', descr => 'fetch the Nth following row value', - proname => 'lead', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement int4', prosrc => 'window_lead_with_offset' }, + proname => 'lead', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement int4', + prosrc => 'window_lead_with_offset' }, { oid => '3111', descr => 'fetch the Nth following row value with default', - proname => 'lead', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement int4 anyelement', + proname => 'lead', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement int4 anyelement', prosrc => 'window_lead_with_offset_and_default' }, { oid => '3112', descr => 'fetch the first row value', - proname => 'first_value', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement', prosrc => 'window_first_value' }, + proname => 'first_value', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement', + prosrc => 'window_first_value' }, { oid => '3113', descr => 'fetch the last row value', - proname => 'last_value', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement', prosrc => 'window_last_value' }, + proname => 'last_value', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement', + prosrc => 'window_last_value' }, { oid => '3114', descr => 'fetch the Nth row value', - proname => 'nth_value', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement int4', prosrc => 'window_nth_value' }, + proname => 'nth_value', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement int4', + prosrc => 'window_nth_value' }, # functions for range types { oid => '3832', descr => 'I/O', @@ -9957,41 +9968,41 @@ # hypothetical-set aggregates (and their support functions) { oid => '3986', descr => 'rank of hypothetical row', proname => 'rank', provariadic => 'any', prokind => 'a', proisstrict => 'f', - prorettype => 'int8', proargtypes => 'any', proallargtypes => '{any}', - proargmodes => '{v}', prosrc => 'aggregate_dummy' }, + proparallel => 'r', prorettype => 'int8', proargtypes => 'any', + proallargtypes => '{any}', proargmodes => '{v}', prosrc => 'aggregate_dummy' }, { oid => '3987', descr => 'aggregate final function', proname => 'rank_final', provariadic => 'any', proisstrict => 'f', - prorettype => 'int8', proargtypes => 'internal any', + proparallel => 'r', prorettype => 'int8', proargtypes => 'internal any', proallargtypes => '{internal,any}', proargmodes => '{i,v}', prosrc => 'hypothetical_rank_final' }, { oid => '3988', descr => 'fractional rank of hypothetical row', proname => 'percent_rank', provariadic => 'any', prokind => 'a', - proisstrict => 'f', prorettype => 'float8', proargtypes => 'any', - proallargtypes => '{any}', proargmodes => '{v}', + proisstrict => 'f', proparallel => 'r', prorettype => 'float8', + proargtypes => 'any', proallargtypes => '{any}', proargmodes => '{v}', prosrc => 'aggregate_dummy' }, { oid => '3989', descr => 'aggregate final function', proname => 'percent_rank_final', provariadic => 'any', proisstrict => 'f', - prorettype => 'float8', proargtypes => 'internal any', + proparallel => 'r', prorettype => 'float8', proargtypes => 'internal any', proallargtypes => '{internal,any}', proargmodes => '{i,v}', prosrc => 'hypothetical_percent_rank_final' }, { oid => '3990', descr => 'cumulative distribution of hypothetical row', proname => 'cume_dist', provariadic => 'any', prokind => 'a', - proisstrict => 'f', prorettype => 'float8', proargtypes => 'any', - proallargtypes => '{any}', proargmodes => '{v}', + proisstrict => 'f', proparallel => 'r', prorettype => 'float8', + proargtypes => 'any', proallargtypes => '{any}', proargmodes => '{v}', prosrc => 'aggregate_dummy' }, { oid => '3991', descr => 'aggregate final function', proname => 'cume_dist_final', provariadic => 'any', proisstrict => 'f', - prorettype => 'float8', proargtypes => 'internal any', + proparallel => 'r', prorettype => 'float8', proargtypes => 'internal any', proallargtypes => '{internal,any}', proargmodes => '{i,v}', prosrc => 'hypothetical_cume_dist_final' }, { oid => '3992', descr => 'rank of hypothetical row without gaps', proname => 'dense_rank', provariadic => 'any', prokind => 'a', - proisstrict => 'f', prorettype => 'int8', proargtypes => 'any', - proallargtypes => '{any}', proargmodes => '{v}', + proisstrict => 'f', proparallel => 'r', prorettype => 'int8', + proargtypes => 'any', proallargtypes => '{any}', proargmodes => '{v}', prosrc => 'aggregate_dummy' }, { oid => '3993', descr => 'aggregate final function', proname => 'dense_rank_final', provariadic => 'any', proisstrict => 'f', - prorettype => 'int8', proargtypes => 'internal any', + proparallel => 'r', prorettype => 'int8', proargtypes => 'internal any', proallargtypes => '{internal,any}', proargmodes => '{i,v}', prosrc => 'hypothetical_dense_rank_final' }, diff --git a/src/test/regress/expected/select_parallel.out b/src/test/regress/expected/select_parallel.out index ad03807..bb96931 100644 --- a/src/test/regress/expected/select_parallel.out +++ b/src/test/regress/expected/select_parallel.out @@ -977,6 +977,21 @@ select * from tenk1 where two in Filter: (stringu1 ~~ '%AAAA'::text) (11 rows) +-- Window function calculation can't be pushed to workers. +explain (costs off, verbose) +select two, row_number() over() from tenk1 where two > 100; + QUERY PLAN +----------------------------------------------- + WindowAgg + Output: two, row_number() OVER (?) + -> Gather + Output: two + Workers Planned: 4 + -> Parallel Seq Scan on public.tenk1 + Output: two + Filter: (tenk1.two > 100) +(8 rows) + -- to increase the parallel query test coverage SAVEPOINT settings; SET LOCAL force_parallel_mode = 1; diff --git a/src/test/regress/sql/select_parallel.sql b/src/test/regress/sql/select_parallel.sql index aea2461..7e30543 100644 --- a/src/test/regress/sql/select_parallel.sql +++ b/src/test/regress/sql/select_parallel.sql @@ -367,6 +367,10 @@ explain (costs off) select * from tenk1 where two in (select two from tenk1 where stringu1 like '%AAAA' limit 3); +-- Window function calculation can't be pushed to workers. +explain (costs off, verbose) +select two, row_number() over() from tenk1 where two > 100; + -- to increase the parallel query test coverage SAVEPOINT settings; SET LOCAL force_parallel_mode = 1;
^ permalink raw reply [nested|flat] 38+ messages in thread

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-20 10:52  Amit Kapila <amit.kapila16@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 1 reply; 38+ messages in thread

From: Amit Kapila @ 2018-08-20 10:52 UTC (permalink / raw)
  To: Stephen Frost <sfrost@snowman.net>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Mon, Aug 20, 2018 at 4:20 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Thu, Aug 16, 2018 at 9:25 AM, Amit Kapila <amit.kapila16@gmail.com> wrote:
>> On Wed, Aug 15, 2018 at 4:40 PM, Stephen Frost <sfrost@snowman.net> wrote:
>> (b) Consider the presence of any window function calculation as
>> parallel-restricted operation.
>>
>
> For this, we need to mark all the window functions like row_number,
> rank, dense_rank, etc as parallel-restricted.   Additionally, we also
> need to detect the presence of aggregate functions that act as window
> functions (when an OVER clause follows the call).   Attached patch
> treat_window_func_calc_parallel_restricted_v1 implements the fix.
>

As this patch changes the catalog contents, we need to bump catalog
version number.  However, I have left it for later once we get a
review and or testing of the patch.

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-20 13:29  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 38+ messages in thread

From: Tom Lane @ 2018-08-20 13:29 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Stephen Frost <sfrost@snowman.net>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

Amit Kapila <amit.kapila16@gmail.com> writes:
> On Mon, Aug 20, 2018 at 4:20 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
>> On Thu, Aug 16, 2018 at 9:25 AM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Wed, Aug 15, 2018 at 4:40 PM, Stephen Frost <sfrost@snowman.net> wrote:
>>> (b) Consider the presence of any window function calculation as
>>> parallel-restricted operation.

>> For this, we need to mark all the window functions like row_number,
>> rank, dense_rank, etc as parallel-restricted.   Additionally, we also
>> need to detect the presence of aggregate functions that act as window
>> functions (when an OVER clause follows the call).   Attached patch
>> treat_window_func_calc_parallel_restricted_v1 implements the fix.

> As this patch changes the catalog contents, we need to bump catalog
> version number.  However, I have left it for later once we get a
> review and or testing of the patch.

Sounds to me like you're using the wrong approach.  I would just consider
any Agg or WindowFunc node as parallel-restricted regardless of the
function it references.

			regards, tom lane




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-08-21 03:14  Amit Kapila <amit.kapila16@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 2 replies; 38+ messages in thread

From: Amit Kapila @ 2018-08-21 03:14 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Stephen Frost <sfrost@snowman.net>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Mon, Aug 20, 2018 at 6:59 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Amit Kapila <amit.kapila16@gmail.com> writes:
>> On Mon, Aug 20, 2018 at 4:20 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
>>> On Thu, Aug 16, 2018 at 9:25 AM, Amit Kapila <amit.kapila16@gmail.com> wrote:
>> On Wed, Aug 15, 2018 at 4:40 PM, Stephen Frost <sfrost@snowman.net> wrote:
>>>> (b) Consider the presence of any window function calculation as
>>>> parallel-restricted operation.
>
>>> For this, we need to mark all the window functions like row_number,
>>> rank, dense_rank, etc as parallel-restricted.   Additionally, we also
>>> need to detect the presence of aggregate functions that act as window
>>> functions (when an OVER clause follows the call).   Attached patch
>>> treat_window_func_calc_parallel_restricted_v1 implements the fix.
>
>> As this patch changes the catalog contents, we need to bump catalog
>> version number.  However, I have left it for later once we get a
>> review and or testing of the patch.
>
> Sounds to me like you're using the wrong approach.  I would just consider
> any Agg or WindowFunc node as parallel-restricted regardless of the
> function it references.
>

I have below change in the patch which I think is on the lines what
you are describing, do you have something different in mind?

@@ -1197,6 +1197,19 @@ max_parallel_hazard_walker(Node *node,
max_parallel_hazard_context *context)
  }

  /*
+ * Treat window functions as parallel-restricted as the row ordering
+ * induced by them is non-deterministic.  We can relax this condition for
+ * cases where the row ordering can be deterministic like when there is
+ * an ORDER BY on the primary key, but those cases don't seem to be
+ * interesting enough to have additional checks.
+ */
+ if (IsA(node, WindowFunc))
+ {
+ if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
+ return true;
+ }

In addition to the above, I have marked all built-in window functions
as parallel-restricted.  I think even if we don't do that something
like above check should be sufficient, but OTOH, I don't see any
reason to keep the marking of such functions as parallel-safe.  Is
there a reason, why we shouldn't mark them as parallel-restricted?

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-09-02 04:48  Amit Kapila <amit.kapila16@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 1 reply; 38+ messages in thread

From: Amit Kapila @ 2018-09-02 04:48 UTC (permalink / raw)
  To: Stephen Frost <sfrost@snowman.net>; Robert Haas <robertmhaas@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Mon, Aug 20, 2018 at 4:20 PM Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Thu, Aug 16, 2018 at 9:25 AM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> > On Wed, Aug 15, 2018 at 4:40 PM, Stephen Frost <sfrost@snowman.net> wrote:
> >> Greetings,
> >>
> >
> > Yeah, let me summarize the problems which require patches:
> > (a) Consider the presence of a LIMIT/OFFSET in a sub-select as making
> > it parallel-unsafe.
> >
>
> As mentioned up-thread, I have considered adding a check in
> max_parallel_hazard_walker, but it turns out that it will make the
> whole query parallel-unsafe even if one of the sub-selects has
> Limit/Offset.  I think the better idea is to detect that during
> set_rel_consider_parallel.  Attached patch
> prohibit_parallel_limit_subselect_v2 implements the fix for same.
>

I was trying this patch on back-branches and found that it doesn't
apply cleanly beyond PG11, so created separate patches for 10 and 9.6.
  Further, I found that the test for this patch was not failing for
9.6 (without the patch) even though the code doesn't deal with this
problem.  On further investigation, I found that it is because the
commit
655393a022bd653e2b48dbf20b69236981e35195 has not been backpatched to
9.6.  I don't see any reason why we shouldn't backpatch this commit.
So, I have attached a patch (fix_parallel_hash_path_v1.patch) which we
can backpatch in 9.6.

Robert, your input will be highly appreciated here especially for the
back patch (to 9.6) I am proposing?

> > (b) Consider the presence of any window function calculation as
> > parallel-restricted operation.
> >
>
> For this, we need to mark all the window functions like row_number,
> rank, dense_rank, etc as parallel-restricted.   Additionally, we also
> need to detect the presence of aggregate functions that act as window
> functions (when an OVER clause follows the call).   Attached patch
> treat_window_func_calc_parallel_restricted_v1 implements the fix.
>

On again looking at this patch, I found that the test case in the
patch was not sufficient to reproduce the problem reported here, so I
have changed the test on the lines of what is reported in this thread.

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com

Attachments: download all (4 files, .tar.gz)

prohibit_parallel_limit_subselect_v2.rel10.patch (application/octet-stream, 4.1K) download diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index fff2f4c..e122a52 100644 --- a/src/backend/optimizer/path/allpaths.c +++ b/src/backend/optimizer/path/allpaths.c @@ -612,7 +612,17 @@ set_rel_consider_parallel(PlannerInfo *root, RelOptInfo *rel, * the SubqueryScanPath as not parallel-safe. (Note that * set_subquery_pathlist() might push some of these quals down * into the subquery itself, but that doesn't change anything.) + * + * We can't push sub-select containing LIMIT/OFFSET to workers as + * that can change the results depending on what is beneath LIMIT + * node. So, consider that case as parallel-unsafe. */ + { + Query *subquery = castNode(Query, rte->subquery); + + if (limit_needed(subquery)) + return; + } break; case RTE_JOIN: diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 1946f9e..a8a025c 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -121,7 +121,6 @@ static void preprocess_rowmarks(PlannerInfo *root); static double preprocess_limit(PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est); -static bool limit_needed(Query *parse); static void remove_useless_groupby_columns(PlannerInfo *root); static List *preprocess_groupclause(PlannerInfo *root, List *force); static List *extract_rollup_sets(List *groupingSets); @@ -2697,7 +2696,7 @@ preprocess_limit(PlannerInfo *root, double tuple_fraction, * a key distinction: here we need hard constants in OFFSET/LIMIT, whereas * in preprocess_limit it's good enough to consider estimated values. */ -static bool +bool limit_needed(Query *parse) { Node *node; diff --git a/src/include/optimizer/planner.h b/src/include/optimizer/planner.h index 2a4cf71..acb709a 100644 --- a/src/include/optimizer/planner.h +++ b/src/include/optimizer/planner.h @@ -46,6 +46,8 @@ extern bool is_dummy_plan(Plan *plan); extern RowMarkType select_rowmark_type(RangeTblEntry *rte, LockClauseStrength strength); +extern bool limit_needed(Query *parse); + extern void mark_partial_aggref(Aggref *agg, AggSplit aggsplit); extern Path *get_cheapest_fractional_path(RelOptInfo *rel, diff --git a/src/test/regress/expected/select_parallel.out b/src/test/regress/expected/select_parallel.out index 562eb2c..14420f4 100644 --- a/src/test/regress/expected/select_parallel.out +++ b/src/test/regress/expected/select_parallel.out @@ -573,6 +573,25 @@ explain (costs off) Index Cond: (unique1 = 1) (5 rows) +-- LIMIT/OFFSET within sub-selects can't be pushed to workers. +explain (costs off) +select * from tenk1 where two in + (select two from tenk1 where stringu1 like '%AAAA' limit 3); + QUERY PLAN +--------------------------------------------------------------- + Hash Semi Join + Hash Cond: (tenk1.two = tenk1_1.two) + -> Gather + Workers Planned: 4 + -> Parallel Seq Scan on tenk1 + -> Hash + -> Limit + -> Gather + Workers Planned: 4 + -> Parallel Seq Scan on tenk1 tenk1_1 + Filter: (stringu1 ~~ '%AAAA'::text) +(11 rows) + -- to increase the parallel query test coverage EXPLAIN (analyze, timing off, summary off, costs off) SELECT * FROM tenk1; QUERY PLAN diff --git a/src/test/regress/sql/select_parallel.sql b/src/test/regress/sql/select_parallel.sql index 1d29e96..c0bfc2d 100644 --- a/src/test/regress/sql/select_parallel.sql +++ b/src/test/regress/sql/select_parallel.sql @@ -204,6 +204,11 @@ set force_parallel_mode=1; explain (costs off) select stringu1::int2 from tenk1 where unique1 = 1; +-- LIMIT/OFFSET within sub-selects can't be pushed to workers. +explain (costs off) +select * from tenk1 where two in + (select two from tenk1 where stringu1 like '%AAAA' limit 3); + -- to increase the parallel query test coverage EXPLAIN (analyze, timing off, summary off, costs off) SELECT * FROM tenk1;
prohibit_parallel_limit_subselect_v2_rel96.patch (application/octet-stream, 3.9K) download diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index b4a1e8b..df0ee2f 100644 --- a/src/backend/optimizer/path/allpaths.c +++ b/src/backend/optimizer/path/allpaths.c @@ -585,7 +585,17 @@ set_rel_consider_parallel(PlannerInfo *root, RelOptInfo *rel, * the SubqueryScanPath as not parallel-safe. (Note that * set_subquery_pathlist() might push some of these quals down * into the subquery itself, but that doesn't change anything.) + * + * We can't push sub-select containing LIMIT/OFFSET to workers as + * that can change the results depending on what is beneath LIMIT + * node. So, consider that case as parallel-unsafe. */ + { + Query *subquery = castNode(Query, rte->subquery); + + if (limit_needed(subquery)) + return; + } break; case RTE_JOIN: diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 73eb307..f348493 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -98,7 +98,6 @@ static void preprocess_rowmarks(PlannerInfo *root); static double preprocess_limit(PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est); -static bool limit_needed(Query *parse); static void remove_useless_groupby_columns(PlannerInfo *root); static List *preprocess_groupclause(PlannerInfo *root, List *force); static List *extract_rollup_sets(List *groupingSets); @@ -2492,7 +2491,7 @@ preprocess_limit(PlannerInfo *root, double tuple_fraction, * a key distinction: here we need hard constants in OFFSET/LIMIT, whereas * in preprocess_limit it's good enough to consider estimated values. */ -static bool +bool limit_needed(Query *parse) { Node *node; diff --git a/src/include/optimizer/planner.h b/src/include/optimizer/planner.h index d9790d7..b4546b1 100644 --- a/src/include/optimizer/planner.h +++ b/src/include/optimizer/planner.h @@ -46,6 +46,8 @@ extern bool is_dummy_plan(Plan *plan); extern RowMarkType select_rowmark_type(RangeTblEntry *rte, LockClauseStrength strength); +extern bool limit_needed(Query *parse); + extern void mark_partial_aggref(Aggref *agg, AggSplit aggsplit); extern Path *get_cheapest_fractional_path(RelOptInfo *rel, diff --git a/src/test/regress/expected/select_parallel.out b/src/test/regress/expected/select_parallel.out index 43801e0..ba1949f 100644 --- a/src/test/regress/expected/select_parallel.out +++ b/src/test/regress/expected/select_parallel.out @@ -182,6 +182,25 @@ select count(*) from tenk1; (1 row) reset role; +-- LIMIT/OFFSET within sub-selects can't be pushed to workers. +explain (costs off) +select * from tenk1 where two in + (select two from tenk1 where stringu1 like '%AAAA' limit 3); + QUERY PLAN +--------------------------------------------------------------- + Hash Semi Join + Hash Cond: (tenk1.two = tenk1_1.two) + -> Gather + Workers Planned: 4 + -> Parallel Seq Scan on tenk1 + -> Hash + -> Limit + -> Gather + Workers Planned: 4 + -> Parallel Seq Scan on tenk1 tenk1_1 + Filter: (stringu1 ~~ '%AAAA'::text) +(11 rows) + explain (costs off) select stringu1::int2 from tenk1 where unique1 = 1; QUERY PLAN diff --git a/src/test/regress/sql/select_parallel.sql b/src/test/regress/sql/select_parallel.sql index 7defc34..dafc4ad 100644 --- a/src/test/regress/sql/select_parallel.sql +++ b/src/test/regress/sql/select_parallel.sql @@ -83,6 +83,11 @@ drop role regress_parallel_worker; select count(*) from tenk1; reset role; +-- LIMIT/OFFSET within sub-selects can't be pushed to workers. +explain (costs off) +select * from tenk1 where two in + (select two from tenk1 where stringu1 like '%AAAA' limit 3); + explain (costs off) select stringu1::int2 from tenk1 where unique1 = 1;
fix_parallel_hash_path_v1.patch (application/octet-stream, 1.1K) download diff --git a/src/backend/optimizer/path/joinpath.c b/src/backend/optimizer/path/joinpath.c index 2897245883..99ec5834bf 100644 --- a/src/backend/optimizer/path/joinpath.c +++ b/src/backend/optimizer/path/joinpath.c @@ -1510,9 +1510,9 @@ hash_inner_and_outer(PlannerInfo *root, /* * Normally, given that the joinrel is parallel-safe, the cheapest * total inner path will also be parallel-safe, but if not, we'll - * have to search cheapest_parameterized_paths for the cheapest - * safe, unparameterized inner path. If doing JOIN_UNIQUE_INNER, - * we can't use any alternative inner path. + * have to search for the cheapest safe, unparameterized inner + * path. If doing JOIN_UNIQUE_INNER, we can't use any alternative + * inner path. */ if (cheapest_total_inner->parallel_safe) cheapest_safe_inner = cheapest_total_inner; @@ -1520,7 +1520,7 @@ hash_inner_and_outer(PlannerInfo *root, { ListCell *lc; - foreach(lc, innerrel->cheapest_parameterized_paths) + foreach(lc, innerrel->pathlist) { Path *innerpath = (Path *) lfirst(lc);
treat_window_func_calc_parallel_restricted_v2.patch (application/octet-stream, 11.7K) download diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index a04ad6e..1c7136f 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -1197,6 +1197,19 @@ max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context) } /* + * Treat window functions as parallel-restricted as the row ordering + * induced by them is non-deterministic. We can relax this condition for + * cases where the row ordering can be deterministic like when there is + * an ORDER BY on the primary key, but those cases don't seem to be + * interesting enough to have additional checks. + */ + if (IsA(node, WindowFunc)) + { + if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context)) + return true; + } + + /* * As a notational convenience for callers, look through RestrictInfo. */ else if (IsA(node, RestrictInfo)) diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index a146510..a641b8c 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -9413,51 +9413,62 @@ # SQL-spec window functions { oid => '3100', descr => 'row number within partition', proname => 'row_number', prokind => 'w', proisstrict => 'f', - prorettype => 'int8', proargtypes => '', prosrc => 'window_row_number' }, + proparallel => 'r', prorettype => 'int8', proargtypes => '', + prosrc => 'window_row_number' }, { oid => '3101', descr => 'integer rank with gaps', - proname => 'rank', prokind => 'w', proisstrict => 'f', prorettype => 'int8', - proargtypes => '', prosrc => 'window_rank' }, + proname => 'rank', prokind => 'w', proisstrict => 'f', proparallel => 'r', + prorettype => 'int8', proargtypes => '', prosrc => 'window_rank' }, { oid => '3102', descr => 'integer rank without gaps', proname => 'dense_rank', prokind => 'w', proisstrict => 'f', - prorettype => 'int8', proargtypes => '', prosrc => 'window_dense_rank' }, + proparallel => 'r', prorettype => 'int8', proargtypes => '', + prosrc => 'window_dense_rank' }, { oid => '3103', descr => 'fractional rank within partition', proname => 'percent_rank', prokind => 'w', proisstrict => 'f', - prorettype => 'float8', proargtypes => '', prosrc => 'window_percent_rank' }, + proparallel => 'r', prorettype => 'float8', proargtypes => '', + prosrc => 'window_percent_rank' }, { oid => '3104', descr => 'fractional row number within partition', proname => 'cume_dist', prokind => 'w', proisstrict => 'f', - prorettype => 'float8', proargtypes => '', prosrc => 'window_cume_dist' }, + proparallel => 'r', prorettype => 'float8', proargtypes => '', + prosrc => 'window_cume_dist' }, { oid => '3105', descr => 'split rows into N groups', - proname => 'ntile', prokind => 'w', prorettype => 'int4', - proargtypes => 'int4', prosrc => 'window_ntile' }, + proname => 'ntile', prokind => 'w', proparallel => 'r', + prorettype => 'int4', proargtypes => 'int4', prosrc => 'window_ntile' }, { oid => '3106', descr => 'fetch the preceding row value', - proname => 'lag', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement', prosrc => 'window_lag' }, + proname => 'lag', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement', + prosrc => 'window_lag' }, { oid => '3107', descr => 'fetch the Nth preceding row value', - proname => 'lag', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement int4', prosrc => 'window_lag_with_offset' }, + proname => 'lag', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement int4', + prosrc => 'window_lag_with_offset' }, { oid => '3108', descr => 'fetch the Nth preceding row value with default', - proname => 'lag', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement int4 anyelement', + proname => 'lag', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement int4 anyelement', prosrc => 'window_lag_with_offset_and_default' }, { oid => '3109', descr => 'fetch the following row value', - proname => 'lead', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement', prosrc => 'window_lead' }, + proname => 'lead', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement', + prosrc => 'window_lead' }, { oid => '3110', descr => 'fetch the Nth following row value', - proname => 'lead', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement int4', prosrc => 'window_lead_with_offset' }, + proname => 'lead', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement int4', + prosrc => 'window_lead_with_offset' }, { oid => '3111', descr => 'fetch the Nth following row value with default', - proname => 'lead', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement int4 anyelement', + proname => 'lead', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement int4 anyelement', prosrc => 'window_lead_with_offset_and_default' }, { oid => '3112', descr => 'fetch the first row value', - proname => 'first_value', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement', prosrc => 'window_first_value' }, + proname => 'first_value', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement', + prosrc => 'window_first_value' }, { oid => '3113', descr => 'fetch the last row value', - proname => 'last_value', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement', prosrc => 'window_last_value' }, + proname => 'last_value', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement', + prosrc => 'window_last_value' }, { oid => '3114', descr => 'fetch the Nth row value', - proname => 'nth_value', prokind => 'w', prorettype => 'anyelement', - proargtypes => 'anyelement int4', prosrc => 'window_nth_value' }, + proname => 'nth_value', prokind => 'w', proparallel => 'r', + prorettype => 'anyelement', proargtypes => 'anyelement int4', + prosrc => 'window_nth_value' }, # functions for range types { oid => '3832', descr => 'I/O', @@ -9957,41 +9968,41 @@ # hypothetical-set aggregates (and their support functions) { oid => '3986', descr => 'rank of hypothetical row', proname => 'rank', provariadic => 'any', prokind => 'a', proisstrict => 'f', - prorettype => 'int8', proargtypes => 'any', proallargtypes => '{any}', - proargmodes => '{v}', prosrc => 'aggregate_dummy' }, + proparallel => 'r', prorettype => 'int8', proargtypes => 'any', + proallargtypes => '{any}', proargmodes => '{v}', prosrc => 'aggregate_dummy' }, { oid => '3987', descr => 'aggregate final function', proname => 'rank_final', provariadic => 'any', proisstrict => 'f', - prorettype => 'int8', proargtypes => 'internal any', + proparallel => 'r', prorettype => 'int8', proargtypes => 'internal any', proallargtypes => '{internal,any}', proargmodes => '{i,v}', prosrc => 'hypothetical_rank_final' }, { oid => '3988', descr => 'fractional rank of hypothetical row', proname => 'percent_rank', provariadic => 'any', prokind => 'a', - proisstrict => 'f', prorettype => 'float8', proargtypes => 'any', - proallargtypes => '{any}', proargmodes => '{v}', + proisstrict => 'f', proparallel => 'r', prorettype => 'float8', + proargtypes => 'any', proallargtypes => '{any}', proargmodes => '{v}', prosrc => 'aggregate_dummy' }, { oid => '3989', descr => 'aggregate final function', proname => 'percent_rank_final', provariadic => 'any', proisstrict => 'f', - prorettype => 'float8', proargtypes => 'internal any', + proparallel => 'r', prorettype => 'float8', proargtypes => 'internal any', proallargtypes => '{internal,any}', proargmodes => '{i,v}', prosrc => 'hypothetical_percent_rank_final' }, { oid => '3990', descr => 'cumulative distribution of hypothetical row', proname => 'cume_dist', provariadic => 'any', prokind => 'a', - proisstrict => 'f', prorettype => 'float8', proargtypes => 'any', - proallargtypes => '{any}', proargmodes => '{v}', + proisstrict => 'f', proparallel => 'r', prorettype => 'float8', + proargtypes => 'any', proallargtypes => '{any}', proargmodes => '{v}', prosrc => 'aggregate_dummy' }, { oid => '3991', descr => 'aggregate final function', proname => 'cume_dist_final', provariadic => 'any', proisstrict => 'f', - prorettype => 'float8', proargtypes => 'internal any', + proparallel => 'r', prorettype => 'float8', proargtypes => 'internal any', proallargtypes => '{internal,any}', proargmodes => '{i,v}', prosrc => 'hypothetical_cume_dist_final' }, { oid => '3992', descr => 'rank of hypothetical row without gaps', proname => 'dense_rank', provariadic => 'any', prokind => 'a', - proisstrict => 'f', prorettype => 'int8', proargtypes => 'any', - proallargtypes => '{any}', proargmodes => '{v}', + proisstrict => 'f', proparallel => 'r', prorettype => 'int8', + proargtypes => 'any', proallargtypes => '{any}', proargmodes => '{v}', prosrc => 'aggregate_dummy' }, { oid => '3993', descr => 'aggregate final function', proname => 'dense_rank_final', provariadic => 'any', proisstrict => 'f', - prorettype => 'int8', proargtypes => 'internal any', + proparallel => 'r', prorettype => 'int8', proargtypes => 'internal any', proallargtypes => '{internal,any}', proargmodes => '{i,v}', prosrc => 'hypothetical_dense_rank_final' }, diff --git a/src/test/regress/expected/select_parallel.out b/src/test/regress/expected/select_parallel.out index ad03807..ce4fab9 100644 --- a/src/test/regress/expected/select_parallel.out +++ b/src/test/regress/expected/select_parallel.out @@ -977,6 +977,32 @@ select * from tenk1 where two in Filter: (stringu1 ~~ '%AAAA'::text) (11 rows) +-- Window function calculation can't be pushed to workers. +explain (costs off, verbose) + select count(*) from tenk1 where (unique1, two) in + (select unique1, row_number() over() from tenk1); + QUERY PLAN +---------------------------------------------------------------------------------------------------- + Aggregate + Output: count(*) + -> Hash Semi Join + Hash Cond: ((tenk1.unique1 = tenk1_1.unique1) AND (tenk1.two = (row_number() OVER (?)))) + -> Gather + Output: tenk1.unique1, tenk1.two + Workers Planned: 4 + -> Parallel Seq Scan on public.tenk1 + Output: tenk1.unique1, tenk1.two + -> Hash + Output: tenk1_1.unique1, (row_number() OVER (?)) + -> WindowAgg + Output: tenk1_1.unique1, row_number() OVER (?) + -> Gather + Output: tenk1_1.unique1 + Workers Planned: 4 + -> Parallel Index Only Scan using tenk1_unique1 on public.tenk1 tenk1_1 + Output: tenk1_1.unique1 +(18 rows) + -- to increase the parallel query test coverage SAVEPOINT settings; SET LOCAL force_parallel_mode = 1; diff --git a/src/test/regress/sql/select_parallel.sql b/src/test/regress/sql/select_parallel.sql index aea2461..f904154 100644 --- a/src/test/regress/sql/select_parallel.sql +++ b/src/test/regress/sql/select_parallel.sql @@ -367,6 +367,11 @@ explain (costs off) select * from tenk1 where two in (select two from tenk1 where stringu1 like '%AAAA' limit 3); +-- Window function calculation can't be pushed to workers. +explain (costs off, verbose) + select count(*) from tenk1 where (unique1, two) in + (select unique1, row_number() over() from tenk1); + -- to increase the parallel query test coverage SAVEPOINT settings; SET LOCAL force_parallel_mode = 1;
^ permalink raw reply [nested|flat] 38+ messages in thread

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-09-02 04:51  Amit Kapila <amit.kapila16@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 0 replies; 38+ messages in thread

From: Amit Kapila @ 2018-09-02 04:51 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Stephen Frost <sfrost@snowman.net>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Tue, Aug 21, 2018 at 8:44 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Mon, Aug 20, 2018 at 6:59 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> > Sounds to me like you're using the wrong approach.  I would just consider
> > any Agg or WindowFunc node as parallel-restricted regardless of the
> > function it references.
> >
>
> I have below change in the patch which I think is on the lines what
> you are describing, do you have something different in mind?
>
> @@ -1197,6 +1197,19 @@ max_parallel_hazard_walker(Node *node,
> max_parallel_hazard_context *context)
>   }
>
>   /*
> + * Treat window functions as parallel-restricted as the row ordering
> + * induced by them is non-deterministic.  We can relax this condition for
> + * cases where the row ordering can be deterministic like when there is
> + * an ORDER BY on the primary key, but those cases don't seem to be
> + * interesting enough to have additional checks.
> + */
> + if (IsA(node, WindowFunc))
> + {
> + if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context))
> + return true;
> + }
>
> In addition to the above, I have marked all built-in window functions
> as parallel-restricted.  I think even if we don't do that something
> like above check should be sufficient, but OTOH, I don't see any
> reason to keep the marking of such functions as parallel-safe.  Is
> there a reason, why we shouldn't mark them as parallel-restricted?
>

Tom, do you have input on this?  Is it okay to backpatch this fix?

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-09-02 18:55  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  1 sibling, 1 reply; 38+ messages in thread

From: Tom Lane @ 2018-09-02 18:55 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Stephen Frost <sfrost@snowman.net>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

Amit Kapila <amit.kapila16@gmail.com> writes:
> Tom, do you have input on this?  Is it okay to backpatch this fix?

Well,

>> + * Treat window functions as parallel-restricted as the row ordering
>> + * induced by them is non-deterministic.  We can relax this condition for
>> + * cases where the row ordering can be deterministic like when there is
>> + * an ORDER BY on the primary key, but those cases don't seem to be
>> + * interesting enough to have additional checks.

This comment seems fairly confused.  I'd say something like

 * Treat window functions as parallel-restricted because we aren't sure
 * whether the input row ordering is fully deterministic, and the output
 * of window functions might vary across workers if not.  (In some cases,
 * like where the window frame orders by a primary key, we could relax
 * this restriction.  But it doesn't currently seem worth expending extra
 * effort to do so.)

>> In addition to the above, I have marked all built-in window functions
>> as parallel-restricted.  I think even if we don't do that something
>> like above check should be sufficient, but OTOH, I don't see any
>> reason to keep the marking of such functions as parallel-safe.  Is
>> there a reason, why we shouldn't mark them as parallel-restricted?

I am *strongly* against this.  It's unnecessary catalog churn that we
might need to undo someday, and it confuses a property of the window
function infrastructure with a property of individual window functions.
As a counterexample, if a window function were parallel-unsafe for
some reason, we'd surely need to honor that.  More realistically,
someone might add a window function that actually needs to be
parallel-restricted for reasons of its own, but then there would be
no obvious distinction between such a function and one that you'd
hacked up to be marked parallel-restricted even though it's safe in
itself.  If we then do make the sort of optimization suggested in the
comment, it's likely that someone would just s/r/s/g for all the window
functions and thereby break such a function.  Better to retain the
correct per-function markings.

			regards, tom lane




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-09-03 04:29  Amit Kapila <amit.kapila16@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 38+ messages in thread

From: Amit Kapila @ 2018-09-03 04:29 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Stephen Frost <sfrost@snowman.net>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Mon, Sep 3, 2018 at 12:25 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Amit Kapila <amit.kapila16@gmail.com> writes:
>
> >> + * Treat window functions as parallel-restricted as the row ordering
> >> + * induced by them is non-deterministic.  We can relax this condition for
> >> + * cases where the row ordering can be deterministic like when there is
> >> + * an ORDER BY on the primary key, but those cases don't seem to be
> >> + * interesting enough to have additional checks.
>
> This comment seems fairly confused.  I'd say something like
>
>  * Treat window functions as parallel-restricted because we aren't sure
>  * whether the input row ordering is fully deterministic, and the output
>  * of window functions might vary across workers if not.  (In some cases,
>  * like where the window frame orders by a primary key, we could relax
>  * this restriction.  But it doesn't currently seem worth expending extra
>  * effort to do so.)
>

Changed.

> >> In addition to the above, I have marked all built-in window functions
> >> as parallel-restricted.  I think even if we don't do that something
> >> like above check should be sufficient, but OTOH, I don't see any
> >> reason to keep the marking of such functions as parallel-safe.  Is
> >> there a reason, why we shouldn't mark them as parallel-restricted?
>
> I am *strongly* against this.  It's unnecessary catalog churn that we
> might need to undo someday, and it confuses a property of the window
> function infrastructure with a property of individual window functions.
> As a counterexample, if a window function were parallel-unsafe for
> some reason, we'd surely need to honor that.  More realistically,
> someone might add a window function that actually needs to be
> parallel-restricted for reasons of its own, but then there would be
> no obvious distinction between such a function and one that you'd
> hacked up to be marked parallel-restricted even though it's safe in
> itself.  If we then do make the sort of optimization suggested in the
> comment, it's likely that someone would just s/r/s/g for all the window
> functions and thereby break such a function.
>

Sounds sensible, I have removed that part from the patch.

You haven't mentioned anything about backpatching, but I don't see any
problem with backpatching this fix.  So, I have prepared patches for
back branches wherever required.  For 10, it is mostly a cosmetic
change (the patch didn't apply cleanly), but for 9.6 the prohibition
check is slightly different.

I will commit the attached patches in a day or so unless somebody sees
any problem.


--
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com

Attachments: download all (3 files, .tar.gz)

treat_window_func_calc_parallel_restricted_v3.pg10.patch (application/octet-stream, 3.3K) download diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index fa53b7a..6aa29c5 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -1175,6 +1175,20 @@ max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context) } /* + * Treat window functions as parallel-restricted because we aren't sure + * whether the input row ordering is fully deterministic, and the output + * of window functions might vary across workers if not. (In some cases, + * like where the window frame orders by a primary key, we could relax + * this restriction. But it doesn't currently seem worth expending extra + * effort to do so.) + */ + if (IsA(node, WindowFunc)) + { + if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context)) + return true; + } + + /* * As a notational convenience for callers, look through RestrictInfo. */ else if (IsA(node, RestrictInfo)) diff --git a/src/test/regress/expected/select_parallel.out b/src/test/regress/expected/select_parallel.out index 562eb2c..66afec4 100644 --- a/src/test/regress/expected/select_parallel.out +++ b/src/test/regress/expected/select_parallel.out @@ -573,6 +573,32 @@ explain (costs off) Index Cond: (unique1 = 1) (5 rows) +-- Window function calculation can't be pushed to workers. +explain (costs off, verbose) + select count(*) from tenk1 where (unique1, two) in + (select unique1, row_number() over() from tenk1); + QUERY PLAN +---------------------------------------------------------------------------------------------------- + Aggregate + Output: count(*) + -> Hash Semi Join + Hash Cond: ((tenk1.unique1 = tenk1_1.unique1) AND (tenk1.two = (row_number() OVER (?)))) + -> Gather + Output: tenk1.unique1, tenk1.two + Workers Planned: 4 + -> Parallel Seq Scan on public.tenk1 + Output: tenk1.unique1, tenk1.two + -> Hash + Output: tenk1_1.unique1, (row_number() OVER (?)) + -> WindowAgg + Output: tenk1_1.unique1, row_number() OVER (?) + -> Gather + Output: tenk1_1.unique1 + Workers Planned: 4 + -> Parallel Index Only Scan using tenk1_unique1 on public.tenk1 tenk1_1 + Output: tenk1_1.unique1 +(18 rows) + -- to increase the parallel query test coverage EXPLAIN (analyze, timing off, summary off, costs off) SELECT * FROM tenk1; QUERY PLAN diff --git a/src/test/regress/sql/select_parallel.sql b/src/test/regress/sql/select_parallel.sql index 1d29e96..f57baf3 100644 --- a/src/test/regress/sql/select_parallel.sql +++ b/src/test/regress/sql/select_parallel.sql @@ -204,6 +204,12 @@ set force_parallel_mode=1; explain (costs off) select stringu1::int2 from tenk1 where unique1 = 1; +-- Window function calculation can't be pushed to workers. +explain (costs off, verbose) + select count(*) from tenk1 where (unique1, two) in + (select unique1, row_number() over() from tenk1); + + -- to increase the parallel query test coverage EXPLAIN (analyze, timing off, summary off, costs off) SELECT * FROM tenk1;
treat_window_func_calc_parallel_restricted_v3.patch (application/octet-stream, 3.2K) download diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index a04ad6e..48fa34f 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -1197,6 +1197,20 @@ max_parallel_hazard_walker(Node *node, max_parallel_hazard_context *context) } /* + * Treat window functions as parallel-restricted because we aren't sure + * whether the input row ordering is fully deterministic, and the output + * of window functions might vary across workers if not. (In some cases, + * like where the window frame orders by a primary key, we could relax + * this restriction. But it doesn't currently seem worth expending extra + * effort to do so.) + */ + if (IsA(node, WindowFunc)) + { + if (max_parallel_hazard_test(PROPARALLEL_RESTRICTED, context)) + return true; + } + + /* * As a notational convenience for callers, look through RestrictInfo. */ else if (IsA(node, RestrictInfo)) diff --git a/src/test/regress/expected/select_parallel.out b/src/test/regress/expected/select_parallel.out index f1b8cd4..d9c60c0 100644 --- a/src/test/regress/expected/select_parallel.out +++ b/src/test/regress/expected/select_parallel.out @@ -958,6 +958,32 @@ select count(*) from tenk1; reset force_parallel_mode; reset role; +-- Window function calculation can't be pushed to workers. +explain (costs off, verbose) + select count(*) from tenk1 where (unique1, two) in + (select unique1, row_number() over() from tenk1); + QUERY PLAN +---------------------------------------------------------------------------------------------------- + Aggregate + Output: count(*) + -> Hash Semi Join + Hash Cond: ((tenk1.unique1 = tenk1_1.unique1) AND (tenk1.two = (row_number() OVER (?)))) + -> Gather + Output: tenk1.unique1, tenk1.two + Workers Planned: 4 + -> Parallel Seq Scan on public.tenk1 + Output: tenk1.unique1, tenk1.two + -> Hash + Output: tenk1_1.unique1, (row_number() OVER (?)) + -> WindowAgg + Output: tenk1_1.unique1, row_number() OVER (?) + -> Gather + Output: tenk1_1.unique1 + Workers Planned: 4 + -> Parallel Index Only Scan using tenk1_unique1 on public.tenk1 tenk1_1 + Output: tenk1_1.unique1 +(18 rows) + -- to increase the parallel query test coverage SAVEPOINT settings; SET LOCAL force_parallel_mode = 1; diff --git a/src/test/regress/sql/select_parallel.sql b/src/test/regress/sql/select_parallel.sql index 7771e05..f8a0c08 100644 --- a/src/test/regress/sql/select_parallel.sql +++ b/src/test/regress/sql/select_parallel.sql @@ -362,6 +362,12 @@ select count(*) from tenk1; reset force_parallel_mode; reset role; +-- Window function calculation can't be pushed to workers. +explain (costs off, verbose) + select count(*) from tenk1 where (unique1, two) in + (select unique1, row_number() over() from tenk1); + + -- to increase the parallel query test coverage SAVEPOINT settings; SET LOCAL force_parallel_mode = 1;
treat_window_func_calc_parallel_restricted_v3.pg96.patch (application/octet-stream, 3.0K) download diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c index 8cdee70..1734561 100644 --- a/src/backend/optimizer/util/clauses.c +++ b/src/backend/optimizer/util/clauses.c @@ -1162,6 +1162,20 @@ has_parallel_hazard_walker(Node *node, has_parallel_hazard_arg *context) } /* + * Treat window functions as parallel-restricted because we aren't sure + * whether the input row ordering is fully deterministic, and the output + * of window functions might vary across workers if not. (In some cases, + * like where the window frame orders by a primary key, we could relax + * this restriction. But it doesn't currently seem worth expending extra + * effort to do so.) + */ + if (IsA(node, WindowFunc)) + { + if (!context->allow_restricted) + return true; + } + + /* * As a notational convenience for callers, look through RestrictInfo. */ else if (IsA(node, RestrictInfo)) diff --git a/src/test/regress/expected/select_parallel.out b/src/test/regress/expected/select_parallel.out index 43801e0..bce2439 100644 --- a/src/test/regress/expected/select_parallel.out +++ b/src/test/regress/expected/select_parallel.out @@ -182,6 +182,29 @@ select count(*) from tenk1; (1 row) reset role; +-- Window function calculation can't be pushed to workers. +explain (costs off, verbose) + select count(*) from tenk1 where (unique1, two) in + (select unique1, row_number() over() from tenk1); + QUERY PLAN +-------------------------------------------------------------------------------------------------- + Aggregate + Output: count(*) + -> Hash Semi Join + Hash Cond: ((tenk1.unique1 = tenk1_1.unique1) AND (tenk1.two = (row_number() OVER (?)))) + -> Gather + Output: tenk1.unique1, tenk1.two + Workers Planned: 4 + -> Parallel Seq Scan on public.tenk1 + Output: tenk1.unique1, tenk1.two + -> Hash + Output: tenk1_1.unique1, (row_number() OVER (?)) + -> WindowAgg + Output: tenk1_1.unique1, row_number() OVER (?) + -> Index Only Scan using tenk1_unique1 on public.tenk1 tenk1_1 + Output: tenk1_1.unique1 +(15 rows) + explain (costs off) select stringu1::int2 from tenk1 where unique1 = 1; QUERY PLAN diff --git a/src/test/regress/sql/select_parallel.sql b/src/test/regress/sql/select_parallel.sql index 7defc34..272efd5 100644 --- a/src/test/regress/sql/select_parallel.sql +++ b/src/test/regress/sql/select_parallel.sql @@ -83,6 +83,11 @@ drop role regress_parallel_worker; select count(*) from tenk1; reset role; +-- Window function calculation can't be pushed to workers. +explain (costs off, verbose) + select count(*) from tenk1 where (unique1, two) in + (select unique1, row_number() over() from tenk1); + explain (costs off) select stringu1::int2 from tenk1 where unique1 = 1;
^ permalink raw reply [nested|flat] 38+ messages in thread

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-09-03 13:49  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 38+ messages in thread

From: Tom Lane @ 2018-09-03 13:49 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Stephen Frost <sfrost@snowman.net>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

Amit Kapila <amit.kapila16@gmail.com> writes:
> You haven't mentioned anything about backpatching, but I don't see any
> problem with backpatching this fix.

Yeah, we definitely need to back-patch, and that's another reason not
to touch the catalog contents.

> I will commit the attached patches in a day or so unless somebody sees
> any problem.

Looking more closely at the patch:

* The general design in max_parallel_hazard_walker appears to be that
after the initial check_functions_in_node test, the rest of it should be
an if ... else if ... else if ... else if ... chain of mutually-exclusive
IsA tests.  Whoever stuck in the NextValueExpr test (possibly me?) did so
with a tin ear, and you've duplicated that mistake here.  Please make it
"else if", and fix the NextValueExpr test to be "else if" while at it.
(Or else get rid of all the "else"s, but that would be a shade less
efficient unless the compiler is very very smart.)

* The plan tree for the added test case is hard to read because it's
unclear which tenk1 scan is which.  I'd suggest adding aliases to
clarify that, eg

+explain (costs off, verbose)
+  select count(*) from tenk1 a where (unique1, two) in
+    (select unique1, row_number() over() from tenk1 b);

HEAD patch is OK otherwise.  I didn't look at the back-branch patches.

			regards, tom lane




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-09-04 06:12  Amit Kapila <amit.kapila16@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 0 replies; 38+ messages in thread

From: Amit Kapila @ 2018-09-04 06:12 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Stephen Frost <sfrost@snowman.net>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Mon, Sep 3, 2018 at 7:19 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
>
> Amit Kapila <amit.kapila16@gmail.com> writes:
> > You haven't mentioned anything about backpatching, but I don't see any
> > problem with backpatching this fix.
>
> Yeah, we definitely need to back-patch, and that's another reason not
> to touch the catalog contents.
>
> > I will commit the attached patches in a day or so unless somebody sees
> > any problem.
>
> Looking more closely at the patch:
>
> * The general design in max_parallel_hazard_walker appears to be that
> after the initial check_functions_in_node test, the rest of it should be
> an if ... else if ... else if ... else if ... chain of mutually-exclusive
> IsA tests.  Whoever stuck in the NextValueExpr test (possibly me?) did so
> with a tin ear, and you've duplicated that mistake here.  Please make it
> "else if", and fix the NextValueExpr test to be "else if" while at it.
> (Or else get rid of all the "else"s, but that would be a shade less
> efficient unless the compiler is very very smart.)
>
> * The plan tree for the added test case is hard to read because it's
> unclear which tenk1 scan is which.  I'd suggest adding aliases to
> clarify that, eg
>
> +explain (costs off, verbose)
> +  select count(*) from tenk1 a where (unique1, two) in
> +    (select unique1, row_number() over() from tenk1 b);
>
> HEAD patch is OK otherwise.  I didn't look at the back-branch patches.
>

Thanks for the review.  After making the changes suggested by you, I
have pushed and back-patched it till 9.6.

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-09-05 04:33  Amit Kapila <amit.kapila16@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 38+ messages in thread

From: Amit Kapila @ 2018-09-05 04:33 UTC (permalink / raw)
  To: Stephen Frost <sfrost@snowman.net>; Robert Haas <robertmhaas@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Sun, Sep 2, 2018 at 10:18 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
> > > Yeah, let me summarize the problems which require patches:
> > > (a) Consider the presence of a LIMIT/OFFSET in a sub-select as making
> > > it parallel-unsafe.
> > >
> >
> > As mentioned up-thread, I have considered adding a check in
> > max_parallel_hazard_walker, but it turns out that it will make the
> > whole query parallel-unsafe even if one of the sub-selects has
> > Limit/Offset.  I think the better idea is to detect that during
> > set_rel_consider_parallel.  Attached patch
> > prohibit_parallel_limit_subselect_v2 implements the fix for same.
> >
>
> I was trying this patch on back-branches and found that it doesn't
> apply cleanly beyond PG11, so created separate patches for 10 and 9.6.
>   Further, I found that the test for this patch was not failing for
> 9.6 (without the patch) even though the code doesn't deal with this
> problem.  On further investigation, I found that it is because the
> commit
> 655393a022bd653e2b48dbf20b69236981e35195 has not been backpatched to
> 9.6.  I don't see any reason why we shouldn't backpatch this commit.
> So, I have attached a patch (fix_parallel_hash_path_v1.patch) which we
> can backpatch in 9.6.
>
> Robert, your input will be highly appreciated here especially for the
> back patch (to 9.6) I am proposing?
>

I have rebased the HEAD patch and done some cosmetic changes like
improved the test by giving aliases to table names and modified the
comment a bit, otherwise, the core logic remains the same.  As the
back-branch patches are just the matter of rebasing them, I will do
that before commit.

I am still waiting for input, but if there is none, my plan is to
commit this in a day or two and back-patch it as well.  Along with
this, I would also like to back-patch commit
655393a022bd653e2b48dbf20b69236981e35195 for the reasons mentioned
above.

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com

Attachments:

prohibit_parallel_limit_subselect_v3.patch (application/octet-stream, 4.2K) download diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index 5db1688..5f74d3b 100644 --- a/src/backend/optimizer/path/allpaths.c +++ b/src/backend/optimizer/path/allpaths.c @@ -620,7 +620,20 @@ set_rel_consider_parallel(PlannerInfo *root, RelOptInfo *rel, * the SubqueryScanPath as not parallel-safe. (Note that * set_subquery_pathlist() might push some of these quals down * into the subquery itself, but that doesn't change anything.) + * + * We can't push sub-select containing LIMIT/OFFSET to workers as + * there is no guarantee that the row order will be fully + * deterministic, and applying LIMIT/OFFSET will lead to + * inconsistent results at the top-level. (In some cases, where + * the result is ordered, we could relax this restriction. But it + * doesn't currently seem worth expending extra effort to do so.) */ + { + Query *subquery = castNode(Query, rte->subquery); + + if (limit_needed(subquery)) + return; + } break; case RTE_JOIN: diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index 96bf060..e589471 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -123,7 +123,6 @@ static void preprocess_rowmarks(PlannerInfo *root); static double preprocess_limit(PlannerInfo *root, double tuple_fraction, int64 *offset_est, int64 *count_est); -static bool limit_needed(Query *parse); static void remove_useless_groupby_columns(PlannerInfo *root); static List *preprocess_groupclause(PlannerInfo *root, List *force); static List *extract_rollup_sets(List *groupingSets); @@ -2870,7 +2869,7 @@ preprocess_limit(PlannerInfo *root, double tuple_fraction, * a key distinction: here we need hard constants in OFFSET/LIMIT, whereas * in preprocess_limit it's good enough to consider estimated values. */ -static bool +bool limit_needed(Query *parse) { Node *node; diff --git a/src/include/optimizer/planner.h b/src/include/optimizer/planner.h index c090396..3e733b3 100644 --- a/src/include/optimizer/planner.h +++ b/src/include/optimizer/planner.h @@ -47,6 +47,8 @@ extern bool is_dummy_plan(Plan *plan); extern RowMarkType select_rowmark_type(RangeTblEntry *rte, LockClauseStrength strength); +extern bool limit_needed(Query *parse); + extern void mark_partial_aggref(Aggref *agg, AggSplit aggsplit); extern Path *get_cheapest_fractional_path(RelOptInfo *rel, diff --git a/src/test/regress/expected/select_parallel.out b/src/test/regress/expected/select_parallel.out index 13cdd3d..26409d3 100644 --- a/src/test/regress/expected/select_parallel.out +++ b/src/test/regress/expected/select_parallel.out @@ -984,6 +984,25 @@ explain (costs off, verbose) Output: b.unique1 (18 rows) +-- LIMIT/OFFSET within sub-selects can't be pushed to workers. +explain (costs off) + select * from tenk1 a where two in + (select two from tenk1 b where stringu1 like '%AAAA' limit 3); + QUERY PLAN +--------------------------------------------------------------- + Hash Semi Join + Hash Cond: (a.two = b.two) + -> Gather + Workers Planned: 4 + -> Parallel Seq Scan on tenk1 a + -> Hash + -> Limit + -> Gather + Workers Planned: 4 + -> Parallel Seq Scan on tenk1 b + Filter: (stringu1 ~~ '%AAAA'::text) +(11 rows) + -- to increase the parallel query test coverage SAVEPOINT settings; SET LOCAL force_parallel_mode = 1; diff --git a/src/test/regress/sql/select_parallel.sql b/src/test/regress/sql/select_parallel.sql index 3d1dffe..938c708 100644 --- a/src/test/regress/sql/select_parallel.sql +++ b/src/test/regress/sql/select_parallel.sql @@ -368,6 +368,11 @@ explain (costs off, verbose) (select unique1, row_number() over() from tenk1 b); +-- LIMIT/OFFSET within sub-selects can't be pushed to workers. +explain (costs off) + select * from tenk1 a where two in + (select two from tenk1 b where stringu1 like '%AAAA' limit 3); + -- to increase the parallel query test coverage SAVEPOINT settings; SET LOCAL force_parallel_mode = 1;
^ permalink raw reply [nested|flat] 38+ messages in thread

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-09-13 12:00  Dilip Kumar <dilipbalaut@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 38+ messages in thread

From: Dilip Kumar @ 2018-09-13 12:00 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Stephen Frost <sfrost@snowman.net>; Robert Haas <robertmhaas@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Wed, Sep 5, 2018 at 10:03 AM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Sun, Sep 2, 2018 at 10:18 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
>> > > Yeah, let me summarize the problems which require patches:
>> > > (a) Consider the presence of a LIMIT/OFFSET in a sub-select as making
>> > > it parallel-unsafe.
>> > >
>> >
>> > As mentioned up-thread, I have considered adding a check in
>> > max_parallel_hazard_walker, but it turns out that it will make the
>> > whole query parallel-unsafe even if one of the sub-selects has
>> > Limit/Offset.  I think the better idea is to detect that during
>> > set_rel_consider_parallel.  Attached patch
>> > prohibit_parallel_limit_subselect_v2 implements the fix for same.
>> >
>>
>> I was trying this patch on back-branches and found that it doesn't
>> apply cleanly beyond PG11, so created separate patches for 10 and 9.6.
>>   Further, I found that the test for this patch was not failing for
>> 9.6 (without the patch) even though the code doesn't deal with this
>> problem.  On further investigation, I found that it is because the
>> commit
>> 655393a022bd653e2b48dbf20b69236981e35195 has not been backpatched to
>> 9.6.  I don't see any reason why we shouldn't backpatch this commit.
>> So, I have attached a patch (fix_parallel_hash_path_v1.patch) which we
>> can backpatch in 9.6.
>>
>> Robert, your input will be highly appreciated here especially for the
>> back patch (to 9.6) I am proposing?
>>
>
> I have rebased the HEAD patch and done some cosmetic changes like
> improved the test by giving aliases to table names and modified the
> comment a bit, otherwise, the core logic remains the same.  As the
> back-branch patches are just the matter of rebasing them, I will do
> that before commit.
>
> I am still waiting for input, but if there is none, my plan is to
> commit this in a day or two and back-patch it as well.  Along with
> this, I would also like to back-patch commit
> 655393a022bd653e2b48dbf20b69236981e35195 for the reasons mentioned
> above.

I have reviewed and tested the patch.  The patch looks fine to me and
behaviour is as expected.

-- 
Regards,
Dilip Kumar
EnterpriseDB: http://www.enterprisedb.com




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-09-13 12:48  Amit Kapila <amit.kapila16@gmail.com>
  parent: Dilip Kumar <dilipbalaut@gmail.com>
  0 siblings, 1 reply; 38+ messages in thread

From: Amit Kapila @ 2018-09-13 12:48 UTC (permalink / raw)
  To: Dilip Kumar <dilipbalaut@gmail.com>; +Cc: Stephen Frost <sfrost@snowman.net>; Robert Haas <robertmhaas@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Thu, Sep 13, 2018 at 5:30 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:
>
> On Wed, Sep 5, 2018 at 10:03 AM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> > On Sun, Sep 2, 2018 at 10:18 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
> >> > > Yeah, let me summarize the problems which require patches:
> >> > > (a) Consider the presence of a LIMIT/OFFSET in a sub-select as making
> >> > > it parallel-unsafe.
> >> > >
> >> >
> >> > As mentioned up-thread, I have considered adding a check in
> >> > max_parallel_hazard_walker, but it turns out that it will make the
> >> > whole query parallel-unsafe even if one of the sub-selects has
> >> > Limit/Offset.  I think the better idea is to detect that during
> >> > set_rel_consider_parallel.  Attached patch
> >> > prohibit_parallel_limit_subselect_v2 implements the fix for same.
> >> >
> >>
> >> I was trying this patch on back-branches and found that it doesn't
> >> apply cleanly beyond PG11, so created separate patches for 10 and 9.6.
> >>   Further, I found that the test for this patch was not failing for
> >> 9.6 (without the patch) even though the code doesn't deal with this
> >> problem.  On further investigation, I found that it is because the
> >> commit
> >> 655393a022bd653e2b48dbf20b69236981e35195 has not been backpatched to
> >> 9.6.  I don't see any reason why we shouldn't backpatch this commit.
> >> So, I have attached a patch (fix_parallel_hash_path_v1.patch) which we
> >> can backpatch in 9.6.
> >>
> >> Robert, your input will be highly appreciated here especially for the
> >> back patch (to 9.6) I am proposing?
> >>
> >
> > I have rebased the HEAD patch and done some cosmetic changes like
> > improved the test by giving aliases to table names and modified the
> > comment a bit, otherwise, the core logic remains the same.  As the
> > back-branch patches are just the matter of rebasing them, I will do
> > that before commit.
> >
> > I am still waiting for input, but if there is none, my plan is to
> > commit this in a day or two and back-patch it as well.  Along with
> > this, I would also like to back-patch commit
> > 655393a022bd653e2b48dbf20b69236981e35195 for the reasons mentioned
> > above.
>
> I have reviewed and tested the patch.  The patch looks fine to me and
> behaviour is as expected.
>

Do you agree with my proposal to backpatch commit - 655393a022 to 9.6?

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-09-13 15:12  Dilip Kumar <dilipbalaut@gmail.com>
  parent: Amit Kapila <amit.kapila16@gmail.com>
  0 siblings, 1 reply; 38+ messages in thread

From: Dilip Kumar @ 2018-09-13 15:12 UTC (permalink / raw)
  To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Stephen Frost <sfrost@snowman.net>; Robert Haas <robertmhaas@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Thu, Sep 13, 2018 at 6:18 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Thu, Sep 13, 2018 at 5:30 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:
>>
>> On Wed, Sep 5, 2018 at 10:03 AM, Amit Kapila <amit.kapila16@gmail.com> wrote:
>> > On Sun, Sep 2, 2018 at 10:18 AM Amit Kapila <amit.kapila16@gmail.com> wrote:
>> >> > > Yeah, let me summarize the problems which require patches:
>> >> > > (a) Consider the presence of a LIMIT/OFFSET in a sub-select as making
>> >> > > it parallel-unsafe.
>> >> > >
>> >> >
>> >> > As mentioned up-thread, I have considered adding a check in
>> >> > max_parallel_hazard_walker, but it turns out that it will make the
>> >> > whole query parallel-unsafe even if one of the sub-selects has
>> >> > Limit/Offset.  I think the better idea is to detect that during
>> >> > set_rel_consider_parallel.  Attached patch
>> >> > prohibit_parallel_limit_subselect_v2 implements the fix for same.
>> >> >
>> >>
>> >> I was trying this patch on back-branches and found that it doesn't
>> >> apply cleanly beyond PG11, so created separate patches for 10 and 9.6.
>> >>   Further, I found that the test for this patch was not failing for
>> >> 9.6 (without the patch) even though the code doesn't deal with this
>> >> problem.  On further investigation, I found that it is because the
>> >> commit
>> >> 655393a022bd653e2b48dbf20b69236981e35195 has not been backpatched to
>> >> 9.6.  I don't see any reason why we shouldn't backpatch this commit.
>> >> So, I have attached a patch (fix_parallel_hash_path_v1.patch) which we
>> >> can backpatch in 9.6.
>> >>
>> >> Robert, your input will be highly appreciated here especially for the
>> >> back patch (to 9.6) I am proposing?
>> >>
>> >
>> > I have rebased the HEAD patch and done some cosmetic changes like
>> > improved the test by giving aliases to table names and modified the
>> > comment a bit, otherwise, the core logic remains the same.  As the
>> > back-branch patches are just the matter of rebasing them, I will do
>> > that before commit.
>> >
>> > I am still waiting for input, but if there is none, my plan is to
>> > commit this in a day or two and back-patch it as well.  Along with
>> > this, I would also like to back-patch commit
>> > 655393a022bd653e2b48dbf20b69236981e35195 for the reasons mentioned
>> > above.
>>
>> I have reviewed and tested the patch.  The patch looks fine to me and
>> behaviour is as expected.
>>
>
> Do you agree with my proposal to backpatch commit - 655393a022 to 9.6?
>

Although it was not giving any wrong output. However, this was a bug,
due to which, it may not select the best parallel plan or completely
miss some of the parallel paths so I will vote for backpatching it.

-- 
Regards,
Dilip Kumar
EnterpriseDB: http://www.enterprisedb.com




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

* Re: BUG #15324: Non-deterministic behaviour from parallelised sub-query
@ 2018-09-14 05:00  Amit Kapila <amit.kapila16@gmail.com>
  parent: Dilip Kumar <dilipbalaut@gmail.com>
  0 siblings, 0 replies; 38+ messages in thread

From: Amit Kapila @ 2018-09-14 05:00 UTC (permalink / raw)
  To: Dilip Kumar <dilipbalaut@gmail.com>; +Cc: Stephen Frost <sfrost@snowman.net>; Robert Haas <robertmhaas@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; Marko Tiikkaja <marko@joh.to>; Andres Freund <andres@anarazel.de>; Andrew Fletcher <andy@prestigedigital.com>; PostgreSQL mailing lists <pgsql-bugs@lists.postgresql.org>

On Thu, Sep 13, 2018 at 8:42 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:
>
> On Thu, Sep 13, 2018 at 6:18 PM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> >> >>
> >> >
> >> > I have rebased the HEAD patch and done some cosmetic changes like
> >> > improved the test by giving aliases to table names and modified the
> >> > comment a bit, otherwise, the core logic remains the same.  As the
> >> > back-branch patches are just the matter of rebasing them, I will do
> >> > that before commit.
> >> >
> >> > I am still waiting for input, but if there is none, my plan is to
> >> > commit this in a day or two and back-patch it as well.  Along with
> >> > this, I would also like to back-patch commit
> >> > 655393a022bd653e2b48dbf20b69236981e35195 for the reasons mentioned
> >> > above.
> >>
> >> I have reviewed and tested the patch.  The patch looks fine to me and
> >> behaviour is as expected.
> >>

Thanks, pushed.

> >
> > Do you agree with my proposal to backpatch commit - 655393a022 to 9.6?
> >
>
> Although it was not giving any wrong output. However, this was a bug,
> due to which, it may not select the best parallel plan or completely
> miss some of the parallel paths so I will vote for backpatching it.
>

Okay, pushed the back-patch patch.

-- 
With Regards,
Amit Kapila.
EnterpriseDB: http://www.enterprisedb.com




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


end of thread, other threads:[~2018-09-14 05:00 UTC | newest]

Thread overview: 38+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2018-08-13 16:14 BUG #15324: Non-deterministic behaviour from parallelised sub-query PG Bug reporting form <noreply@postgresql.org>
2018-08-13 16:35 ` Andres Freund <andres@anarazel.de>
2018-08-13 16:40   ` Andrew Fletcher <andy@prestigedigital.com>
2018-08-13 16:43   ` Marko Tiikkaja <marko@joh.to>
2018-08-13 17:26     ` Tom Lane <tgl@sss.pgh.pa.us>
2018-08-13 17:47       ` Pavel Stehule <pavel.stehule@gmail.com>
2018-08-13 18:04         ` Tom Lane <tgl@sss.pgh.pa.us>
2018-08-13 20:25           ` David G. Johnston <david.g.johnston@gmail.com>
2018-08-13 22:38             ` Tom Lane <tgl@sss.pgh.pa.us>
2018-08-14 04:10       ` Amit Kapila <amit.kapila16@gmail.com>
2018-08-14 07:36         ` Amit Kapila <amit.kapila16@gmail.com>
2018-08-14 10:22         ` Marko Tiikkaja <marko@joh.to>
2018-08-14 11:09           ` Amit Kapila <amit.kapila16@gmail.com>
2018-08-14 11:12             ` Marko Tiikkaja <marko@joh.to>
2018-08-14 11:50               ` Amit Kapila <amit.kapila16@gmail.com>
2018-08-14 12:20                 ` Marko Tiikkaja <marko@joh.to>
2018-08-14 15:44                   ` Tom Lane <tgl@sss.pgh.pa.us>
2018-08-15 00:44                     ` Andrew Gierth <andrew@tao11.riddles.org.uk>
2018-08-15 06:51                     ` Amit Kapila <amit.kapila16@gmail.com>
2018-08-15 11:10                       ` Stephen Frost <sfrost@snowman.net>
2018-08-16 03:55                         ` Amit Kapila <amit.kapila16@gmail.com>
2018-08-16 06:17                           ` Andrew Fletcher <andy@prestigedigital.com>
2018-08-16 06:59                             ` Amit Kapila <amit.kapila16@gmail.com>
2018-08-20 10:50                           ` Amit Kapila <amit.kapila16@gmail.com>
2018-08-20 10:52                             ` Amit Kapila <amit.kapila16@gmail.com>
2018-08-20 13:29                               ` Tom Lane <tgl@sss.pgh.pa.us>
2018-08-21 03:14                                 ` Amit Kapila <amit.kapila16@gmail.com>
2018-09-02 04:51                                   ` Amit Kapila <amit.kapila16@gmail.com>
2018-09-02 18:55                                   ` Tom Lane <tgl@sss.pgh.pa.us>
2018-09-03 04:29                                     ` Amit Kapila <amit.kapila16@gmail.com>
2018-09-03 13:49                                       ` Tom Lane <tgl@sss.pgh.pa.us>
2018-09-04 06:12                                         ` Amit Kapila <amit.kapila16@gmail.com>
2018-09-02 04:48                             ` Amit Kapila <amit.kapila16@gmail.com>
2018-09-05 04:33                               ` Amit Kapila <amit.kapila16@gmail.com>
2018-09-13 12:00                                 ` Dilip Kumar <dilipbalaut@gmail.com>
2018-09-13 12:48                                   ` Amit Kapila <amit.kapila16@gmail.com>
2018-09-13 15:12                                     ` Dilip Kumar <dilipbalaut@gmail.com>
2018-09-14 05:00                                       ` Amit Kapila <amit.kapila16@gmail.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