Parallel INSERT SELECT take 2
Parallel INSERT SELECT take 2
От:
"tsunakawa.takay@fujitsu.com" <tsunakawa.takay@fujitsu.com>
Дата:
This is another try of [1].
BACKGROUND
========================================
We want to realize parallel INSERT SELECT in the following steps:
1) INSERT + parallel SELECT
2) Parallel INSERT + parallel SELECT
Below are example use cases. We don't expect high concurrency or an empty data source.
* Data loading (ETL or ELT) into an analytics database, typically a data ware house.
* Batch processing in an OLTP database.
PROBLEMS
========================================
(1) The overhead of checking parallel-safety could be large
We have to check the target table and its child partitions for parallel safety. That is, we make sure those relations don't have parallel-unsafe domains, constraints, indexes, or triggers.
What we should check is the relations into which the statement actually inserts data. However, the planner does not know which relations will be actually inserted into. So, the planner has to check all descendant partitions of a target table. When the target table has many partitions, this overhead could be unacceptable when compared to the benefit gained from parallelism.
(2) There's no mechanism for parallel workers to assign an XID
Parallel workers need an XID of the current (sub)transaction when actually inserting a tuple (i.e., calling heap_insert()). When the leader has not got the XID yet, the worker may have to assign a new XID and communicate it to the leader and other workers so that all parallel processes use the same XID.
SOLUTION TO (1)
========================================
The candidate ideas are:
1) Caching the result of parallel-safety check
The planner stores the result of checking parallel safety for each relation in relcache, or some purpose-built hash table in shared memory.
The problems are:
* Even if the target relation turns out to be parallel safe by looking at those data structures, we cannot assume it remains true until the SQL statement finishes. For instance, other sessions might add a parallel-unsafe index to its descendant relations. Other examples include that when the user changes the parallel safety of indexes or triggers by running ALTER FUNCTION on the underlying index AM function or trigger function, the relcache entry of the table or index is not invalidated, so the correct parallel safety is not maintained in the cache.
In that case, when the executor encounters a parallel-unsafe object, it can change the cached state as being parallel-unsafe and error out.
* Can't ensure fast access. With relcache, the first access in each session has to undergo the overhead of parallel-safety check. With a hash table in shared memory, the number of relations stored there would be limited, so the first access after database startup or the hash table entry eviction similarly experiences slowness.
* With a new hash table, some lwlock for concurrent access must be added, which can have an adverse effect on performance.
2) Enabling users to declare that the table allows parallel data modification
Add a table property that represents parallel safety of the table for DML statement execution. Users specify it as follows:
CREATE TABLE table_name (...) PARALLEL { UNSAFE | RESTRICTED | SAFE };
ALTER TABLE table_name PARALLEL { UNSAFE | RESTRICTED | SAFE };
This property is recorded in pg_class's relparallel column as 'u', 'r', or 's', just like pg_proc's proparallel. The default is UNSAFE.
The planner assumes that all of the table, its descendant partitions, and their ancillary objects have the specified parallel safety or safer one. The user is responsible for its correctness. If the parallel processes find an object that is less safer than the assumed parallel safety during statement execution, it throws an ERROR and abort the statement execution.
The objects that relate to the parallel safety of a DML target table are as follows:
* Column default expression
* DOMAIN type CHECK expression
* CHECK constraints on column
* Partition key
* Partition key support function
* Index expression
* Index predicate
* Index AM function
* Operator function
* Trigger function
When the parallel safety of some of these objects is changed, it's costly to reflect it on the parallel safety of tables that depend on them. So, we don't do it. Instead, we provide a utility function pg_get_parallel_safety('table_name') that returns records of (objid, classid, parallel_safety) that represent the parallel safety of objects that determine the parallel safety of the specified table. The function only outputs objects that are not parallel safe. Otherwise, it will consume excessive memory while accumulating the output. The user can use this function to identify problematic objects when a parallel DML fails or is not parallelized in an expected manner.
How does the executor detect parallel unsafe objects? There are two ways:
1) At loading time
When the executor loads the definition of objects (tables, constraints, index, triggers, etc.) during the first access to them after session start or their eviction by sinval message, it checks the parallel safety.
This is a legitimate way, but may need much code. Also, it might overlook necessary code changes without careful inspection.
2) At function execution time
All related objects come down to some function execution. So, add a parallel safety check there when in a parallel worker. If the current process is a parallel worker and the function is parallel unsafe, error out with ereport(ERROR). This approach eliminates the oversight of parallel safety check with the additional bonus of tiny code change!
The place would be FunctionCallInvoke(). It's a macro in fmgr.h now. Perhaps we should make it a function in fmgr.c, so that fmgr.h does not have to include header files for parallelism-related definitions.
We have to evaluate the performance effect of converting FunctionCallInvoke() into a function and adding an if statement there, because it's a relatively low-level function.
SOLUTION TO (2)
========================================
1) Make it possible for workers to assign an XID and share it among the parallel processes
The problems are:
* Tuple visibility
If the worker that acquires the XID writes some row and another worker reads that row before it gets to see the XID information, the latter worker won't treat such a row is written by its own transaction.
For instance, the worker (w-1) that acquires the XID (501) deletes the tuple (CTID: 0, 2). Now, another worker (w-2) reads that tuple (CTID: 0, 2), it would consider that the tuple is still visible to its snapshot but if the w-2 knows that 501 is its own XID, it would have been considered it as (not-visible) deleted. I think this can happen when multiple updates to the same row happen and new rows get added to the new page.
* The implementation seems complex
When the DML is run inside a deeply nested subtransaction and the parent transactions have not allocated their XIDs yet, the worker needs to allocate the XIDs for its parents. That indeterminate number of XIDs must be stored in shared memory. The stack of TransactionState structures must also be passed.
Also, TransactionIdIsCurrentTransactionId() uses an array ParallelCurrentXids where parallel workers receive sub-committed XIDs from the leader. This needs to be reconsidered.
2) The leader assigns an XID before entering parallel mode and passes it to workers
This is what was done in [1].
The problem is that the XID would not be used if the data source (SELECT query) returns no valid rows. This is a waste of XID.
However, the data source should be rarely empty when this feature is used. As the following Oracle manual says, parallel DML will be used in data analytics and OLTP batch jobs. There should be plenty of source data in those scenarios.
When to Use Parallel DML
https://docs.oracle.com/en/database/oracle/oracle-database/21/vldbg/types-parallelism.html#GUID-18B2AF09-C548-48DE-A794-86224111549F
--------------------------------------------------
Several scenarios where parallel DML is used include:
Refreshing Tables in a Data Warehouse System
Creating Intermediate Summary Tables
Using Scoring Tables
Updating Historical Tables
Running Batch Jobs
--------------------------------------------------
CONCLUSION
========================================
(1) The overhead of checking parallel-safety could be large
We're inclined to go with solution 2, because it doesn't have a big problem. However, we'd like to try to present some more analysis on solution 1 in this thread.
Regarding how to check parallel safety in executor, I prefer the simpler way of adding a check in function execution. If it turns out to have an untolerable performance problem, we can choose the other approach.
(2) There's no mechanism for parallel workers to assign an XID
We'd like to adopt solution 2 because it will really not have a big issue in the assumed use cases. The implementation is very easy and does not look strange.
Of course, any better-looking idea would be much appreciated. (But simple, or not unnecessarily complex, one is desired.)
[1]
Parallel INSERT (INTO ... SELECT ...)
https://www.postgresql.org/message-id/flat/CAJcOf-cXnB5cnMKqWEp2E2z7Mvcd04iLVmV=qpFJrR3AcrTS3g@mail.gmail.com
Regards
Takayuki Tsunakawa
RE: Parallel INSERT SELECT take 2
> BACKGROUND
> ========================================
>
> We want to realize parallel INSERT SELECT in the following steps:
> 1) INSERT + parallel SELECT
> 2) Parallel INSERT + parallel SELECT
>
> Below are example use cases. We don't expect high concurrency or an empty
> data source.
> * Data loading (ETL or ELT) into an analytics database, typically a data ware
> house.
> * Batch processing in an OLTP database.
> 2) Enabling users to declare that the table allows parallel data modification Add
> a table property that represents parallel safety of the table for DML statement
> execution. Users specify it as follows:
>
> CREATE TABLE table_name (...) PARALLEL { UNSAFE | RESTRICTED | SAFE };
> ALTER TABLE table_name PARALLEL { UNSAFE | RESTRICTED | SAFE };
>
> This property is recorded in pg_class's relparallel column as 'u', 'r', or 's', just
> like pg_proc's proparallel. The default is UNSAFE.
>
> The planner assumes that all of the table, its descendant partitions, and their
> ancillary objects have the specified parallel safety or safer one. The user is
> responsible for its correctness. If the parallel processes find an object that is
> less safer than the assumed parallel safety during statement execution, it
> throws an ERROR and abort the statement execution.
>
> When the parallel safety of some of these objects is changed, it's costly to
> reflect it on the parallel safety of tables that depend on them. So, we don't do
> it. Instead, we provide a utility function pg_get_parallel_safety('table_name')
> that returns records of (objid, classid, parallel_safety) that represent the
> parallel safety of objects that determine the parallel safety of the specified
> table. The function only outputs objects that are not parallel safe. Otherwise,
> it will consume excessive memory while accumulating the output. The user
> can use this function to identify problematic objects when a parallel DML fails
> or is not parallelized in an expected manner.
>
> How does the executor detect parallel unsafe objects? There are two ways:
>
> 1) At loading time
> ...
> 2) At function execution time
> All related objects come down to some function execution. So, add a parallel
> safety check there when in a parallel worker. If the current process is a parallel
> worker and the function is parallel unsafe, error out with ereport(ERROR). This
> approach eliminates the oversight of parallel safety check with the additional
> bonus of tiny code change!
>
> The place would be FunctionCallInvoke(). It's a macro in fmgr.h now. Perhaps
> we should make it a function in fmgr.c, so that fmgr.h does not have to include
> header files for parallelism-related definitions.
>
> We have to evaluate the performance effect of converting FunctionCallInvoke()
> into a function and adding an if statement there, because it's a relatively
> low-level function.
Based on above, we plan to move forward with the apporache 2) (declarative idea).
Attatching the POC patchset which including the following:
0001: provide a utility function pg_get_parallel_safety('table_name').
The function returns records of (objid, classid, parallel_safety) that represent
the parallel safety of objects that determine the parallel safety of the specified table.
Note: The function only outputs objects that are not parallel safe.
(Thanks a lot for greg's previous work, most of the safety check code here is based on it)
0002: allow user use "ALTER TABLE PARALLEL SAFE/UNSAFE/RESTRICTED".
Add proparallel column in pg_class and allow use to change its.
0003: detect parallel unsafe objects in executor.
Currently we choose to check function's parallel safety at function execution time.
We add safety check at FunctionCallInvoke(), but it may be better to check in fmgr_info_cxt_security.
we are still discussing it in another thread[1].
TODO: we currently skip checking built-in function's parallel safety, because we lack the information about built-in
function's parallel safety, we cannot access pg_proc.proparallel in a low level because it could result in infinite recursion.
Adding parallel property in fmgrBuiltin will enlarge the frequently accessed fmgr_builtins and lock down the value of the
parallel-safety flag. The solution is still under discussion. Suggestions and comments are welcome.
0004: fix some mislabeled function in testcase
Since we check parallel safety of function at a low level, we found some functions marked as parallel unsafe will be
executed in parallel mode in regression test when setting force_parallel_mode=regress. After checking, these functions
are parallel safe, So , we plan to fix these function's parallel label.
Note: we plan to take 0004 as a separate patch , see[2], I post 0004 here just to prevent some testcase failures.
The above are the POC patches, it could be imperfect for now and I am still working on improving it.
Suggestions and comments about the design or code are very welcome and appreciated.
Best regards,
houzj
RE: Parallel INSERT SELECT take 2
От:
"houzj.fnst@fujitsu.com" <houzj.fnst@fujitsu.com>
Дата:
> > BACKGROUND
> > ========================================
> >
> > We want to realize parallel INSERT SELECT in the following steps:
> > 1) INSERT + parallel SELECT
> > 2) Parallel INSERT + parallel SELECT
> >
> > Below are example use cases. We don't expect high concurrency or an
> > empty data source.
> > * Data loading (ETL or ELT) into an analytics database, typically a
> > data ware house.
> > * Batch processing in an OLTP database.
> > 2) Enabling users to declare that the table allows parallel data
> > modification Add a table property that represents parallel safety of
> > the table for DML statement execution. Users specify it as follows:
> >
> > CREATE TABLE table_name (...) PARALLEL { UNSAFE | RESTRICTED | SAFE };
> > ALTER TABLE table_name PARALLEL { UNSAFE | RESTRICTED | SAFE };
> >
> > This property is recorded in pg_class's relparallel column as 'u',
> > 'r', or 's', just like pg_proc's proparallel. The default is UNSAFE.
> >
> > The planner assumes that all of the table, its descendant partitions,
> > and their ancillary objects have the specified parallel safety or
> > safer one. The user is responsible for its correctness. If the
> > parallel processes find an object that is less safer than the assumed
> > parallel safety during statement execution, it throws an ERROR and abort the
> statement execution.
> >
> > When the parallel safety of some of these objects is changed, it's
> > costly to reflect it on the parallel safety of tables that depend on
> > them. So, we don't do it. Instead, we provide a utility function
> > pg_get_parallel_safety('table_name')
> > that returns records of (objid, classid, parallel_safety) that
> > represent the parallel safety of objects that determine the parallel
> > safety of the specified table. The function only outputs objects that
> > are not parallel safe. Otherwise, it will consume excessive memory
> > while accumulating the output. The user can use this function to
> > identify problematic objects when a parallel DML fails or is not parallelized in
> an expected manner.
> >
> > How does the executor detect parallel unsafe objects? There are two ways:
> >
> > 1) At loading time
> > ...
> > 2) At function execution time
> > All related objects come down to some function execution. So, add a
> > parallel safety check there when in a parallel worker. If the current
> > process is a parallel worker and the function is parallel unsafe,
> > error out with ereport(ERROR). This approach eliminates the oversight
> > of parallel safety check with the additional bonus of tiny code change!
> >
> > The place would be FunctionCallInvoke(). It's a macro in fmgr.h now.
> > Perhaps we should make it a function in fmgr.c, so that fmgr.h does
> > not have to include header files for parallelism-related definitions.
> >
> > We have to evaluate the performance effect of converting
> > FunctionCallInvoke() into a function and adding an if statement there,
> > because it's a relatively low-level function.
>
> Based on above, we plan to move forward with the apporache 2) (declarative
> idea).
>
> Attatching the POC patchset which including the following:
>
> 0001: provide a utility function pg_get_parallel_safety('table_name').
>
> The function returns records of (objid, classid, parallel_safety) that represent
> the parallel safety of objects that determine the parallel safety of the
> specified table.
> Note: The function only outputs objects that are not parallel safe.
> (Thanks a lot for greg's previous work, most of the safety check code here is
> based on it)
>
> 0002: allow user use "ALTER TABLE PARALLEL SAFE/UNSAFE/RESTRICTED".
>
> Add proparallel column in pg_class and allow use to change its.
>
> 0003: detect parallel unsafe objects in executor.
>
> Currently we choose to check function's parallel safety at function execution
> time.
> We add safety check at FunctionCallInvoke(), but it may be better to check in
> fmgr_info_cxt_security.
> we are still discussing it in another thread[1].
>
> TODO: we currently skip checking built-in function's parallel safety, because
> we lack the information about built-in
> function's parallel safety, we cannot access pg_proc.proparallel in a low level
> because it could result in infinite recursion.
> Adding parallel property in fmgrBuiltin will enlarge the frequently accessed
> fmgr_builtins and lock down the value of the
> parallel-safety flag. The solution is still under discussion. Suggestions and
> comments are welcome.
>
> 0004: fix some mislabeled function in testcase
>
> Since we check parallel safety of function at a low level, we found some
> functions marked as parallel unsafe will be
> executed in parallel mode in regression test when setting
> force_parallel_mode=regress. After checking, these functions
> are parallel safe, So , we plan to fix these function's parallel label.
> Note: we plan to take 0004 as a separate patch , see[2], I post 0004 here just
> to prevent some testcase failures.
>
> The above are the POC patches, it could be imperfect for now and I am still
> working on improving it.
> Suggestions and comments about the design or code are very welcome and
> appreciated.
Sorry, I forgot to attach the discussion link about [1] and [2].
[1]
https://www.postgresql.org/message-id/756027.1619012086%40sss.pgh.pa.us
[2]
https://www.postgresql.org/message-id/OS0PR01MB571637085C0D3AFC3AB3600194479%40OS0PR01MB5716.jpnprd01.prod.outlook.com
Best regards,
houzj
Re: Parallel INSERT SELECT take 2
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
On Thu, Apr 22, 2021 at 4:51 PM houzj.fnst@fujitsu.com
wrote:
>
> > BACKGROUND
> > ========================================
> >
> > We want to realize parallel INSERT SELECT in the following steps:
> > 1) INSERT + parallel SELECT
> > 2) Parallel INSERT + parallel SELECT
> >
> > Below are example use cases. We don't expect high concurrency or an empty
> > data source.
> > * Data loading (ETL or ELT) into an analytics database, typically a data ware
> > house.
> > * Batch processing in an OLTP database.
> > 2) Enabling users to declare that the table allows parallel data modification Add
> > a table property that represents parallel safety of the table for DML statement
> > execution. Users specify it as follows:
> >
> > CREATE TABLE table_name (...) PARALLEL { UNSAFE | RESTRICTED | SAFE };
> > ALTER TABLE table_name PARALLEL { UNSAFE | RESTRICTED | SAFE };
> >
> > This property is recorded in pg_class's relparallel column as 'u', 'r', or 's', just
> > like pg_proc's proparallel. The default is UNSAFE.
> >
> > The planner assumes that all of the table, its descendant partitions, and their
> > ancillary objects have the specified parallel safety or safer one. The user is
> > responsible for its correctness. If the parallel processes find an object that is
> > less safer than the assumed parallel safety during statement execution, it
> > throws an ERROR and abort the statement execution.
> >
> > When the parallel safety of some of these objects is changed, it's costly to
> > reflect it on the parallel safety of tables that depend on them. So, we don't do
> > it. Instead, we provide a utility function pg_get_parallel_safety('table_name')
> > that returns records of (objid, classid, parallel_safety) that represent the
> > parallel safety of objects that determine the parallel safety of the specified
> > table. The function only outputs objects that are not parallel safe. Otherwise,
> > it will consume excessive memory while accumulating the output. The user
> > can use this function to identify problematic objects when a parallel DML fails
> > or is not parallelized in an expected manner.
> >
> > How does the executor detect parallel unsafe objects? There are two ways:
> >
> > 1) At loading time
> > ...
> > 2) At function execution time
> > All related objects come down to some function execution. So, add a parallel
> > safety check there when in a parallel worker. If the current process is a parallel
> > worker and the function is parallel unsafe, error out with ereport(ERROR). This
> > approach eliminates the oversight of parallel safety check with the additional
> > bonus of tiny code change!
> >
> > The place would be FunctionCallInvoke(). It's a macro in fmgr.h now. Perhaps
> > we should make it a function in fmgr.c, so that fmgr.h does not have to include
> > header files for parallelism-related definitions.
> >
> > We have to evaluate the performance effect of converting FunctionCallInvoke()
> > into a function and adding an if statement there, because it's a relatively
> > low-level function.
>
> Based on above, we plan to move forward with the apporache 2) (declarative idea).
IIUC, the declarative behaviour idea attributes parallel
safe/unsafe/restricted tags to each table with default being the
unsafe. Does it mean for a parallel unsafe table, no parallel selects,
inserts (may be updates) will be picked up? Or is it only the parallel
inserts? If both parallel inserts, selects will be picked, then the
existing tables need to be adjusted to set the parallel safety tags
while migrating?
Another point, what does it mean a table being parallel restricted?
What should happen if it is present in a query of other parallel safe
tables?
I may be wrong here: IIUC, the main problem we are trying to solve
with the declarative approach is to let the user decide parallel
safety for partition tables as it may be costlier for postgres to
determine it. And for the normal tables we can perform parallel safety
checks without incurring much cost. So, I think we should restrict the
declarative approach to only partitioned tables?
While reading the design, I came across this "erroring out during
execution of a query when a parallel unsafe function is detected". If
this is correct, isn't it warranting users to run
pg_get_parallel_safety to know the parallel unsafe objects, set
parallel safety to all of them if possible, otherwise disable
parallelism to run the query? Isn't this burdensome? Instead, how
about postgres retries the query upon detecting the error that came
from a parallel unsafe function during execution, disable parallelism
and run the query? I think this kind of retry query feature can be
built outside of the core postgres, but IMO it will be good to have
inside (of course configurable). IIRC, the Teradata database has a
Query Retry feature.
With Regards,
Bharath Rupireddy.
EnterpriseDB: http://www.enterprisedb.com
RE: Parallel INSERT SELECT take 2
От:
"houzj.fnst@fujitsu.com" <houzj.fnst@fujitsu.com>
Дата:
> > Based on above, we plan to move forward with the apporache 2) (declarative > idea). > > IIUC, the declarative behaviour idea attributes parallel safe/unsafe/restricted > tags to each table with default being the unsafe. Does it mean for a parallel > unsafe table, no parallel selects, inserts (may be updates) will be picked up? Or > is it only the parallel inserts? If both parallel inserts, selects will be picked, then > the existing tables need to be adjusted to set the parallel safety tags while > migrating? Thanks for looking into this. The parallel attributes in table means the parallel safety when user does some data-modification operations on it. So, It only limit the use of parallel plan when using INSERT/UPDATE/DELETE. > Another point, what does it mean a table being parallel restricted? > What should happen if it is present in a query of other parallel safe tables? If a table is parallel restricted, it means the table contains some parallel restricted objects(such as: parallel restricted functions in index expressions). And in planner, it means parallel insert plan will not be chosen, but it can use parallel select(with serial insert). > I may be wrong here: IIUC, the main problem we are trying to solve with the > declarative approach is to let the user decide parallel safety for partition tables > as it may be costlier for postgres to determine it. And for the normal tables we > can perform parallel safety checks without incurring much cost. So, I think we > should restrict the declarative approach to only partitioned tables? Yes, we are tring to avoid overhead when checking parallel safety. The cost to check all the partition's parallel safety is the biggest one. Another is the safety check of index's expression. Currently, for INSERT, the planner does not open the target table's indexinfo and does not parse the expression of the index. We need to parse the expression in planner if we want to do parallel safety check for it which can bring some overhead(it will open the index the do the parse in executor again). So, we plan to skip all of the extra check and let user take responsibility for the safety. Of course, maybe we can try to pass the indexinfo to the executor but it need some further refactor and I will take a look into it. > While reading the design, I came across this "erroring out during execution of a > query when a parallel unsafe function is detected". If this is correct, isn't it > warranting users to run pg_get_parallel_safety to know the parallel unsafe > objects, set parallel safety to all of them if possible, otherwise disable > parallelism to run the query? Isn't this burdensome? How about: If detecting parallel unsafe objects in executor, then, alter the table to parallel unsafe internally. So, user do not need to alter it manually. > Instead, how about > postgres retries the query upon detecting the error that came from a parallel > unsafe function during execution, disable parallelism and run the query? I think > this kind of retry query feature can be built outside of the core postgres, but > IMO it will be good to have inside (of course configurable). IIRC, the Teradata > database has a Query Retry feature. > Thanks for the suggestion. The retry query feature sounds like a good idea to me. OTOH, it sounds more like an independent feature which parallel select can also benefit from it. I think maybe we can try to achieve it after we commit the parallel insert ? Best regards, houzj
Re: Parallel INSERT SELECT take 2
От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Mon, Apr 26, 2021 at 7:00 AM houzj.fnst@fujitsu.com wrote: > > > Instead, how about > > postgres retries the query upon detecting the error that came from a parallel > > unsafe function during execution, disable parallelism and run the query? I think > > this kind of retry query feature can be built outside of the core postgres, but > > IMO it will be good to have inside (of course configurable). IIRC, the Teradata > > database has a Query Retry feature. > > > > Thanks for the suggestion. > The retry query feature sounds like a good idea to me. > OTOH, it sounds more like an independent feature which parallel select can also benefit from it. > +1. I also think retrying a query on an error is not related to this feature and should be built separately if required. -- With Regards, Amit Kapila.
Re: Parallel INSERT SELECT take 2
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
On Mon, Apr 26, 2021 at 7:00 AM houzj.fnst@fujitsu.com
wrote:
>
> > > Based on above, we plan to move forward with the apporache 2) (declarative
> > idea).
> >
> > IIUC, the declarative behaviour idea attributes parallel safe/unsafe/restricted
> > tags to each table with default being the unsafe. Does it mean for a parallel
> > unsafe table, no parallel selects, inserts (may be updates) will be picked up? Or
> > is it only the parallel inserts? If both parallel inserts, selects will be picked, then
> > the existing tables need to be adjusted to set the parallel safety tags while
> > migrating?
>
> Thanks for looking into this.
Thanks for the responses.
> The parallel attributes in table means the parallel safety when user does some data-modification operations on it.
> So, It only limit the use of parallel plan when using INSERT/UPDATE/DELETE.
In that case, isn't it better to use the terminology "PARALLEL DML
SAFE/UNSAFE/RESTRICTED" in the code and docs? This way, it will be
clear that these tags don't affect parallel selects.
> > Another point, what does it mean a table being parallel restricted?
> > What should happen if it is present in a query of other parallel safe tables?
>
> If a table is parallel restricted, it means the table contains some parallel restricted objects(such as: parallel restricted functions in index expressions).
> And in planner, it means parallel insert plan will not be chosen, but it can use parallel select(with serial insert).
Makes sense. I assume that when there is a parallel restricted
function associated with a table, the current design doesn't enforce
the planner to choose parallel select and it is left up to it.
> > I may be wrong here: IIUC, the main problem we are trying to solve with the
> > declarative approach is to let the user decide parallel safety for partition tables
> > as it may be costlier for postgres to determine it. And for the normal tables we
> > can perform parallel safety checks without incurring much cost. So, I think we
> > should restrict the declarative approach to only partitioned tables?
>
> Yes, we are tring to avoid overhead when checking parallel safety.
> The cost to check all the partition's parallel safety is the biggest one.
> Another is the safety check of index's expression.
> Currently, for INSERT, the planner does not open the target table's indexinfo and does not
> parse the expression of the index. We need to parse the expression in planner if we want
> to do parallel safety check for it which can bring some overhead(it will open the index the do the parse in executor again).
> So, we plan to skip all of the extra check and let user take responsibility for the safety.
> Of course, maybe we can try to pass the indexinfo to the executor but it need some further refactor and I will take a look into it.
Will the planner parse and check parallel safety of index((where
clause) expressions in case of SELECTs? I'm not sure of this. But if
it does, maybe we could do the same thing for parallel DML as well for
normal tables? What is the overhead of parsing index expressions? If
the cost is heavy for checking index expressions parallel safety in
case of normal tables, then the current design i.e. attributing
parallel safety tag to all the tables makes sense.
I was actually thinking that we will have the declarative approach
only for partitioned tables as it is the main problem we are trying to
solve with this design. Something like: users will run
pg_get_parallel_safety to see the parallel unsafe objects associated
with a partitioned table by looking at all of its partitions and be
able to set a parallel dml safety tag to only partitioned tables.
> > While reading the design, I came across this "erroring out during execution of a
> > query when a parallel unsafe function is detected". If this is correct, isn't it
> > warranting users to run pg_get_parallel_safety to know the parallel unsafe
> > objects, set parallel safety to all of them if possible, otherwise disable
> > parallelism to run the query? Isn't this burdensome?
>
> How about:
> If detecting parallel unsafe objects in executor, then, alter the table to parallel unsafe internally.
> So, user do not need to alter it manually.
I don't think this is a good idea, because, if there are multiple
tables involved in the query, do you alter all the tables? Usually, we
error out on finding the first such unsafe object.
> > Instead, how about
> > postgres retries the query upon detecting the error that came from a parallel
> > unsafe function during execution, disable parallelism and run the query? I think
> > this kind of retry query feature can be built outside of the core postgres, but
> > IMO it will be good to have inside (of course configurable). IIRC, the Teradata
> > database has a Query Retry feature.
> >
>
> Thanks for the suggestion.
> The retry query feature sounds like a good idea to me.
> OTOH, it sounds more like an independent feature which parallel select can also benefit from it.
> I think maybe we can try to achieve it after we commit the parallel insert ?
Yeah, it will be a separate thing altogether.
>0001: provide a utility function pg_get_parallel_safety('table_name').
>
>The function returns records of (objid, classid, parallel_safety) that represent
>the parallel safety of objects that determine the parallel safety of the specified table.
>Note: The function only outputs objects that are not parallel safe.
If it returns only parallel "unsafe" objects and not "safe" or
"restricted" objects, how about naming it to
pg_get_table_parallel_unsafe_objects("table_name")? This way we could
get rid of parallel_safety in the output record? If at all users want
to see parallel restricted or safe objects, we can also have the
counterparts pg_get_table_parallel_safe_objects and
pg_get_table_parallel_restricted_objects. Of course, we can caution
the user that execution of these functions might take longer and
"might consume excessive memory while accumulating the output".
Otherwise, we can have a single function
pg_get_parallel_safety("table_name" IN, "parallel_safety" IN, "objid"
OUT, "classid" OUT)? If required, we could name it
pg_get_parallel_safety_of_table_objects.
Thoughts?
Although, I have not looked at the patches, few questions on
pg_get_parallel_safety function:
1) Will it parse all the expressions for the objects that are listed
under "The objects that relate to the parallel safety of a DML target
table are as follows:" in the upthread?
2) How will it behave if a partitioned table is passed to it? Will it
recurse for all the partitions?
3) How will it behave if a foreign table is passed to it? Will it error out?
In general:
1) Is ALTER SET PARALLEL SAFETY on a partitioned table allowed? If
yes, will it be set based on all the partitions parallel safety?
2) How will users have to decide on parallel safety of a foreign table
or a partitioned table with foreign partitions? Or is it that we set
these tables parallel unsafe and don't do parallel inserts?
With Regards,
Bharath Rupireddy.
EnterpriseDB: http://www.enterprisedb.com
RE: Parallel INSERT SELECT take 2
От:
"houzj.fnst@fujitsu.com" <houzj.fnst@fujitsu.com>
Дата:
> > The parallel attributes in table means the parallel safety when user does some
> data-modification operations on it.
> > So, It only limit the use of parallel plan when using INSERT/UPDATE/DELETE.
>
> In that case, isn't it better to use the terminology "PARALLEL DML
> SAFE/UNSAFE/RESTRICTED" in the code and docs? This way, it will be clear that
> these tags don't affect parallel selects.
Makes sense, I recalled I have heart similar suggestion before.
If there are no other objections, I plan to change command to
PARALLEL DML in my next version patches.
> > > I may be wrong here: IIUC, the main problem we are trying to solve
> > > with the declarative approach is to let the user decide parallel
> > > safety for partition tables as it may be costlier for postgres to
> > > determine it. And for the normal tables we can perform parallel
> > > safety checks without incurring much cost. So, I think we should restrict the
> declarative approach to only partitioned tables?
> >
> > Yes, we are tring to avoid overhead when checking parallel safety.
> > The cost to check all the partition's parallel safety is the biggest one.
> > Another is the safety check of index's expression.
> > Currently, for INSERT, the planner does not open the target table's
> > indexinfo and does not parse the expression of the index. We need to
> > parse the expression in planner if we want to do parallel safety check for it
> which can bring some overhead(it will open the index the do the parse in
> executor again).
> > So, we plan to skip all of the extra check and let user take responsibility for
> the safety.
> > Of course, maybe we can try to pass the indexinfo to the executor but it need
> some further refactor and I will take a look into it.
>
> Will the planner parse and check parallel safety of index((where
> clause) expressions in case of SELECTs? I'm not sure of this. But if it does, maybe
> we could do the same thing for parallel DML as well for normal tables?
The planner does not check the index expression, because the expression will not be used in SELECT.
I think the expression is only used when a tuple inserted into the index.
> the overhead of parsing index expressions? If the cost is heavy for checking
> index expressions parallel safety in case of normal tables, then the current
> design i.e. attributing parallel safety tag to all the tables makes sense.
Currently, index expression and predicate are stored in text format.
We need to use stringToNode(expression/predicate) to parse it.
Some committers think doing this twice does not look good,
unless we found some ways to pass parsed info to the executor to avoid the second parse.
> I was actually thinking that we will have the declarative approach only for
> partitioned tables as it is the main problem we are trying to solve with this
> design. Something like: users will run pg_get_parallel_safety to see the parallel
> unsafe objects associated with a partitioned table by looking at all of its
> partitions and be able to set a parallel dml safety tag to only partitioned tables.
We originally want to make the declarative approach for both normal and partitioned table.
In this way, it will not bring any overhead to planner and looks consistency.
But, do you think we should put some really cheap safety check to the planner ?
>
> >0001: provide a utility function pg_get_parallel_safety('table_name').
> >
> >The function returns records of (objid, classid, parallel_safety) that
> >represent the parallel safety of objects that determine the parallel safety of
> the specified table.
> >Note: The function only outputs objects that are not parallel safe.
>
> If it returns only parallel "unsafe" objects and not "safe" or "restricted" objects,
> how about naming it to pg_get_table_parallel_unsafe_objects("table_name")?
Currently, the function returns both unsafe and restricted objects(I thought restricted is also not safe),
because we thought users only care about the objects that affect the use of parallel plan.
> This way we could get rid of parallel_safety in the output record? If at all users
> want to see parallel restricted or safe objects, we can also have the
> counterparts pg_get_table_parallel_safe_objects and
> pg_get_table_parallel_restricted_objects. Of course, we can caution the user
> that execution of these functions might take longer and "might consume
> excessive memory while accumulating the output".
>
> Otherwise, we can have a single function pg_get_parallel_safety("table_name"
> IN, "parallel_safety" IN, "objid"
> OUT, "classid" OUT)? If required, we could name it
> pg_get_parallel_safety_of_table_objects.
>
> Thoughts?
I am sure will user want to get safe objects, do you have some usecases ?
If users do not care the safe objects, I think they can use
"SELECT * FROM pg_get_parallel_safety() where parallel_safety = 'specified safety' " to get the specified objects.
> Although, I have not looked at the patches, few questions on
> pg_get_parallel_safety function:
> 1) Will it parse all the expressions for the objects that are listed under "The
> objects that relate to the parallel safety of a DML target table are as follows:" in
> the upthread?
Yes.
But some parsed expression(such as domain type's expression) can be found in typecache,
we just check the safety for these already parsed expression.
> 2) How will it behave if a partitioned table is passed to it? Will it recurse for all
> the partitions?
Yes, because both parent table and child table will be inserted and the parallel
related objects on them will be executed. If users want to make sure the parallel insert succeed,
they need to check all the objects.
> 3) How will it behave if a foreign table is passed to it? Will it error out?
It currently does not error out.
It will also check the objects on it and return not safe objects.
Note: I consider foreign table itself as a parallel restricted object, because it does not support parallel insert fdw api for now.
> In general:
> 1) Is ALTER SET PARALLEL SAFETY on a partitioned table allowed?
Yes.
> If yes, will it be
> set based on all the partitions parallel safety?
Yes,
But the ALTER PARALLEL command itself does not check all the partition's safety flag.
The function pg_get_parallel_safety can return all the partition's not safe objects,
user should set the parallel safety based the function's result.
> 2) How will users have to decide on parallel safety of a foreign table or a
> partitioned table with foreign partitions? Or is it that we set these tables
> parallel unsafe and don't do parallel inserts?
Foreign table itself is considered as parallel restricted,
because we do not support parallel insert fdw api for now.
Best regards,
houzj
Re: Parallel INSERT SELECT take 2
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
On Mon, Apr 26, 2021 at 4:56 PM houzj.fnst@fujitsu.com
wrote:
> > > The parallel attributes in table means the parallel safety when user does some
> > data-modification operations on it.
> > > So, It only limit the use of parallel plan when using INSERT/UPDATE/DELETE.
> >
> > In that case, isn't it better to use the terminology "PARALLEL DML
> > SAFE/UNSAFE/RESTRICTED" in the code and docs? This way, it will be clear that
> > these tags don't affect parallel selects.
>
> Makes sense, I recalled I have heart similar suggestion before.
> If there are no other objections, I plan to change command to
> PARALLEL DML in my next version patches.
+1 from me. Let's hear from others.
> > Will the planner parse and check parallel safety of index((where
> > clause) expressions in case of SELECTs? I'm not sure of this. But if it does, maybe
> > we could do the same thing for parallel DML as well for normal tables?
>
> The planner does not check the index expression, because the expression will not be used in SELECT.
> I think the expression is only used when a tuple inserted into the index.
Oh.
> > the overhead of parsing index expressions? If the cost is heavy for checking
> > index expressions parallel safety in case of normal tables, then the current
> > design i.e. attributing parallel safety tag to all the tables makes sense.
>
> Currently, index expression and predicate are stored in text format.
> We need to use stringToNode(expression/predicate) to parse it.
> Some committers think doing this twice does not look good,
> unless we found some ways to pass parsed info to the executor to avoid the second parse.
How much is the extra cost that's added if we do stringToNode twiice?
Maybe, we can check for a few sample test cases by just having
stringToNode(expression/predicate) in the planner and see if it adds
much to the total execution time of the query.
> > I was actually thinking that we will have the declarative approach only for
> > partitioned tables as it is the main problem we are trying to solve with this
> > design. Something like: users will run pg_get_parallel_safety to see the parallel
> > unsafe objects associated with a partitioned table by looking at all of its
> > partitions and be able to set a parallel dml safety tag to only partitioned tables.
>
> We originally want to make the declarative approach for both normal and partitioned table.
> In this way, it will not bring any overhead to planner and looks consistency.
> But, do you think we should put some really cheap safety check to the planner ?
I still feel that why we shouldn't limit the declarative approach to
only partitioned tables? And for normal tables, possibly with a
minimal cost(??), the server can do the safety checking. I know this
feels a little inconsistent. In the planner we will have different
paths like: if (partitioned_table) { check the parallel safety tag
associated with the table } else { perform the parallel safety of the
associated objects }.
Others may have better thoughts on this.
> > >0001: provide a utility function pg_get_parallel_safety('table_name').
> > >
> > >The function returns records of (objid, classid, parallel_safety) that
> > >represent the parallel safety of objects that determine the parallel safety of
> > the specified table.
> > >Note: The function only outputs objects that are not parallel safe.
> >
> > If it returns only parallel "unsafe" objects and not "safe" or "restricted" objects,
> > how about naming it to pg_get_table_parallel_unsafe_objects("table_name")?
>
> Currently, the function returns both unsafe and restricted objects(I thought restricted is also not safe),
> because we thought users only care about the objects that affect the use of parallel plan.
Hm.
> > This way we could get rid of parallel_safety in the output record? If at all users
> > want to see parallel restricted or safe objects, we can also have the
> > counterparts pg_get_table_parallel_safe_objects and
> > pg_get_table_parallel_restricted_objects. Of course, we can caution the user
> > that execution of these functions might take longer and "might consume
> > excessive memory while accumulating the output".
> >
> > Otherwise, we can have a single function pg_get_parallel_safety("table_name"
> > IN, "parallel_safety" IN, "objid"
> > OUT, "classid" OUT)? If required, we could name it
> > pg_get_parallel_safety_of_table_objects.
> >
> > Thoughts?
>
> I am sure will user want to get safe objects, do you have some usecases ?
> If users do not care the safe objects, I think they can use
> "SELECT * FROM pg_get_parallel_safety() where parallel_safety = 'specified safety' " to get the specified objects.
I don't know any practical scenarios, but If I'm a user, at least I
will be tempted to see the parallel safe objects associated with a
particular table along with unsafe and restricted ones. Others may
have better thoughts on this.
> > Although, I have not looked at the patches, few questions on
> > pg_get_parallel_safety function:
> > 1) Will it parse all the expressions for the objects that are listed under "The
> > objects that relate to the parallel safety of a DML target table are as follows:" in
> > the upthread?
>
> Yes.
> But some parsed expression(such as domain type's expression) can be found in typecache,
> we just check the safety for these already parsed expression.
Oh.
> > 2) How will it behave if a partitioned table is passed to it? Will it recurse for all
> > the partitions?
>
> Yes, because both parent table and child table will be inserted and the parallel
> related objects on them will be executed. If users want to make sure the parallel insert succeed,
> they need to check all the objects.
Then, running the pg_get_parallel_safety will have some overhead if
there are many partitions associated with a table. And, this is the
overhead planner would have had to incur without the declarative
approach which we are trying to avoid with this design.
> > 3) How will it behave if a foreign table is passed to it? Will it error out?
>
> It currently does not error out.
> It will also check the objects on it and return not safe objects.
> Note: I consider foreign table itself as a parallel restricted object, because it does not support parallel insert fdw api for now.
>
> > 2) How will users have to decide on parallel safety of a foreign table or a
> > partitioned table with foreign partitions? Or is it that we set these tables
> > parallel unsafe and don't do parallel inserts?
>
> Foreign table itself is considered as parallel restricted,
> because we do not support parallel insert fdw api for now.
Maybe, the ALTER TABLE ... SET PARALLEL on a foreign table should
default to parallel restricted always and emit a warning saying the
reason?
> > In general:
> > 1) Is ALTER SET PARALLEL SAFETY on a partitioned table allowed?
>
> Yes.
>
> > If yes, will it be
> > set based on all the partitions parallel safety?
>
> Yes,
> But the ALTER PARALLEL command itself does not check all the partition's safety flag.
> The function pg_get_parallel_safety can return all the partition's not safe objects,
> user should set the parallel safety based the function's result.
I'm thinking that when users say ALTER TABLE partioned_table SET
PARALLEL TO 'safe';, we check all the partitions' and their associated
objects' parallel safety? If all are parallel safe, then only we set
partitioned_table as parallel safe. What should happen if the parallel
safety of any of the associated objects/partitions changes after
setting the partitioned_table safety?
My understanding was that: the command ALTER TABLE ... SET PARALLEL TO
'safe' work will check the parallel safety of all the objects
associated with the table. If the objects are all parallel safe, then
the table will be set to safe. If at least one object is parallel
unsafe or restricted, then the command will fail. I was also thinking
that how will the design cope with situations such as the parallel
safety of any of the associated objects changing after setting the
table to parallel safe. The planner would have relied on the outdated
parallel safety of the table and chosen parallel inserts and the
executor will catch such situations. Looks like my understanding was
wrong.
So, the ALTER TABLE ... SET PARALLEL TO command just sets the target
table safety, doesn't bother what the associated objects' safety is.
It just believes the user. If at all there are any parallel unsafe
objects it will be caught by the executor. Just like, setting parallel
safety of the functions/aggregates, the docs caution users about
accidentally/intentionally tagging parallel unsafe
functions/aggregates as parallel safe.
Note: I meant the table objects are the ones that are listed under
"The objects that relate to the parallel safety of a DML target table
are as follows:" in the upthread.
With Regards,
Bharath Rupireddy.
EnterpriseDB: http://www.enterprisedb.com
RE: Parallel INSERT SELECT take 2
От:
"houzj.fnst@fujitsu.com" <houzj.fnst@fujitsu.com>
Дата:
> > Currently, index expression and predicate are stored in text format. > > We need to use stringToNode(expression/predicate) to parse it. > > Some committers think doing this twice does not look good, unless we > > found some ways to pass parsed info to the executor to avoid the second > parse. > > How much is the extra cost that's added if we do stringToNode twiice? > Maybe, we can check for a few sample test cases by just having > stringToNode(expression/predicate) in the planner and see if it adds much to > the total execution time of the query. OK, I will do some test on it. > > Yes, because both parent table and child table will be inserted and > > the parallel related objects on them will be executed. If users want > > to make sure the parallel insert succeed, they need to check all the objects. > > Then, running the pg_get_parallel_safety will have some overhead if there are > many partitions associated with a table. And, this is the overhead planner > would have had to incur without the declarative approach which we are trying > to avoid with this design. Yes, I think put such overhead in a separate function is better than in a common path(planner). > > Foreign table itself is considered as parallel restricted, because we > > do not support parallel insert fdw api for now. > > Maybe, the ALTER TABLE ... SET PARALLEL on a foreign table should default to > parallel restricted always and emit a warning saying the reason? Thanks for the comment, I agree. I will change this in the next version patches. > > But the ALTER PARALLEL command itself does not check all the partition's > safety flag. > > The function pg_get_parallel_safety can return all the partition's not > > safe objects, user should set the parallel safety based the function's result. > > I'm thinking that when users say ALTER TABLE partioned_table SET PARALLEL > TO 'safe';, we check all the partitions' and their associated objects' parallel > safety? If all are parallel safe, then only we set partitioned_table as parallel safe. > What should happen if the parallel safety of any of the associated > objects/partitions changes after setting the partitioned_table safety? Currently, nothing happened if any of the associated objects/partitions changes after setting the partitioned_table safety. Because , we do not have a really cheap way to catch the change. The existing relcache does not work because alter function does not invalid the relcache which the function belongs to. And it will bring some other overhead(locking, systable scan,...) to find the table the objects belong to. > My understanding was that: the command ALTER TABLE ... SET PARALLEL TO > 'safe' work will check the parallel safety of all the objects associated with the > table. If the objects are all parallel safe, then the table will be set to safe. If at > least one object is parallel unsafe or restricted, then the command will fail. I think this idea makes sense. Some detail of the designed can be improved. I agree with you that we can try to check check all the partitions' and their associated objects' parallel safety when ALTER PARALLEL. Because it's a separate new command, add some overhead to it seems not too bad. If there are no other objections, I plan to add safety check in the ALTER PARALLEL command. > also thinking that how will the design cope with situations such as the parallel > safety of any of the associated objects changing after setting the table to > parallel safe. The planner would have relied on the outdated parallel safety of > the table and chosen parallel inserts and the executor will catch such situations. > Looks like my understanding was wrong. Currently, we assume user is responsible for its correctness. Because, from our research, when the parallel safety of some of these objects is changed, it's costly to reflect it on the parallel safety of tables that depend on them. (we need to scan the pg_depend,pg_inherit,pg_index.... to find the target table) > So, the ALTER TABLE ... SET PARALLEL TO command just sets the target table > safety, doesn't bother what the associated objects' safety is. > It just believes the user. If at all there are any parallel unsafe objects it will be > caught by the executor. Just like, setting parallel safety of the > functions/aggregates, the docs caution users about accidentally/intentionally > tagging parallel unsafe functions/aggregates as parallel safe. Yes, thanks for looking into this. Best regards, houzj
Re: Parallel INSERT SELECT take 2
От:
Greg Nancarrow <gregn4422@gmail.com>
Дата:
On Tue, Apr 27, 2021 at 10:51 AM Bharath Rupireddy
wrote:
>
>
> I still feel that why we shouldn't limit the declarative approach to
> only partitioned tables? And for normal tables, possibly with a
> minimal cost(??), the server can do the safety checking. I know this
> feels a little inconsistent. In the planner we will have different
> paths like: if (partitioned_table) { check the parallel safety tag
> associated with the table } else { perform the parallel safety of the
> associated objects }.
>
Personally I think the simplest and best approach is just do it
consistently, using the declarative approach across all table types.
>
> Then, running the pg_get_parallel_safety will have some overhead if
> there are many partitions associated with a table. And, this is the
> overhead planner would have had to incur without the declarative
> approach which we are trying to avoid with this design.
>
The big difference is that pg_get_parallel_safety() is intended to be
used during development, not as part of runtime parallel-safety checks
(which are avoided using the declarative approach).
So there is no runtime overhead associated with pg_get_parallel_safety().
>
> I'm thinking that when users say ALTER TABLE partioned_table SET
> PARALLEL TO 'safe';, we check all the partitions' and their associated
> objects' parallel safety? If all are parallel safe, then only we set
> partitioned_table as parallel safe. What should happen if the parallel
> safety of any of the associated objects/partitions changes after
> setting the partitioned_table safety?
>
With the declarative approach, there is no parallel-safety checking on
either the CREATE/ALTER when the parallel-safety is declared/set.
It's up to the user to get it right. If it's actually wrong, it will
be detected at runtime.
Regards,
Greg Nancarrow
Fujitsu Australia
Re: Parallel INSERT SELECT take 2
От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Tue, Apr 27, 2021 at 7:45 AM Greg Nancarrow wrote:
>
> On Tue, Apr 27, 2021 at 10:51 AM Bharath Rupireddy
> wrote:
> >
> >
> > I still feel that why we shouldn't limit the declarative approach to
> > only partitioned tables? And for normal tables, possibly with a
> > minimal cost(??), the server can do the safety checking. I know this
> > feels a little inconsistent. In the planner we will have different
> > paths like: if (partitioned_table) { check the parallel safety tag
> > associated with the table } else { perform the parallel safety of the
> > associated objects }.
> >
>
> Personally I think the simplest and best approach is just do it
> consistently, using the declarative approach across all table types.
>
Yeah, if we decide to go with a declarative approach then that sounds
like a better approach.
> >
> > Then, running the pg_get_parallel_safety will have some overhead if
> > there are many partitions associated with a table. And, this is the
> > overhead planner would have had to incur without the declarative
> > approach which we are trying to avoid with this design.
> >
>
> The big difference is that pg_get_parallel_safety() is intended to be
> used during development, not as part of runtime parallel-safety checks
> (which are avoided using the declarative approach).
> So there is no runtime overhead associated with pg_get_parallel_safety().
>
> >
> > I'm thinking that when users say ALTER TABLE partioned_table SET
> > PARALLEL TO 'safe';, we check all the partitions' and their associated
> > objects' parallel safety? If all are parallel safe, then only we set
> > partitioned_table as parallel safe. What should happen if the parallel
> > safety of any of the associated objects/partitions changes after
> > setting the partitioned_table safety?
> >
>
> With the declarative approach, there is no parallel-safety checking on
> either the CREATE/ALTER when the parallel-safety is declared/set.
> It's up to the user to get it right. If it's actually wrong, it will
> be detected at runtime.
>
OTOH, even if we want to verify at DDL time, we won't be able to
maintain it at the later point of time say if user changed the
parallel-safety of some function used in check constraint. I think the
function pg_get_parallel_safety() will help the user to decide whether
it can declare table parallel-safe. Now, it is quite possible that the
user can later change the parallel-safe property of some function then
that should be caught at runtime.
--
With Regards,
Amit Kapila.
Re: Parallel INSERT SELECT take 2
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
On Tue, Apr 27, 2021 at 7:39 AM houzj.fnst@fujitsu.com wrote: > > I'm thinking that when users say ALTER TABLE partioned_table SET PARALLEL > > TO 'safe';, we check all the partitions' and their associated objects' parallel > > safety? If all are parallel safe, then only we set partitioned_table as parallel safe. > > What should happen if the parallel safety of any of the associated > > objects/partitions changes after setting the partitioned_table safety? > > Currently, nothing happened if any of the associated objects/partitions changes after setting the partitioned_table safety. > Because , we do not have a really cheap way to catch the change. The existing relcache does not work because alter function > does not invalid the relcache which the function belongs to. And it will bring some other overhead(locking, systable scan,...) > to find the table the objects belong to. Makes sense. Anyways, the user is responsible for such changes and otherwise the executor can catch them at run time, if not, the users will see unintended consequences. > > My understanding was that: the command ALTER TABLE ... SET PARALLEL TO > > 'safe' work will check the parallel safety of all the objects associated with the > > table. If the objects are all parallel safe, then the table will be set to safe. If at > > least one object is parallel unsafe or restricted, then the command will fail. > > I think this idea makes sense. Some detail of the designed can be improved. > I agree with you that we can try to check check all the partitions' and their associated objects' parallel safety when ALTER PARALLEL. > Because it's a separate new command, add some overhead to it seems not too bad. > If there are no other objections, I plan to add safety check in the ALTER PARALLEL command. Maybe we can make the parallel safety check of the associated objects/partitions optional for CREATE/ALTER DDLs, with the default being no checks performed. Both Greg and Amit agree that we don't have to perform any parallel safety checks during CREATE/ALTER DDLs. > > also thinking that how will the design cope with situations such as the parallel > > safety of any of the associated objects changing after setting the table to > > parallel safe. The planner would have relied on the outdated parallel safety of > > the table and chosen parallel inserts and the executor will catch such situations. > > Looks like my understanding was wrong. > > Currently, we assume user is responsible for its correctness. > Because, from our research, when the parallel safety of some of these objects is changed, > it's costly to reflect it on the parallel safety of tables that depend on them. > (we need to scan the pg_depend,pg_inherit,pg_index.... to find the target table) Agree. With Regards, Bharath Rupireddy. EnterpriseDB: http://www.enterprisedb.com
Re: Parallel INSERT SELECT take 2
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
On Tue, Apr 27, 2021 at 7:45 AM Greg Nancarrow wrote:
>
> On Tue, Apr 27, 2021 at 10:51 AM Bharath Rupireddy
> wrote:
> >
> >
> > I still feel that why we shouldn't limit the declarative approach to
> > only partitioned tables? And for normal tables, possibly with a
> > minimal cost(??), the server can do the safety checking. I know this
> > feels a little inconsistent. In the planner we will have different
> > paths like: if (partitioned_table) { check the parallel safety tag
> > associated with the table } else { perform the parallel safety of the
> > associated objects }.
> >
>
> Personally I think the simplest and best approach is just do it
> consistently, using the declarative approach across all table types.
Agree.
> > Then, running the pg_get_parallel_safety will have some overhead if
> > there are many partitions associated with a table. And, this is the
> > overhead planner would have had to incur without the declarative
> > approach which we are trying to avoid with this design.
> >
>
> The big difference is that pg_get_parallel_safety() is intended to be
> used during development, not as part of runtime parallel-safety checks
> (which are avoided using the declarative approach).
> So there is no runtime overhead associated with pg_get_parallel_safety().
Yes, while we avoid runtime overhead, but we run the risk of changed
parallel safety of any of the underlying objects/functions/partitions.
This risk will anyways be unavoidable with declarative approach.
> > I'm thinking that when users say ALTER TABLE partioned_table SET
> > PARALLEL TO 'safe';, we check all the partitions' and their associated
> > objects' parallel safety? If all are parallel safe, then only we set
> > partitioned_table as parallel safe. What should happen if the parallel
> > safety of any of the associated objects/partitions changes after
> > setting the partitioned_table safety?
> >
>
> With the declarative approach, there is no parallel-safety checking on
> either the CREATE/ALTER when the parallel-safety is declared/set.
> It's up to the user to get it right. If it's actually wrong, it will
> be detected at runtime.
As I said upthread, we can provide the parallel safety check of
associated objects/partitions as an option with default as false. I'm
not sure if this is a good thing to do at all. Thoughts?
With Regards,
Bharath Rupireddy.
EnterpriseDB: http://www.enterprisedb.com
Re: Parallel INSERT SELECT take 2
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
On Tue, Apr 27, 2021 at 8:12 AM Amit Kapila wrote:
> On Tue, Apr 27, 2021 at 7:45 AM Greg Nancarrow wrote:
> >
> > On Tue, Apr 27, 2021 at 10:51 AM Bharath Rupireddy
> > wrote:
> > >
> > >
> > > I still feel that why we shouldn't limit the declarative approach to
> > > only partitioned tables? And for normal tables, possibly with a
> > > minimal cost(??), the server can do the safety checking. I know this
> > > feels a little inconsistent. In the planner we will have different
> > > paths like: if (partitioned_table) { check the parallel safety tag
> > > associated with the table } else { perform the parallel safety of the
> > > associated objects }.
> > >
> >
> > Personally I think the simplest and best approach is just do it
> > consistently, using the declarative approach across all table types.
> >
>
> Yeah, if we decide to go with a declarative approach then that sounds
> like a better approach.
Agree.
> > > Then, running the pg_get_parallel_safety will have some overhead if
> > > there are many partitions associated with a table. And, this is the
> > > overhead planner would have had to incur without the declarative
> > > approach which we are trying to avoid with this design.
> > >
> >
> > The big difference is that pg_get_parallel_safety() is intended to be
> > used during development, not as part of runtime parallel-safety checks
> > (which are avoided using the declarative approach).
> > So there is no runtime overhead associated with pg_get_parallel_safety().
> >
> > >
> > > I'm thinking that when users say ALTER TABLE partioned_table SET
> > > PARALLEL TO 'safe';, we check all the partitions' and their associated
> > > objects' parallel safety? If all are parallel safe, then only we set
> > > partitioned_table as parallel safe. What should happen if the parallel
> > > safety of any of the associated objects/partitions changes after
> > > setting the partitioned_table safety?
> > >
> >
> > With the declarative approach, there is no parallel-safety checking on
> > either the CREATE/ALTER when the parallel-safety is declared/set.
> > It's up to the user to get it right. If it's actually wrong, it will
> > be detected at runtime.
> >
>
> OTOH, even if we want to verify at DDL time, we won't be able to
> maintain it at the later point of time say if user changed the
> parallel-safety of some function used in check constraint. I think the
> function pg_get_parallel_safety() will help the user to decide whether
> it can declare table parallel-safe. Now, it is quite possible that the
> user can later change the parallel-safe property of some function then
> that should be caught at runtime.
Yeah, this is an unavoidable problem with the declarative approach.
With Regards,
Bharath Rupireddy.
EnterpriseDB: http://www.enterprisedb.com
RE: Parallel INSERT SELECT take 2
Hi, Attaching new version patches with the following change: 0002: 1): Change "ALTER/CREATE TABLE PARALLEL SAFE" to "ALTER/CREATE TABLE PARALLEL DML SAFE" 2): disallow temp/foreign table to be parallel safe. 0003: 1) Temporarily, add the check of built-in function by adding a member for proparallel in FmgrBuiltin. To avoid enlarging FmgrBuiltin struct , change the existing bool members strict and and retset into one member of type char, and represent the original values with some bit flags. Note: this will lock down the parallel property of built-in function, but, I think the parallel safety of built-in function is related to the C code, user should not change the property of it unless they change its code. So, I think it might be better to disallow changing parallel safety for built-in functions, Thoughts ? I have not added the parallel safety check in ALTER/CREATE table PARALLEL DML SAFE command. I think it seems better to add it after some more discussion. Best regards, houzj
Re: Parallel INSERT SELECT take 2
От:
Greg Nancarrow <gregn4422@gmail.com>
Дата:
On Wed, Apr 28, 2021 at 12:44 PM houzj.fnst@fujitsu.com
wrote:
>
> 0003:
> 1) Temporarily, add the check of built-in function by adding a member for proparallel in FmgrBuiltin.
> To avoid enlarging FmgrBuiltin struct , change the existing bool members strict and and retset into
> one member of type char, and represent the original values with some bit flags.
>
I was thinking that it would be better to replace the two bool members
with one "unsigned char" member for the bitflags for strict and
retset, and another "char" member for parallel.
The struct would still remain the same size as it originally was, and
you wouldn't need to convert between bit settings and char
('u'/'r'/'s') each time a built-in function was checked for
parallel-safety in fmgr_info().
> Note: this will lock down the parallel property of built-in function, but, I think the parallel safety of built-in function
> is related to the C code, user should not change the property of it unless they change its code. So, I think it might be
> better to disallow changing parallel safety for built-in functions, Thoughts ?
>
I'd vote for disallowing it (unless someone can justify why it
currently is allowed).
> I have not added the parallel safety check in ALTER/CREATE table PARALLEL DML SAFE command.
> I think it seems better to add it after some more discussion.
>
I'd vote for not adding such a check (as this is a declaration).
Some additional comments:
1) In patch 0002 comment, it says:
This property is recorded in pg_class's relparallel column as 'u', 'r', or 's',
just like pg_proc's proparallel. The default is UNSAFE.
It should say "relparalleldml" column.
2) With the patches applied, I seem to be getting a couple of errors
when running "make installcheck-world" with
force_parallel_mode=regress in effect.
Can you please try it?
Regards,
Greg Nancarrow
Fujitsu Australia
Re: Parallel INSERT SELECT take 2
От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Mon, Apr 12, 2021 at 6:52 AM tsunakawa.takay@fujitsu.com
wrote:
>
>
> SOLUTION TO (1)
> ========================================
>
> The candidate ideas are:
>
> 1) Caching the result of parallel-safety check
> The planner stores the result of checking parallel safety for each relation in relcache, or some purpose-built hash table in shared memory.
>
> The problems are:
>
> * Even if the target relation turns out to be parallel safe by looking at those data structures, we cannot assume it remains true until the SQL statement finishes. For instance, other sessions might add a parallel-unsafe index to its descendant relations. Other examples include that when the user changes the parallel safety of indexes or triggers by running ALTER FUNCTION on the underlying index AM function or trigger function, the relcache entry of the table or index is not invalidated, so the correct parallel safety is not maintained in the cache.
> In that case, when the executor encounters a parallel-unsafe object, it can change the cached state as being parallel-unsafe and error out.
>
> * Can't ensure fast access. With relcache, the first access in each session has to undergo the overhead of parallel-safety check. With a hash table in shared memory, the number of relations stored there would be limited, so the first access after database startup or the hash table entry eviction similarly experiences slowness.
>
> * With a new hash table, some lwlock for concurrent access must be added, which can have an adverse effect on performance.
>
>
> 2) Enabling users to declare that the table allows parallel data modification
> Add a table property that represents parallel safety of the table for DML statement execution. Users specify it as follows:
>
> CREATE TABLE table_name (...) PARALLEL { UNSAFE | RESTRICTED | SAFE };
> ALTER TABLE table_name PARALLEL { UNSAFE | RESTRICTED | SAFE };
>
> This property is recorded in pg_class's relparallel column as 'u', 'r', or 's', just like pg_proc's proparallel. The default is UNSAFE.
>
So, in short, if we need to go with any sort of solution with caching,
we can't avoid
(a) locking all the partitions
(b) getting an error while execution because at a later point user has
altered the parallel-safe property of a relation.
We can't avoid locking all the partitions because while we are
executing the statement, the user can change the parallel-safety for
one of the partitions by changing a particular partition and if we
didn't have a lock on that partition, it will lead to an error during
execution. Now, here, one option could be that we document this point
and then don't take lock on any of the partitions except for root
table. So, the design would be simpler, that we either cache the
parallel-safe in relcache or shared hash table and just lock the
parent table and perform all parallel-safety checks for the first
time.
I think if we want to go with the behavior that we will error out
during statement execution if any parallel-safe property is changed at
run-time, it is better to go with the declarative approach. In the
declarative approach, at least the user will be responsible for taking
any such decision and the chances of toggling the parallel-safe
property will be less. To aid users, as suggested, we can provide a
function to determine parallel-safety of relation for DML operations.
Now, in the declarative approach, we can either go with whatever the
user has mentioned or we can do some checks during DDL to determine
the actual parallel-safety. I think even if try to determine
parallel-safety during DDL it will be quite tricky in some cases, like
when a user performs Alter Function to change parallel-safety of the
function used in some constraint for the table or if the user changes
parallel-safety of one of the partition then we need to traverse the
partition hierarchy upwards which doesn't seem advisable. So, I guess
it is better to go with whatever the user has mentioned but if you or
others feel we can have some sort of parallel-safety checks during DDL
as well.
> The planner assumes that all of the table, its descendant partitions, and their ancillary objects have the specified parallel safety or safer one. The user is responsible for its correctness. If the parallel processes find an object that is less safer than the assumed parallel safety during statement execution, it throws an ERROR and abort the statement execution.
>
> The objects that relate to the parallel safety of a DML target table are as follows:
>
> * Column default expression
> * DOMAIN type CHECK expression
> * CHECK constraints on column
> * Partition key
> * Partition key support function
> * Index expression
> * Index predicate
> * Index AM function
> * Operator function
> * Trigger function
>
> When the parallel safety of some of these objects is changed, it's costly to reflect it on the parallel safety of tables that depend on them. So, we don't do it. Instead, we provide a utility function pg_get_parallel_safety('table_name') that returns records of (objid, classid, parallel_safety) that represent the parallel safety of objects that determine the parallel safety of the specified table. The function only outputs objects that are not parallel safe.
>
So, users need to check count(*) for this to determine
parallel-safety? How about if we provide a wrapper function on top of
this function or a separate function that returns char to indicate
whether it is safe, unsafe, or restricted to perform a DML operation
on the table?
> How does the executor detect parallel unsafe objects? There are two ways:
>
> 1) At loading time
> When the executor loads the definition of objects (tables, constraints, index, triggers, etc.) during the first access to them after session start or their eviction by sinval message, it checks the parallel safety.
>
> This is a legitimate way, but may need much code. Also, it might overlook necessary code changes without careful inspection.
>
If we want to go with a declarative approach, then I think we should
try to do this because it will be almost free in some cases and we can
detect error early. For example, when we decide to insert in a
partition that is declared unsafe whereas the root (partitioned) table
is declared safe.
--
With Regards,
Amit Kapila.
Re: Parallel INSERT SELECT take 2
От:
Dilip Kumar <dilipbalaut@gmail.com>
Дата:
On Mon, May 10, 2021 at 11:21 AM Amit Kapila wrote:
>
> Now, in the declarative approach, we can either go with whatever the
> user has mentioned or we can do some checks during DDL to determine
> the actual parallel-safety. I think even if try to determine
> parallel-safety during DDL it will be quite tricky in some cases, like
> when a user performs Alter Function to change parallel-safety of the
> function used in some constraint for the table or if the user changes
> parallel-safety of one of the partition then we need to traverse the
> partition hierarchy upwards which doesn't seem advisable. So, I guess
> it is better to go with whatever the user has mentioned but if you or
> others feel we can have some sort of parallel-safety checks during DDL
> as well.
IMHO, it makes sense to go with what the user has declared to avoid
complexity. And, I don't see any problem with that.
> > The planner assumes that all of the table, its descendant partitions, and their ancillary objects have the specified parallel safety or safer one. The user is responsible for its correctness. If the parallel processes find an object that is less safer than the assumed parallel safety during statement execution, it throws an ERROR and abort the statement execution.
> >
> > The objects that relate to the parallel safety of a DML target table are as follows:
> >
> > * Column default expression
> > * DOMAIN type CHECK expression
> > * CHECK constraints on column
> > * Partition key
> > * Partition key support function
> > * Index expression
> > * Index predicate
> > * Index AM function
> > * Operator function
> > * Trigger function
> >
> > When the parallel safety of some of these objects is changed, it's costly to reflect it on the parallel safety of tables that depend on them. So, we don't do it. Instead, we provide a utility function pg_get_parallel_safety('table_name') that returns records of (objid, classid, parallel_safety) that represent the parallel safety of objects that determine the parallel safety of the specified table. The function only outputs objects that are not parallel safe.
> >
>
> So, users need to check count(*) for this to determine
> parallel-safety? How about if we provide a wrapper function on top of
> this function or a separate function that returns char to indicate
> whether it is safe, unsafe, or restricted to perform a DML operation
> on the table?
Such wrapper function make sense.
--
Regards,
Dilip Kumar
EnterpriseDB: http://www.enterprisedb.com
RE: Parallel INSERT SELECT take 2
От:
"houzj.fnst@fujitsu.com" <houzj.fnst@fujitsu.com>
Дата:
> > > When the parallel safety of some of these objects is changed, it's costly to
> reflect it on the parallel safety of tables that depend on them. So, we don't do
> it. Instead, we provide a utility function pg_get_parallel_safety('table_name')
> that returns records of (objid, classid, parallel_safety) that represent the
> parallel safety of objects that determine the parallel safety of the specified
> table. The function only outputs objects that are not parallel safe.
> > >
> >
> > So, users need to check count(*) for this to determine
> > parallel-safety? How about if we provide a wrapper function on top of
> > this function or a separate function that returns char to indicate
> > whether it is safe, unsafe, or restricted to perform a DML operation
> > on the table?
>
> Such wrapper function make sense.
Thanks for the suggestion, and I agree.
I will add another wrapper function and post new version patches soon.
Best regards,
houzj
RE: Parallel INSERT SELECT take 2
> > > So, users need to check count(*) for this to determine
> > > parallel-safety? How about if we provide a wrapper function on top
> > > of this function or a separate function that returns char to
> > > indicate whether it is safe, unsafe, or restricted to perform a DML
> > > operation on the table?
> >
> > Such wrapper function make sense.
>
> Thanks for the suggestion, and I agree.
> I will add another wrapper function and post new version patches soon.
Attaching new version patches with the following changes:
0001
Add a new function pg_get_max_parallel_hazard('table_name') returns char('s', 'u', 'r')
which indicate whether it is safe, unsafe, or restricted to perform a DML.
0003
Temporarily, I removed the safety check for function in the executor.
Because we are trying to post the safety check as a separate patch which
can help detect parallel unsafe function in parallel mode, and the approach
is still in discussion[1].
Comments and suggestions are welcome either in that thread[1] or here.
[1] https://www.postgresql.org/message-id/OS0PR01MB571646637784DAF1DD4C8BE994539%40OS0PR01MB5716.jpnprd01.prod.outlook.com
Best regards,
houzj
Re: Parallel INSERT SELECT take 2
От:
Bharath Rupireddy <bharath.rupireddyforpostgres@gmail.com>
Дата:
On Tue, May 11, 2021 at 6:11 PM houzj.fnst@fujitsu.com
wrote:
>
> > > > So, users need to check count(*) for this to determine
> > > > parallel-safety? How about if we provide a wrapper function on top
> > > > of this function or a separate function that returns char to
> > > > indicate whether it is safe, unsafe, or restricted to perform a DML
> > > > operation on the table?
> > >
> > > Such wrapper function make sense.
> >
> > Thanks for the suggestion, and I agree.
> > I will add another wrapper function and post new version patches soon.
>
> Attaching new version patches with the following changes:
>
> 0001
> Add a new function pg_get_max_parallel_hazard('table_name') returns char('s', 'u', 'r')
> which indicate whether it is safe, unsafe, or restricted to perform a DML.
Thanks for the patches. I think we should have the table name as
regclass type for pg_get_max_parallel_hazard? See, pg_relation_size,
pg_table_size, pg_filenode_relation and so on.
With Regards,
Bharath Rupireddy.
EnterpriseDB: http://www.enterprisedb.com
Re: Parallel INSERT SELECT take 2
От:
Greg Nancarrow <gregn4422@gmail.com>
Дата:
On Tue, May 11, 2021 at 10:41 PM houzj.fnst@fujitsu.com
wrote:
>
> Attaching new version patches with the following changes:
>
> 0001
> Add a new function pg_get_max_parallel_hazard('table_name') returns char('s', 'u', 'r')
> which indicate whether it is safe, unsafe, or restricted to perform a DML.
>
Currently the 1st patch actually also contains the changes for the
Parallel-SELECT-for-INSERT functionality. This is not obvious.
So I think this should be split out into a separate patch (i.e. the
minor planner update and related planner comment changes,
is_parallel_allowed_for_modify() function, max_parallel_hazard()
update, XID changes).
Also, the regression tests' "serial_schedule" file has been removed
since you posted the v3-POC patches, so you need to remove updates for
that from your 3rd patch.
How about reorganisation of the patches like the following?
0001: CREATE ALTER TABLE PARALLEL DML
0002: parallel-SELECT-for-INSERT (planner changes,
max_parallel_hazard() update, XID changes)
0003: pg_get_parallel_safety()
0004: regression test updates
Regards,
Greg Nancarrow
Fujitsu Australia
RE: Parallel INSERT SELECT take 2
> > Currently the 1st patch actually also contains the changes for the > Parallel-SELECT-for-INSERT functionality. This is not obvious. > So I think this should be split out into a separate patch (i.e. the minor planner > update and related planner comment changes, > is_parallel_allowed_for_modify() function, max_parallel_hazard() update, XID > changes). > Also, the regression tests' "serial_schedule" file has been removed since you > posted the v3-POC patches, so you need to remove updates for that from your > 3rd patch. Thanks for the comments, I have posted new version patches with this change. > How about reorganisation of the patches like the following? > 0001: CREATE ALTER TABLE PARALLEL DML > 0002: parallel-SELECT-for-INSERT (planner changes, > max_parallel_hazard() update, XID changes) > 0003: pg_get_parallel_safety() > 0004: regression test updates Thanks, it looks good and I reorganized the latest patchset in this way. Attaching new version patches with the following change. 0003 Change functions arg type to regclass. 0004 remove updates for "serial_schedule". Best regards, houzj
RE: Parallel INSERT SELECT take 2
От:
"houzj.fnst@fujitsu.com" <houzj.fnst@fujitsu.com>
Дата:
> > > > > So, users need to check count(*) for this to determine
> > > > > parallel-safety? How about if we provide a wrapper function on
> > > > > top of this function or a separate function that returns char to
> > > > > indicate whether it is safe, unsafe, or restricted to perform a
> > > > > DML operation on the table?
> > > >
> > > > Such wrapper function make sense.
> > >
> > > Thanks for the suggestion, and I agree.
> > > I will add another wrapper function and post new version patches soon.
> >
> > Attaching new version patches with the following changes:
> >
> > 0001
> > Add a new function pg_get_max_parallel_hazard('table_name') returns
> > char('s', 'u', 'r') which indicate whether it is safe, unsafe, or restricted to
> perform a DML.
>
> Thanks for the patches. I think we should have the table name as regclass type
> for pg_get_max_parallel_hazard? See, pg_relation_size, pg_table_size,
> pg_filenode_relation and so on.
Thanks for the comment.
I have changed the type to regclass in the latest patchset.
Best regards,
houzj
Re: Parallel INSERT SELECT take 2
От:
Greg Nancarrow <gregn4422@gmail.com>
Дата:
On Fri, May 14, 2021 at 6:24 PM houzj.fnst@fujitsu.com
wrote:
>
> Thanks for the comments, I have posted new version patches with this change.
>
> > How about reorganisation of the patches like the following?
> > 0001: CREATE ALTER TABLE PARALLEL DML
> > 0002: parallel-SELECT-for-INSERT (planner changes,
> > max_parallel_hazard() update, XID changes)
> > 0003: pg_get_parallel_safety()
> > 0004: regression test updates
>
> Thanks, it looks good and I reorganized the latest patchset in this way.
>
> Attaching new version patches with the following change.
>
> 0003
> Change functions arg type to regclass.
>
> 0004
> remove updates for "serial_schedule".
>
I've got some comments for the V4 set of patches:
(0001)
(i) Patch comment needs a little updating (suggested change is below):
Enable users to declare a table's parallel data-modification safety
(SAFE/RESTRICTED/UNSAFE).
Add a table property that represents parallel safety of a table for
DML statement execution.
It may be specified as follows:
CREATE TABLE table_name PARALLEL DML { UNSAFE | RESTRICTED | SAFE };
ALTER TABLE table_name PARALLEL DML { UNSAFE | RESTRICTED | SAFE };
This property is recorded in pg_class's relparallel column as 'u',
'r', or 's', just like pg_proc's proparallel.
The default is UNSAFE.
The planner assumes that all of the table, its descendant partitions,
and their ancillary objects have,
at worst, the specified parallel safety. The user is responsible for
its correctness.
---
NOTE: The following sentence was removed from the original V4 0001
patch comment (since this version of the patch is not doing runtime
parallel-safety checks on functions):.
If the parallel processes
find an object that is less safer than the assumed parallel safety during
statement execution, it throws an ERROR and abort the statement execution.
(ii) Update message to say "a foreign ...":
BEFORE:
+ errmsg("cannot support parallel data modification on foreign or
temporary table")));
AFTER:
+ errmsg("cannot support parallel data modification on a foreign or
temporary table")));
(iii) strVal() macro already casts to "Value *", so the cast can be
removed from the following:
+ char *parallel = strVal((Value *) def);
(0003)
(i) Suggested updates to the patch comment:
Provide a utility function "pg_get_parallel_safety(regclass)" that
returns records of
(objid, classid, parallel_safety) for all parallel unsafe/restricted
table-related objects
from which the table's parallel DML safety is determined. The user can
use this information
during development in order to accurately declare a table's parallel
DML safety. or to
identify any problematic objects if a parallel DML fails or behaves
unexpectedly.
When the use of an index-related parallel unsafe/restricted function
is detected, both the
function oid and the index oid are returned.
Provide a utility function "pg_get_max_parallel_hazard(regclass)" that
returns the worst
parallel DML safety hazard that can be found in the given relation.
Users can use this
function to do a quick check without caring about specific
parallel-related objects.
Regards,
Greg Nancarrow
Fujitsu Australia
RE: Parallel INSERT SELECT take 2
From: Greg Nancarrow
Sent: Wednesday, May 19, 2021 7:55 PM
>
> On Fri, May 14, 2021 at 6:24 PM houzj.fnst@fujitsu.com
> wrote:
> >
> > Thanks for the comments, I have posted new version patches with this
> change.
> >
> > > How about reorganisation of the patches like the following?
> > > 0001: CREATE ALTER TABLE PARALLEL DML
> > > 0002: parallel-SELECT-for-INSERT (planner changes,
> > > max_parallel_hazard() update, XID changes)
> > > 0003: pg_get_parallel_safety()
> > > 0004: regression test updates
> >
> > Thanks, it looks good and I reorganized the latest patchset in this way.
> >
> > Attaching new version patches with the following change.
> >
> > 0003
> > Change functions arg type to regclass.
> >
> > 0004
> > remove updates for "serial_schedule".
> >
>
> I've got some comments for the V4 set of patches:
>
> (0001)
>
> (i) Patch comment needs a little updating (suggested change is below):
>
> Enable users to declare a table's parallel data-modification safety
> (SAFE/RESTRICTED/UNSAFE).
>
> Add a table property that represents parallel safety of a table for
> DML statement execution.
> It may be specified as follows:
>
> CREATE TABLE table_name PARALLEL DML { UNSAFE | RESTRICTED | SAFE };
> ALTER TABLE table_name PARALLEL DML { UNSAFE | RESTRICTED | SAFE };
>
> This property is recorded in pg_class's relparallel column as 'u',
> 'r', or 's', just like pg_proc's proparallel.
> The default is UNSAFE.
>
> The planner assumes that all of the table, its descendant partitions,
> and their ancillary objects have,
> at worst, the specified parallel safety. The user is responsible for
> its correctness.
>
> ---
>
> NOTE: The following sentence was removed from the original V4 0001
> patch comment (since this version of the patch is not doing runtime
> parallel-safety checks on functions):.
>
> If the parallel processes
> find an object that is less safer than the assumed parallel safety during
> statement execution, it throws an ERROR and abort the statement execution.
>
>
> (ii) Update message to say "a foreign ...":
>
> BEFORE:
> + errmsg("cannot support parallel data modification on foreign or
> temporary table")));
>
> AFTER:
> + errmsg("cannot support parallel data modification on a foreign or
> temporary table")));
>
>
> (iii) strVal() macro already casts to "Value *", so the cast can be
> removed from the following:
>
> + char *parallel = strVal((Value *) def);
>
>
> (0003)
>
> (i) Suggested updates to the patch comment:
>
> Provide a utility function "pg_get_parallel_safety(regclass)" that
> returns records of
> (objid, classid, parallel_safety) for all parallel unsafe/restricted
> table-related objects
> from which the table's parallel DML safety is determined. The user can
> use this information
> during development in order to accurately declare a table's parallel
> DML safety. or to
> identify any problematic objects if a parallel DML fails or behaves
> unexpectedly.
>
> When the use of an index-related parallel unsafe/restricted function
> is detected, both the
> function oid and the index oid are returned.
>
> Provide a utility function "pg_get_max_parallel_hazard(regclass)" that
> returns the worst
> parallel DML safety hazard that can be found in the given relation.
> Users can use this
> function to do a quick check without caring about specific
> parallel-related objects.
Thanks for the comments and your descriptions looks good.
Attaching v5 patchset with all these changes.
Best regards,
houzj
Re: Parallel INSERT SELECT take 2
От:
Greg Nancarrow <gregn4422@gmail.com>
Дата:
On Mon, May 24, 2021 at 3:15 PM houzj.fnst@fujitsu.com
wrote:
>
>
> Thanks for the comments and your descriptions looks good.
> Attaching v5 patchset with all these changes.
>
A few other minor things I noticed:
(1) error message wording when declaring a table SAFE for parallel DML
src/backend/commands/tablecmds.c
Since data modification for the RELKIND_FOREIGN_TABLE and
RELPERSISTENCE_TEMP types are allowed in the parallel-restricted case
(i.e. leader may modify in parallel mode)
I'm thinking it may be better to use wording like:
"cannot support foreign or temporary table data modification by
parallel workers"
instead of
"cannot support parallel data modification on a foreign or temporary table"
There are TWO places where this error message is used.
(What do you think?)
(2) Minor formatting issue
src/backend/optimizer/util/clauses.c
static safety_object *make_safety_object(Oid objid, Oid classid,
char proparallel)
should be:
static safety_object *
make_safety_object(Oid objid, Oid classid, char proparallel)
(3) Minor formatting issue
src/backend/utils/cache/typcache.c
List *GetDomainConstraints(Oid type_id)
should be:
List *
GetDomainConstraints(Oid type_id)
Regards,
Greg Nancarrow
Fujitsu Australia
RE: Parallel INSERT SELECT take 2
From: Greg Nancarrow Sent: Friday, May 28, 2021 4:42 PM > On Mon, May 24, 2021 at 3:15 PM houzj.fnst@fujitsu.com > wrote: > > > > > > Thanks for the comments and your descriptions looks good. > > Attaching v5 patchset with all these changes. > > > > A few other minor things I noticed: > > (1) error message wording when declaring a table SAFE for parallel DML > > src/backend/commands/tablecmds.c > > Since data modification for the RELKIND_FOREIGN_TABLE and > RELPERSISTENCE_TEMP types are allowed in the parallel-restricted case (i.e. > leader may modify in parallel mode) I'm thinking it may be better to use > wording like: > > "cannot support foreign or temporary table data modification by parallel > workers" > > instead of > > "cannot support parallel data modification on a foreign or temporary table" > > There are TWO places where this error message is used. > > (What do you think?) I think your change looks good. I used your msg in the latest patchset. > (2) Minor formatting issue > > src/backend/optimizer/util/clauses.c > > static safety_object *make_safety_object(Oid objid, Oid classid, char > proparallel) > > should be: > > static safety_object * > make_safety_object(Oid objid, Oid classid, char proparallel) Changed. > (3) Minor formatting issue > > src/backend/utils/cache/typcache.c > > > List *GetDomainConstraints(Oid type_id) > > should be: > > List * > GetDomainConstraints(Oid type_id) Changed. Attaching v6 patchset. And I registered it in CF https://commitfest.postgresql.org/33/3143/, comments are welcome. Best regards, houzj
Re: Parallel INSERT SELECT take 2
От:
Greg Nancarrow <gregn4422@gmail.com>
Дата:
On Mon, May 31, 2021 at 3:34 PM houzj.fnst@fujitsu.com
wrote:
>
>
> Attaching v6 patchset.
> And I registered it in CF https://commitfest.postgresql.org/33/3143/,
> comments are welcome.
>
The latest patchset has some documentation updates. I'd like to
suggest a couple of documentation tweaks (this is mainly just minor
word changes and some extra details):
(1)
doc/src/sgml/ref/create_foreign_table.sgml
doc/src/sgml/ref/create_table.sgml
PARALLEL DML UNSAFE indicates that the data in the table can't be
modified in parallel mode, and this forces a serial execution plan for
DML statements operating on the table. This is the default. PARALLEL
DML RESTRICTED indicates that the data in the table can be modified in
parallel mode, but the modification is restricted to the parallel
group leader. PARALLEL DML SAFE indicates that the data in the table
can be modified in parallel mode without restriction. Note that
PostgreSQL currently does not support data modification by parallel
workers.
Tables should be labeled parallel dml unsafe/restricted if any
parallel unsafe/restricted function could be executed when modifying
the data in the table (e.g., functions in triggers/index
expressions/constraints etc.).
To assist in correctly labeling the parallel DML safety level of a
table, PostgreSQL provides some utility functions that may be used
during application development. Refer to pg_get_parallel_safety() and
pg_get_max_parallel_hazard() for more information.
(2) doc/src/sgml/func.sgml
(i) pg_get_parallel_safety
Returns a row containing enough information to uniquely identify the
parallel unsafe/restricted table-related objects from which the
table's parallel DML safety is determined. The user can use this
information during development in order to accurately declare a
table's parallel DML safety, or to identify any problematic objects if
parallel DML fails or behaves unexpectedly. Note that when the use of
an object-related parallel unsafe/restricted function is detected,
both the function OID and the object OID are returned. classid is the
OID of the system catalog containing the object; objid is the OID of
the object itself.
(ii) pg_get_max_parallel_hazard
Returns the worst parallel DML safety hazard that can be found in the
given relation:
s safe
r restricted
u unsafe
Users can use this function to do a quick check without caring about
specific parallel-related objects.
---
Also, shouldn't support for "Parallel" be added for table output in
PSQL? (e.g. \dt+)
Regards,
Greg Nancarrow
Fujitsu Australia
RE: Parallel INSERT SELECT take 2
From: Greg Nancarrow > On Mon, May 31, 2021 at 3:34 PM houzj.fnst@fujitsu.com > wrote: > > > > > > Attaching v6 patchset. > > And I registered it in CF https://commitfest.postgresql.org/33/3143/, > > comments are welcome. > > > > The latest patchset has some documentation updates. I'd like to suggest a > couple of documentation tweaks (this is mainly just minor word changes and > some extra details): > > (1) > doc/src/sgml/ref/create_foreign_table.sgml > doc/src/sgml/ref/create_table.sgml > > PARALLEL DML UNSAFE indicates that the data in the table can't be modified in > parallel mode, and this forces a serial execution plan for DML statements > operating on the table. This is the default. PARALLEL DML RESTRICTED > indicates that the data in the table can be modified in parallel mode, but the > modification is restricted to the parallel group leader. PARALLEL DML SAFE > indicates that the data in the table can be modified in parallel mode without > restriction. Note that PostgreSQL currently does not support data > modification by parallel workers. > > Tables should be labeled parallel dml unsafe/restricted if any parallel > unsafe/restricted function could be executed when modifying the data in the > table (e.g., functions in triggers/index expressions/constraints etc.). > > To assist in correctly labeling the parallel DML safety level of a table, > PostgreSQL provides some utility functions that may be used during > application development. Refer to pg_get_parallel_safety() and > pg_get_max_parallel_hazard() for more information. > > > (2) doc/src/sgml/func.sgml > > (i) pg_get_parallel_safety > Returns a row containing enough information to uniquely identify the parallel > unsafe/restricted table-related objects from which the table's parallel DML > safety is determined. The user can use this information during development in > order to accurately declare a table's parallel DML safety, or to identify any > problematic objects if parallel DML fails or behaves unexpectedly. Note that > when the use of an object-related parallel unsafe/restricted function is > detected, both the function OID and the object OID are returned. classid is the > OID of the system catalog containing the object; objid is the OID of the object > itself. > > (ii) pg_get_max_parallel_hazard > Returns the worst parallel DML safety hazard that can be found in the given > relation: > s safe > r restricted > u unsafe > Users can use this function to do a quick check without caring about specific > parallel-related objects. Thanks for looking into the doc change, I think your change looks better and have merged it in the attached patch. > Also, shouldn't support for "Parallel" be added for table output in PSQL? (e.g. > \dt+) Yeah, I think we should add it and I added it in the attached 0001 patch. Best regards, houzj
RE: Parallel INSERT SELECT take 2
From: houzj.fnst@fujitsu.com > Thanks for looking into the doc change, I think your change looks better and > have merged it in the attached patch. > > > Also, shouldn't support for "Parallel" be added for table output in PSQL? (e.g. > > \dt+) > > Yeah, I think we should add it and I added it in the attached 0001 patch. Oops, forgot to update the regression test in contrib/. Attaching new version patchset with this fix. Best regards, houzj
RE: Parallel INSERT SELECT take 2
Hi, When testing the patch, I found some issues in the 0003,0004 patch. Attaching new version patchset which fix these issues. 0003 * don't check parallel safety of partition's default column expression. * rename some function/variable names to be consistent with existing code. * remove some unused function parameters. * fix a max_hazard overwrite issue. * add some code comments and adjust some code forms. 0004 * Remove some unrelated comments in the regression test. * add the 'begin;', 'rollback;' in insert_parallel.sql. Best regards, houzj
RE: Parallel INSERT SELECT take 2
From: houzj.fnst@fujitsu.com > Hi, > > When testing the patch, I found some issues in the 0003,0004 patch. > Attaching new version patchset which fix these issues. > > 0003 > * don't check parallel safety of partition's default column expression. > * rename some function/variable names to be consistent with existing code. > * remove some unused function parameters. > * fix a max_hazard overwrite issue. > * add some code comments and adjust some code forms. > > 0004 > * Remove some unrelated comments in the regression test. > * add the 'begin;', 'rollback;' in insert_parallel.sql. Through further review and thanks for greg-san's suggestions, I attached a new version patchset with some minor change in 0001,0003 and 0004. 0001. * fix a typo in variable name. * add a TODO in patch comment about updating the version number when branch PG15. 0003 * fix a 'git apply white space' warning. * Remove some unnecessary if condition. * add some code comments above the safety check function. * Fix some typo. 0004 * add a testcase to test ALTER PARALLEL DML UNSAFE/RESTRICTED. Best regards, houzj
Re: Parallel INSERT SELECT take 2
От:
Greg Nancarrow <gregn4422@gmail.com>
Дата:
On Thu, Jun 10, 2021 at 11:26 AM houzj.fnst@fujitsu.com wrote: > > Through further review and thanks for greg-san's suggestions, > I attached a new version patchset with some minor change in 0001,0003 and 0004. > > 0001. > * fix a typo in variable name. > * add a TODO in patch comment about updating the version number when branch PG15. > > 0003 > * fix a 'git apply white space' warning. > * Remove some unnecessary if condition. > * add some code comments above the safety check function. > * Fix some typo. > > 0004 > * add a testcase to test ALTER PARALLEL DML UNSAFE/RESTRICTED. > Thanks, those updates addressed most of what I was going to comment on for the v9 patches. Some additional comments on the v10 patches: (1) I noticed some functions in the 0003 patch have no function header: make_safety_object parallel_hazard_walker target_rel_all_parallel_hazard_recurse (2) I found the "recurse_partition" parameter of the target_rel_all_parallel_hazard_recurse() function a bit confusing, because the function recursively checks partitions without looking at that flag. How about naming it "is_partition"? (3) The names of the utility functions don't convey that they operate on tables. How about: pg_get_parallel_safety() -> pg_get_table_parallel_safety() pg_get_max_parallel_hazard() -> pg_get_table_max_parallel_hazard() or pg_get_rel_xxxxx()? What do you think? (4) I think that some of the tests need parallel dml settings to match their expected output: (i) +-- Test INSERT with underlying query - and RETURNING (no projection) +-- (should create a parallel plan; parallel SELECT) -> but creates a serial plan (so needs to set parallel dml safe, so a parallel plan is created) (ii) +-- Parallel INSERT with unsafe column default, should not use a parallel plan +-- +alter table testdef parallel dml safe; -> should set "unsafe" not "safe" (iii) +-- Parallel INSERT with restricted column default, should use parallel SELECT +-- +explain (costs off) insert into testdef(a,b,d) select a,a*2,a*8 from test_data; -> should use "alter table testdef parallel dml restricted;" before the explain (iv) +-- +-- Parallel INSERT with restricted and unsafe column defaults, should not use a parallel plan +-- +explain (costs off) insert into testdef(a,d) select a,a*8 from test_data; -> should use "alter table testdef parallel dml unsafe;" before the explain Regards, Greg Nancarrow Fujitsu Australia
RE: Parallel INSERT SELECT take 2
On Thursday, June 10, 2021 1:39 PM Greg Nancarrow wrote: > On Thu, Jun 10, 2021 at 11:26 AM houzj.fnst@fujitsu.com > wrote: > > > > Through further review and thanks for greg-san's suggestions, I > > attached a new version patchset with some minor change in 0001,0003 and > 0004. > > > > 0001. > > * fix a typo in variable name. > > * add a TODO in patch comment about updating the version number when > branch PG15. > > > > 0003 > > * fix a 'git apply white space' warning. > > * Remove some unnecessary if condition. > > * add some code comments above the safety check function. > > * Fix some typo. > > > > 0004 > > * add a testcase to test ALTER PARALLEL DML UNSAFE/RESTRICTED. > > > > Thanks, those updates addressed most of what I was going to comment on > for the v9 patches. > > Some additional comments on the v10 patches: > > (1) I noticed some functions in the 0003 patch have no function header: > > make_safety_object > parallel_hazard_walker > target_rel_all_parallel_hazard_recurse Thanks, added. > (2) I found the "recurse_partition" parameter of the > target_rel_all_parallel_hazard_recurse() function a bit confusing, because the > function recursively checks partitions without looking at that flag. How about > naming it "is_partition"? Yeah, it looks better. Changed. > (3) The names of the utility functions don't convey that they operate on tables. > > How about: > > pg_get_parallel_safety() -> pg_get_table_parallel_safety() > pg_get_max_parallel_hazard() -> pg_get_table_max_parallel_hazard() > > or pg_get_rel_xxxxx()? > > What do you think? I changed it like the following: pg_get_parallel_safety -> pg_get_table_parallel_dml_safety pg_get_max_parallel_hazard -> pg_get_table_max_parallel_dml_hazard > (4) I think that some of the tests need parallel dml settings to match their > expected output: > > (i) > +-- Test INSERT with underlying query - and RETURNING (no projection) > +-- (should create a parallel plan; parallel SELECT) > > -> but creates a serial plan (so needs to set parallel dml safe, so a > parallel plan is created) Changed. > (ii) > +-- Parallel INSERT with unsafe column default, should not use a > +parallel plan > +-- > +alter table testdef parallel dml safe; > > -> should set "unsafe" not "safe" I thought the testcase about table 'testdef' is to test if the planner is able to check whether it has parallel unsafe or restricted column default expression, because column default expression will be merged into select part in planner. So, It seems we don't need to change the table's parallel safety for these cases ? > (iii) > +-- Parallel INSERT with restricted column default, should use parallel > +SELECT > +-- > +explain (costs off) insert into testdef(a,b,d) select a,a*2,a*8 from > +test_data; > > -> should use "alter table testdef parallel dml restricted;" before the > -> explain > > (iv) > +-- > +-- Parallel INSERT with restricted and unsafe column defaults, should > not use a parallel plan > +-- > +explain (costs off) insert into testdef(a,d) select a,a*8 from > +test_data; > > -> should use "alter table testdef parallel dml unsafe;" before the > -> explain I addressed most of the comments and rebased the patch. Besides, I changed the following things: * I removed the safety check for index-am function as discussed[1]. * change version 140000 to 150000 Attach new version patchset for further review. [1] https://www.postgresql.org/message-id/164474.1623652853%40sss.pgh.pa.us Best regards, houzj
RE: Parallel INSERT SELECT take 2
On Tuesday, July 6, 2021 11:42 AM houzj.fnst@fujitsu.com wrote: > > I addressed most of the comments and rebased the patch. > Besides, I changed the following things: > * I removed the safety check for index-am function as discussed[1]. > * change version 140000 to 150000 > > Attach new version patchset for further review. > > [1] > https://www.postgresql.org/message-id/164474.1623652853%40sss.pgh.pa.us Attach a rebased patchset which fix some compile warnings and errors due to recent commit 2ed532. Best regards, Hou zhijie
RE: Parallel INSERT SELECT take 2
On Monday, July 12, 2021 4:01 PM wrote: > Attach a rebased patchset which fix some compile warnings and errors due to > recent commit 2ed532. Attach rebased patches. Best regards Houzj
Re: Parallel INSERT SELECT take 2
От:
Greg Nancarrow <gregn4422@gmail.com>
Дата:
On Tue, Jul 20, 2021 at 11:47 AM houzj.fnst@fujitsu.com wrote: > > Attach rebased patches. > Just letting you know that CRLFs are in the patch comments for the 0001 and 0003 patches. (It doesn't affect patch application) Regards, Greg Nancarrow Fujitsu Australia
Re: Parallel INSERT SELECT take 2
On Tue, Jul 20, 2021 at 11:47 AM houzj.fnst@fujitsu.com wrote: > > > Attach rebased patches. > There's a failure in the "triggers" tests and the cfbot is not happy. Attaching an updated set of patches with a minor update to the expected test results to fix this. Also removed some CRLFs in some of the patch comments. No other changes. Regards, Greg Nancarrow Fujitsu Australia
RE: Parallel INSERT SELECT take 2
От:
"houzj.fnst@fujitsu.com" <houzj.fnst@fujitsu.com>
Дата:
Hi, Based on the discussion in another thread[1], we plan to change the design like the following: allow users to specify a parallel-safety option for both partitioned and non-partitioned relations but for non-partitioned relations if users didn't specify, it would be computed automatically? If the user has specified parallel-safety option for non-partitioned relation then we would consider that instead of computing the value by ourselves. In this approach, it will be more convenient for users to use and get the benefit of parallel select for insert. Since most of the technical discussion happened in another thread, I posted the new version patch including the new design to that thread[2]. Comments are also welcome in that thread. [1] https://www.postgresql.org/message-id/CAA4eK1%2BMQnm6RkqooHA7R-y7riRa84qsh5j3FZDScw71m_n4OA%40mail.gmail.com [2] https://www.postgresql.org/message-id/OS0PR01MB5716DB1E3F723F86314D080094F09%40OS0PR01MB5716.jpnprd01.prod.outlook.com Best regards, houzj
Re: Parallel INSERT SELECT take 2
От:
"Joel Jacobson" <joel@compiler.org>
Дата:
On Sun, May 17, 2026, at 13:24, Tomas Vondra wrote: > On 5/11/26 13:44, Tomas Vondra wrote: >>>>>> alternative idea We noticed some overlap of problems between this thread and [1], and decided to split out our fix into a separate fix, which is 0001 in our patch set. It could possibly be a solution to some of the problem scenarios you're working on in this thread, hence this email. For convenience, below is the git show --stat of the 0001 patch. --- Serialize routine definition changes with dependency recording Dependency recording now locks referenced objects before inserting pg_depend rows. Routine definition changes also need to participate in that object-lock protocol, because stored expressions can depend on function properties such as volatility, strictness, or SQL-body contents. Take AccessExclusiveLock on the pg_proc object before CREATE OR REPLACE FUNCTION updates an existing routine, and before ALTER FUNCTION changes routine properties. After waiting, refetch the pg_proc tuple and repeat the ownership and object-kind checks, because the routine could have been dropped or reassigned while we waited. Authors: Andreas Karlsson, Joel Jacobson, Arne Roland src/backend/catalog/pg_proc.c | 22 ++++++++++++++++++++++ src/backend/commands/functioncmds.c | 29 +++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) --- Since you're discussing alternative ideas, we thought we should throw this into the discussion. -- -- master (21298c2) -- joel@Mac postgresql % psql regression_dep_probe psql (19devel) Type "help" for help. regression_dep_probe=# CREATE SCHEMA dep_probe; CREATE SCHEMA regression_dep_probe=# CREATE FUNCTION dep_probe.f_lock_probe(integer) RETURNS integer regression_dep_probe-# LANGUAGE sql IMMUTABLE PARALLEL SAFE AS $$ SELECT $1 $$; CREATE FUNCTION regression_dep_probe=# regression_dep_probe=# CREATE TABLE dep_probe.t_lock_probe(a integer); CREATE TABLE regression_dep_probe=# -- session 1 regression_dep_probe=# BEGIN; BEGIN regression_dep_probe=*# CREATE INDEX t_lock_probe_expr_idx regression_dep_probe-*# ON dep_probe.t_lock_probe ((dep_probe.f_lock_probe(a))); CREATE INDEX regression_dep_probe=*# SELECT pg_sleep(8); pg_sleep ---------- (1 row) regression_dep_probe=*# COMMIT; COMMIT regression_dep_probe=# joel@mac postgresql % psql regression_dep_probe psql (19devel) Type "help" for help. regression_dep_probe=# -- session 2, while session 1 is open regression_dep_probe=# SET lock_timeout = '1s'; SET regression_dep_probe=# ALTER FUNCTION dep_probe.f_lock_probe(integer) PARALLEL UNSAFE; ALTER FUNCTION regression_dep_probe=# -- -- patch 0001: Serialize routine definition changes with dependency recording -- joel@Mac postgresql % psql regression_dep_probe psql (19devel) Type "help" for help. regression_dep_probe=# CREATE SCHEMA dep_probe; CREATE SCHEMA regression_dep_probe=# CREATE FUNCTION dep_probe.f_lock_probe(integer) RETURNS integer regression_dep_probe-# LANGUAGE sql IMMUTABLE PARALLEL SAFE AS $$ SELECT $1 $$; CREATE FUNCTION regression_dep_probe=# regression_dep_probe=# CREATE TABLE dep_probe.t_lock_probe(a integer); CREATE TABLE regression_dep_probe=# -- session 1 regression_dep_probe=# BEGIN; BEGIN regression_dep_probe=*# CREATE INDEX t_lock_probe_expr_idx regression_dep_probe-*# ON dep_probe.t_lock_probe ((dep_probe.f_lock_probe(a))); CREATE INDEX regression_dep_probe=*# SELECT pg_sleep(8); pg_sleep ---------- (1 row) regression_dep_probe=*# COMMIT; COMMIT regression_dep_probe=# joel@mac postgresql % psql regression_dep_probe psql (19devel) Type "help" for help. regression_dep_probe=# -- session 2, while session 1 is open regression_dep_probe=# SET lock_timeout = '1s'; SET regression_dep_probe=# ALTER FUNCTION dep_probe.f_lock_probe(integer) PARALLEL UNSAFE; ERROR: canceling statement due to lock timeout CONTEXT: waiting for AccessExclusiveLock on object 16387 of class 1255 of database 16385 regression_dep_probe=# /Joel [1] https://www.postgresql.org/message-id/flat/f7f02669-652d-4bbb-bc29-cccdb63c2233%40app.fastmail.com#0bcaf856172453d536f1fd9b6afa7a2f
RE: Parallel INSERT SELECT take 2
On Monday, May 11, 2026 7:44 PM Tomas Vondra wrote: > On 5/11/26 09:21, Zhijie Hou (Fujitsu) wrote: > > On Saturday, May 9, 2026 5:29 PM Tomas Vondra > wrote: > >> ... > > After searching my memory and reviewing the old discussion, I recall > > another locking-related issue... > > > > For example, consider creating a new table that uses a function in an > > index expression (or altering a table to add a new expression or > > function). If a user tries to alter the function used in that > > expression concurrently, the ALTER FUNCTION command cannot see the > newly created table because it hasn't been committed yet. > > As a result, we cannot ensure that pg_class.parallel_safety is updated > > in a concurrency-safe manner. The cause is that we don't hold a lock > > on the function when creating or altering a table. > ... > > Yes, problems like this may be tricky. > > But I don't see a problem with requiring an exclusive lock on a function when > changing the parallel safety for a function (and updating the pg_class attribute > for all relations that use it). Yes, it's not great, it'd be nice to do it with weaker > locks, but if we can't ... sorry. Per an off-list discussion, I'm sharing an alternative approach for consideration. The basic idea is to cache parallel safety in the relcache and invalidate the cached value whenever: a parallel-safety-relevant object (e.g., trigger, index, constraint) is added to or dropped from a table, or a function's parallel-safety flag is altered. This approach essentially follows the design from the earlier thread [1], but remove the parlalel safety declaration and extends it slightly by also attempting to compute safety for partitioned tables. The detailed design is as follows: Modifying a table while in parallel mode is only safe if none of the objects attached to the table involves parallel-unsafe or parallel-restricted functions: triggers, index expressions and predicates, CHECK constraints, column default expressions, and the partition key. For a partitioned table, each partition is checked recursively as well. Checking all of that for every query is expensive, so cache the result in the relation's relcache entry: rd_paralleldml holds the worst hazard level found (one of the PROPARALLEL_xxx values), or zero if it has not been computed yet. The new RelationGetParallelDmlSafety() function computes the value on first use and returns the cached value thereafter. The cached value is invalidated whenever a function's parallel-safety flag is altered, or whenever a parallel-safety-relevant object is added to or dropped from the table or, for a partitioned table, from any of its partitions. When a function's parallel safety changes, we invalidate the cached parallel-safety flag in all relcache entries, rather than introducing heavier locking or reverse-engineering the set of tables that reference the function. Function-safety changes are expected to be rare, so this broad invalidation should be acceptable. Because we do not lock the function while altering its safety, a race is possible: the safety flag could change after another backend has already used the cached value to build its plan. This is no worse than current HEAD behavior, since a function has always been free to be altered without blocking concurrent DML. When a partition's parallel safety changes, we invalidate the cached values of all its ancestors in the partition tree. We deliberately do not take locks on the ancestors: this avoids introducing new deadlock risk, and it avoids changing locking behavior in a way that would make commands suddenly block normal DML that previously ran unimpeded - a change that might be hard for users to reason about. Find the ancestors without locking is safe because a partition cannot be concurrently attached or detached - both ATTACH PARTITION and DETACH PARTITION lock the child tables during DDL execution. The only remaining race is that an unsafe object could be added to a partition while a parallel INSERT ... SELECT is already executing; in that case, execution detects the hazard and raises an ERROR before inserting into that partition. This rare, detectable execution-time error is the trade-off for keeping the locking scheme simple. Because the cached value lives in relcache, every new session must recompute it on first use. This is true of all relcache data, but it is slightly more costly here since the safety computation can be noticeable for tables with many partitions. A possible future improvement is a fixed-size shared hash table storing parallel-safety values, so that only the first session to touch a table pays the computation cost while later sessions can reuse the result. Just share this approach for discussing, if this approach and the old approach[1] both turn out to be unacceptable, we could switch to Tomas's approach of materialize the SELECT result. The attachment implements this approach for reference. To provide context for the old approach for comparison, here is a brief overview of how it works. It is a hybrid approach: we allow the user to explicitly specify the parallel safety of a table via a new DDL command, ALTER TABLE ... PARALLEL SAFETY. If the user does not specify it, the behavior depends on the table type: for non-partitioned tables, we automatically compute the safety and cache it in relcache; for partitioned tables, we default to disallowing parallel SELECT. To enable parallel INSERT ... SELECT on a partitioned table, the user must set the safety manually. When executing ALTER TABLE ... PARALLEL SAFETY, we validate whether the table actually matches the specified safety level and raise an ERROR if it does not. [1] https://www.postgresql.org/message-id/OS0PR01MB5716DB1E3F723F86314D080094F09%40OS0PR01MB5716.jpnprd01.prod.outlook.com Best Regards, Zhijie Hou
Re: Parallel INSERT SELECT take 2
On 8/4/26 05:45, Zhijie Hou (Fujitsu) wrote: > On Monday, May 11, 2026 7:44 PM Tomas Vondra wrote: >> On 5/11/26 09:21, Zhijie Hou (Fujitsu) wrote: >>> On Saturday, May 9, 2026 5:29 PM Tomas Vondra >> wrote: >>>> ... >>> After searching my memory and reviewing the old discussion, I recall >>> another locking-related issue... >>> >>> For example, consider creating a new table that uses a function in an >>> index expression (or altering a table to add a new expression or >>> function). If a user tries to alter the function used in that >>> expression concurrently, the ALTER FUNCTION command cannot see the >> newly created table because it hasn't been committed yet. >>> As a result, we cannot ensure that pg_class.parallel_safety is updated >>> in a concurrency-safe manner. The cause is that we don't hold a lock >>> on the function when creating or altering a table. >> ... >> >> Yes, problems like this may be tricky. >> >> But I don't see a problem with requiring an exclusive lock on a function when >> changing the parallel safety for a function (and updating the pg_class attribute >> for all relations that use it). Yes, it's not great, it'd be nice to do it with weaker >> locks, but if we can't ... sorry. > > Per an off-list discussion, I'm sharing an alternative approach for > consideration. The basic idea is to cache parallel safety in the relcache and > invalidate the cached value whenever: a parallel-safety-relevant object (e.g., > trigger, index, constraint) is added to or dropped from a table, or a function's > parallel-safety flag is altered. This approach essentially follows the design > from the earlier thread [1], but remove the parlalel safety declaration and > extends it slightly by also attempting to compute safety for partitioned tables. > Thanks for the patch. > The detailed design is as follows: > > Modifying a table while in parallel mode is only safe if none of the objects > attached to the table involves parallel-unsafe or parallel-restricted functions: > triggers, index expressions and predicates, CHECK constraints, column default > expressions, and the partition key. For a partitioned table, each partition is > checked recursively as well. > Is this aiming to allow the insert to be parallel too, or just the select part? If only the select part is parallel, wouldn't it be OK to have parallel-restricted expressions? > Checking all of that for every query is expensive, so cache the result in the > relation's relcache entry: rd_paralleldml holds the worst hazard level found > (one of the PROPARALLEL_xxx values), or zero if it has not been computed yet. > The new RelationGetParallelDmlSafety() function computes the value on first use > and returns the cached value thereafter. > > The cached value is invalidated whenever a function's parallel-safety flag is > altered, or whenever a parallel-safety-relevant object is added to or dropped > from the table or, for a partitioned table, from any of its partitions. > OK > When a function's parallel safety changes, we invalidate the cached > parallel-safety flag in all relcache entries, rather than introducing heavier > locking or reverse-engineering the set of tables that reference the function. > Function-safety changes are expected to be rare, so this broad invalidation > should be acceptable. > OK, as you say, it should be a rare event. And it only resets the flag, keeping the rest of the relcache data. > Because we do not lock the function while altering its safety, a race is > possible: the safety flag could change after another backend has already used > the cached value to build its plan. This is no worse than current HEAD behavior, > since a function has always been free to be altered without blocking concurrent > DML. > So the user can execute a long-running DML, and while it's running someone could alter all kinds of function parameters, including the parallel safety. But the DML will keep running. I guess that's probably OK, or rather not a new issue. The next execution should use the correct "new" value, right? Or could it happen that we miss an invalidation? Let's say we start building the relcache entry, when a function gets altered. Could it happen that we end up with a "stale" value of the flag in relcache until the end of the session? > When a partition's parallel safety changes, we invalidate the cached values of > all its ancestors in the partition tree. We deliberately do not take locks on > the ancestors: this avoids introducing new deadlock risk, and it avoids changing > locking behavior in a way that would make commands suddenly block normal DML > that previously ran unimpeded - a change that might be hard for users to reason > about. Find the ancestors without locking is safe because a partition cannot be > concurrently attached or detached - both ATTACH PARTITION and DETACH PARTITION > lock the child tables during DDL execution. The only remaining race is that an > unsafe object could be added to a partition while a parallel INSERT ... SELECT > is already executing; in that case, execution detects the hazard and raises an > ERROR before inserting into that partition. This rare, detectable execution-time > error is the trade-off for keeping the locking scheme simple. > Hmm, OK. We need to document this argument somewhere (maybe it's in a comment already, not sure). Would it be possible to have a TAP test (with injection points?) / isolation test for this? > Because the cached value lives in relcache, every new session must recompute it > on first use. This is true of all relcache data, but it is slightly more costly > here since the safety computation can be noticeable for tables with many > partitions. A possible future improvement is a fixed-size shared hash table > storing parallel-safety values, so that only the first session to touch a table > pays the computation cost while later sessions can reuse the result. > This is my main concern - that we'll have to do this (possibly fairly expensive) check, even for short inserts that can't possibly benefit from parallelism. What's the worst case impact? Say I have a workload that runs small inserts into a partitioned table, each in a new connection. How expensive would that be? (I agree opening a new connection for each insert seems silly, it's merely a synthetic worst-case scenario.) > Just share this approach for discussing, if this approach and the old > approach[1] both turn out to be unacceptable, we could switch to Tomas's > approach of materialize the SELECT result. The attachment implements this > approach for reference. > +1 to using the spilling approach as a fall back, in case this turns out not to work. I wonder if we might want to do both. The spilling approach does not even need to check the parallel safety - it can parallelize even cases where the insert has parallel unsafe expressions, etc. I wonder how many cases would benefit from that. > To provide context for the old approach for comparison, here is a brief overview > of how it works. It is a hybrid approach: we allow the user to explicitly > specify the parallel safety of a table via a new DDL command, ALTER TABLE ... > PARALLEL SAFETY. If the user does not specify it, the behavior depends on the > table type: for non-partitioned tables, we automatically compute the safety and > cache it in relcache; for partitioned tables, we default to disallowing parallel > SELECT. To enable parallel INSERT ... SELECT on a partitioned table, the user > must set the safety manually. When executing ALTER TABLE ... PARALLEL SAFETY, we > validate whether the table actually matches the specified safety level and raise > an ERROR if it does not. > FWIW I agree we really don't want to require users to specify parallel safety for tables - doing that manually would be very tedious, error prone (how would the user even know with tables to modify?). Unlike for functions, the database is able that for tables. My main question is whether it's OK to store that just in the relcache, and why it's safer/better than actually keeping it in pg_class. I mean, we could reset that just like the relcache, the first session would update it with the fresh value, etc. regards -- Tomas Vondra
Re: Parallel INSERT SELECT take 2
I've spent a bit more time looking at the patches, and I have three
issues to report - two seem fairly simple, more like omissions. The
third one may be a more fundamental issue.
1) GENERATED STORED columns not checked - those are evaluated ad insert
time, just like triggers, so I think we need to check them too. I assume
this is mostly just an oversight, because GENERATED STORED columns are a
new feature, introduced after the original patch was written.
2) set_attnotnull has this new block of code:
/*
* The parallel DML safety hazard levels cached in relcache for the
* parent's ancestors, if any, were computed including the detached
* partition, so they must be invalidated as well. (The parent's own
* cached value is already discarded by the relcache invalidation above,
* so no message is needed for it.)
*/
CacheInvalidateParallelDmlSafetyForAncestors(RelationGetRelid(rel));
But why? I don't think changing 'NOT NULL' can alter parallel safety.
Maybe the block belongs somewhere else, and just got lost during a
rebase, or something like that? It actually mentions detaching the
partition, so maybe that's where it should be? But AFAIK that path
already invalidates the flag in DetachPartitionFinalize.
3) The more fundamental issue is that we can easily end up with stale
value of the flag in relcache, if we get an invalidation while already
calculating the flag.
I speculated there may be such issues in my earlier message, but now I
have an isolation test reproducing the issue - written with a bit of
help from AI, but I believe the issue is legit.
The root cause is that when RelationGetParallelDmlSafety() calculates
the hazard (and walks partitions, indexes etc), it locks them. But
locking a relation accepts invalidation messages. So this can happen:
- something triggers an invalidation of rd_paralleldml
- we start recalculating it, and the correct result is 's'
- half-way through, another ALTER TABLE makes it parallel unsafe, but
it's on one of the objects (partitions, ...) we already processed
- we accept the invalidation, but that just resets rd_paralleldml
- RelationGetParallelDmlSafety finishes, updates rd_paralleldml, but it
sets it to the *stale* value, because it did not recheck the modified
objects (from the second invalidation)
I think this might be fixed by having a separate "isvalid" flag, reset
by the invalidation, and repeat RelationGetParallelDmlSafety until it
stays 'true'. So something like this in pseudocode:
invalidation:
rd_paralleldml_isvalid = false
RelationGetParallelDmlSafety:
while (!rd_paralleldml_isvalid)
{
rd_paralleldml_isvalid = true;
... recalculate the rd_paralleldml ...
}
return rd_paralleldml;
Speaking of this, isn't it a bit weird that ExecInitPartitionInfo now
checks RelationGetParallelDmlSafety at runtime? AFAIK it can cause
failures in already-running DML, and it's the only place doing this. Why
should it not just trust the rd_paralleldml value in relcache when
planning the query?
regards
--
Tomas Vondra
RE: Parallel INSERT SELECT take 2
On Friday, August 7, 2026 2:01 AM Tomas Vondra wrote: > On 8/4/26 05:45, Zhijie Hou (Fujitsu) wrote: > > On Monday, May 11, 2026 7:44 PM Tomas Vondra > wrote: > > Thanks for the patch. > > > The detailed design is as follows: Thanks for checking. > > > > Modifying a table while in parallel mode is only safe if none of the > > objects attached to the table involves parallel-unsafe or parallel-restricted > functions: > > triggers, index expressions and predicates, CHECK constraints, column > > default expressions, and the partition key. For a partitioned table, > > each partition is checked recursively as well. > > > > Is this aiming to allow the insert to be parallel too, or just the select part? If > only the select part is parallel, wouldn't it be OK to have parallel-restricted > expressions? Sorry for the typo. The current patch only supports parallel SELECT for INSERT, so parallel-restricted is fine. > > Because we do not lock the function while altering its safety, a race > > is > > possible: the safety flag could change after another backend has > > already used the cached value to build its plan. This is no worse than > > current HEAD behavior, since a function has always been free to be > > altered without blocking concurrent DML. > > > So the user can execute a long-running DML, and while it's running someone > could alter all kinds of function parameters, including the parallel safety. But > the DML will keep running. > > I guess that's probably OK, or rather not a new issue. > > The next execution should use the correct "new" value, right? Or could it > happen that we miss an invalidation? Let's say we start building the relcache > entry, when a function gets altered. Could it happen that we end up with a > "stale" value of the flag in relcache until the end of the session? The v1 patch has a bug that could cause stale value, but I think after fixing in v2, this won't happen anymore. > > > When a partition's parallel safety changes, we invalidate the cached > > values of all its ancestors in the partition tree. We deliberately do > > not take locks on the ancestors: this avoids introducing new deadlock > > risk, and it avoids changing locking behavior in a way that would make > > commands suddenly block normal DML that previously ran unimpeded - a > > change that might be hard for users to reason about. Find the > > ancestors without locking is safe because a partition cannot be > > concurrently attached or detached - both ATTACH PARTITION and DETACH > > PARTITION lock the child tables during DDL execution. The only > > remaining race is that an unsafe object could be added to a partition > > while a parallel INSERT ... SELECT is already executing; in that case, > > execution detects the hazard and raises an ERROR before inserting into that > partition. This rare, detectable execution-time error is the trade-off for > keeping the locking scheme simple. > > > > Hmm, OK. We need to document this argument somewhere (maybe it's in a > comment already, not sure). Would it be possible to have a TAP test (with > injection points?) / isolation test for this? Yes, I added this in the doc and have tests in 0003 patch. > > > Because the cached value lives in relcache, every new session must > > recompute it on first use. This is true of all relcache data, but it > > is slightly more costly here since the safety computation can be > > noticeable for tables with many partitions. A possible future > > improvement is a fixed-size shared hash table storing parallel-safety > > values, so that only the first session to touch a table pays the computation > cost while later sessions can reuse the result. > > > > This is my main concern - that we'll have to do this (possibly fairly > expensive) check, even for short inserts that can't possibly benefit from > parallelism. What's the worst case impact? Say I have a workload that runs > small inserts into a partitioned table, each in a new connection. How > expensive would that be? > > (I agree opening a new connection for each insert seems silly, it's merely a > synthetic worst-case scenario.) I ran some quick tests to measure planning time for INSERT into a partitioned table: - 100 partitions ~5ms - 1000 partitions ~50ms - 10000 partitions ~500ms Test environment: Intel(R) Xeon(R) CPU E5-2690 v4 @ 2.60GHz, 56 CPUs, 200GB RAM I agree that in the worst case, for large number of partitions, this could increase planning time for short INSERT statements without using the cached value, and can be optimized if we avoid opening new connection for each insert select. > > > Just share this approach for discussing, if this approach and the old > > approach[1] both turn out to be unacceptable, we could switch to > > Tomas's approach of materialize the SELECT result. The attachment > > implements this approach for reference. > > > > +1 to using the spilling approach as a fall back, in case this turns out > not to work. > > I wonder if we might want to do both. The spilling approach does not even > need to check the parallel safety - it can parallelize even cases where the > insert has parallel unsafe expressions, etc. I wonder how many cases would > benefit from that. It sounds reasonable to have both approaches, such as forcing the spilling approach if the table is parallel unsafe. Since functions like nextval (which can be used in column default expressions) are parallel unsafe, the spilling mode could help improve performance in such cases. > > > To provide context for the old approach for comparison, here is a > > brief overview of how it works. It is a hybrid approach: we allow the > > user to explicitly specify the parallel safety of a table via a new DDL > command, ALTER TABLE ... > > PARALLEL SAFETY. If the user does not specify it, the behavior depends > > on the table type: for non-partitioned tables, we automatically > > compute the safety and cache it in relcache; for partitioned tables, > > we default to disallowing parallel SELECT. To enable parallel INSERT > > ... SELECT on a partitioned table, the user must set the safety > > manually. When executing ALTER TABLE ... PARALLEL SAFETY, we validate > > whether the table actually matches the specified safety level and raise an > ERROR if it does not. > > > > FWIW I agree we really don't want to require users to specify parallel safety > for tables - doing that manually would be very tedious, error prone (how > would the user even know with tables to modify?). Unlike for functions, the > database is able that for tables. > > My main question is whether it's OK to store that just in the relcache, and why > it's safer/better than actually keeping it in pg_class. I mean, we could reset > that just like the relcache, the first session would update it with the fresh > value, etc. I thought about this a bit, but I'm not sure the same mechanism can be used to maintain a catalog column. If we follow the same approach, ALTER FUNCTION PARALLEL SAFETY would need to update every table record in pg_class. I think that wouldn't be safe because we couldn't catch all tables due to visibility issues - for example, if another table is being created concurrently, ALTER FUNCTION won't see it and thus won't reset the safety for it. (To solve this, we need to tackle another more general issue: we take no lock on the functions used in a table, or when altering a function.) Apart from this issue, updating a pg_class row would generate a full relcache invalidation, which seems to broaden the scope of impact. If we let INSERT SELECT compute safety and update it to pg_class, other sessions cannot see the updated safety until the first session commits, and concurrent updates from multiple sessions would require locking to ensure concurrency safety. For these reasons, handling this in the relcache feels more simple to me. Best Regards, Zhijie Hou