pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
Introducing find_all_inheritors_ordered()
10+ messages / 5 participants
[nested] [flat]

* Introducing find_all_inheritors_ordered()
@ 2026-07-30 08:35  Chao Li <li.evan.chao@gmail.com>
  0 siblings, 2 replies; 10+ messages in thread

From: Chao Li @ 2026-07-30 08:35 UTC (permalink / raw)
  To: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; +Cc: Andrew Dunstan <andrew@dunslane.net>; jian he <jian.universality@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; Álvaro Herrera <alvherre@kurilemu.de>

Hi,

This is follow-up work to patch [1], which fixed a bug when altering a CHECK constraint's enforceability. The fix was not very elegant. It had to use upward recursion to traverse all ancestors when deciding a child table's enforceability. This was because the existing function find_all_inheritors() returns a list of descendants without ensuring that parents precede their children.

This patch introduces a new function, find_all_inheritors_ordered(), which guarantees that every ancestor in the returned list appears before its descendants. With this new function, the original fix in commit 0cd17fdd3c0 is significantly simplified. The function could also potentially benefit other features that need to traverse inheritance trees in parent-before-child order.

This patch also strengthens an existing test by adding another level of inheritance. My first version of the implementation failed with the following case:
```
Root ———————————————> child
     \                                                       /
      \ ——————> a —————> b /
```
(The diagram might not display well. Basically, “child" has parents “b" and “root", “b" has parent “a”, “a” has parent “root")

The current version uses Kahn's topological sorting algorithm, which handles this case correctly. Please see the attached patch for details.

[1] https://postgr.es/m/E74C57FA-1DD0-4C8E-8FB1-538034752592@gmail.com

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/

Attachments:

v1-0001-Add-find_all_inheritors_ordered.patch (application/octet-stream, 16.3K) download From cd328fe399d5c322dfab0d52eac8280c0b1e1068 Mon Sep 17 00:00:00 2001 From: "Chao Li (Evan)" <lic@highgo.com> Date: Thu, 30 Jul 2026 16:03:49 +0800 Subject: [PATCH v1] Add find_all_inheritors_ordered() Add an inheritance traversal that guarantees every ancestor appears before its descendants. find_all_inheritors() does not provide this ordering when multiple inheritance creates both direct and indirect paths to a relation. Use Kahn's topological sorting algorithm to produce the ordered list without recursion. Use the new function to simplify the inherited CHECK constraint enforceability handling committed by 0cd17fdd3c0. Since parents are processed before their children, checking the current state of a child's direct parents is sufficient. Extend the direct-plus-indirect inheritance test with another intermediate level. Author: Chao Li <lic@highgo.com> --- src/backend/catalog/pg_inherits.c | 128 ++++++++++++++++++++++++++ src/backend/commands/tablecmds.c | 110 +++++----------------- src/include/catalog/pg_inherits.h | 1 + src/test/regress/expected/inherit.out | 9 +- src/test/regress/sql/inherit.sql | 3 +- 5 files changed, 159 insertions(+), 92 deletions(-) diff --git a/src/backend/catalog/pg_inherits.c b/src/backend/catalog/pg_inherits.c index 4b9802aafcc..db38ddf9466 100644 --- a/src/backend/catalog/pg_inherits.c +++ b/src/backend/catalog/pg_inherits.c @@ -29,6 +29,7 @@ #include "utils/builtins.h" #include "utils/fmgroids.h" #include "utils/hsearch.h" +#include "utils/memutils.h" #include "utils/snapmgr.h" #include "utils/syscache.h" @@ -41,6 +42,16 @@ typedef struct SeenRelsEntry int list_index; /* its position in output list(s) */ } SeenRelsEntry; +/* + * Entry of a hash table used in find_all_inheritors_ordered. + */ +typedef struct OrderedSeenRelsEntry +{ + Oid rel_id; + List *children; + int indegree; +} OrderedSeenRelsEntry; + /* * find_inheritance_children * @@ -335,6 +346,123 @@ find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents) return rels_list; } +/* + * find_all_inheritors_ordered - + * Same as find_all_inheritors(), except that an ancestor is always listed + * before its descendants. + * + * The ordering is produced using Kahn's topological sorting algorithm. + */ +List * +find_all_inheritors_ordered(Oid parentrelId, LOCKMODE lockmode) +{ + MemoryContext temp_context; + MemoryContext old_context; + HTAB *seen_rels; + HASHCTL ctl; + List *agenda; + List *worklist = NIL; + List *ordered = NIL; + List *result = NIL; + ListCell *lc; + OrderedSeenRelsEntry *node; + bool found; + + /* Use a temporary memory context to simplify cleanup */ + temp_context = AllocSetContextCreate(CurrentMemoryContext, + "find_all_inheritors_ordered", + ALLOCSET_SMALL_SIZES); + old_context = MemoryContextSwitchTo(temp_context); + + ctl.keysize = sizeof(Oid); + ctl.entrysize = sizeof(OrderedSeenRelsEntry); + ctl.hcxt = temp_context; + + seen_rels = hash_create("find_all_inheritors_ordered temporary table", + 32, /* start small and extend */ + &ctl, + HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); + + node = hash_search(seen_rels, &parentrelId, HASH_ENTER, &found); + Assert(!found); + node->children = NIL; + node->indegree = 0; + + /* + * Use the agenda to find every descendant and record every inheritance + * edge. The indegree is the number of direct parents within this + * inheritance graph. + */ + agenda = list_make1_oid(parentrelId); + foreach(lc, agenda) + { + Oid current_oid = lfirst_oid(lc); + List *children; + OrderedSeenRelsEntry *current; + + current = hash_search(seen_rels, &current_oid, HASH_FIND, NULL); + Assert(current != NULL); + + children = find_inheritance_children(current_oid, lockmode); + foreach_oid(child_oid, children) + { + node = hash_search(seen_rels, &child_oid, HASH_ENTER, &found); + if (!found) + { + node->children = NIL; + node->indegree = 0; + agenda = lappend_oid(agenda, child_oid); + } + + current->children = lappend_oid(current->children, child_oid); + node->indegree++; + } + list_free(children); + } + + /* + * Emit nodes in topological order. A node enters the worklist only after + * all of its direct parents have been emitted. + */ + foreach_oid(rel_oid, agenda) + { + node = hash_search(seen_rels, &rel_oid, HASH_FIND, NULL); + Assert(node != NULL); + if (node->indegree == 0) + worklist = lappend_oid(worklist, rel_oid); + } + + /* + * Move nodes from the worklist to the output list, and add their children + * to the worklist when all of their parents have been emitted. + */ + foreach_oid(rel_oid, worklist) + { + node = hash_search(seen_rels, &rel_oid, HASH_FIND, NULL); + Assert(node != NULL); + ordered = lappend_oid(ordered, rel_oid); + + foreach_oid(child_oid, node->children) + { + OrderedSeenRelsEntry *child; + + child = hash_search(seen_rels, &child_oid, HASH_FIND, NULL); + Assert(child != NULL); + Assert(child->indegree > 0); + if (--child->indegree == 0) + worklist = lappend_oid(worklist, child_oid); + } + } + + Assert(list_length(ordered) == list_length(agenda)); + + MemoryContextSwitchTo(old_context); + result = list_copy(ordered); + MemoryContextDelete(temp_context); + + return result; +} + /* * has_subclass - does this relation have any children? diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index 6d4c457b820..2aa5724dcae 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -437,7 +437,6 @@ static bool ATExecAlterFKConstrEnforceability(List **wqueue, ATAlterConstraint * static bool ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, HeapTuple contuple, bool recurse, bool recursing, - List *changing_conids, LOCKMODE lockmode); static bool ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, Relation tgrel, Relation rel, @@ -460,7 +459,6 @@ static void AlterFKConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint static void AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, Oid conrelid, bool recurse, bool recursing, - List *changing_conids, LOCKMODE lockmode); static void AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, Relation tgrel, Relation rel, @@ -470,7 +468,6 @@ static void AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation HeapTuple contuple); static bool ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel, HeapTuple contuple, - List *changing_conids, Oid *enforced_parentoid); static ObjectAddress ATExecValidateConstraint(List **wqueue, Relation rel, char *constrName, @@ -12529,7 +12526,7 @@ ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon, else if (currcon->contype == CONSTRAINT_CHECK) changed = ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel, contuple, recurse, false, - NIL, lockmode); + lockmode); } else if (cmdcon->alterDeferrability && ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, rel, @@ -12717,7 +12714,6 @@ static bool ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, HeapTuple contuple, bool recurse, bool recursing, - List *changing_conids, LOCKMODE lockmode) { Form_pg_constraint currcon; @@ -12759,7 +12755,6 @@ ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, if (!cmdcon->is_enforced && (!recursing || !rel->rd_rel->relispartition) && ATCheckCheckConstrHasEnforcedParent(conrel, rel, contuple, - changing_conids, &enforced_parentoid)) { if (!recursing) @@ -12786,6 +12781,14 @@ ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, updatecon.is_enforced = target_enforced; AlterConstrUpdateConstraintEntry(&updatecon, conrel, contuple); changed = true; + + /* + * A later descendant must see this change when checking its direct + * parents. The ordered inheritance traversal guarantees that all + * affected parents are processed before their children. + */ + if (!cmdcon->is_enforced) + CommandCounterIncrement(); } /* @@ -12806,55 +12809,20 @@ ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, */ if (!recursing && !currcon->connoinherit) { - Assert(changing_conids == NIL); - - children = find_all_inheritors(RelationGetRelid(rel), - lockmode, NULL); + children = find_all_inheritors_ordered(RelationGetRelid(rel), + lockmode); /* - * When setting NOT ENFORCED, build the set of equivalent CHECK - * constraints that this command will attempt to change before - * visiting descendants. The root itself has already been checked - * above. + * If we are told not to recurse, there had better not be any + * child tables, because we can't change constraint enforceability + * on the parent unless we have changed enforceability for all + * children. */ - if (!cmdcon->is_enforced) - changing_conids = list_make1_oid(currcon->oid); - - foreach_oid(childoid, children) - { - if (childoid == RelationGetRelid(rel)) - continue; - - /* - * If we are told not to recurse, there had better not be any - * child tables, because we can't change constraint - * enforceability on the parent unless we have changed - * enforceability for all child. - */ - if (!recurse) - ereport(ERROR, - errcode(ERRCODE_INVALID_TABLE_DEFINITION), - errmsg("constraint must be altered on child tables too"), - errhint("Do not specify the ONLY keyword.")); - - /* - * It is sufficient to look up the constraint by name here. - * Supported DDL ensures that inheritable CHECK constraints - * with the same name have equivalent definitions when they - * are propagated to children or when inheritance is - * established. All descendants returned by - * find_all_inheritors must have this constraint: inherited - * CHECK constraints propagate to all children at - * inheritance-link creation time and cannot be dropped - * independently on child tables. - */ - if (!cmdcon->is_enforced) - changing_conids = - list_append_unique_oid(changing_conids, - get_relation_constraint_oid(childoid, - cmdcon->conname, - false)); - } + if (!recurse && list_length(children) > 1) + ereport(ERROR, + errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("constraint must be altered on child tables too"), + errhint("Do not specify the ONLY keyword.")); } foreach_oid(childoid, children) @@ -12864,7 +12832,6 @@ ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, AlterCheckConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, childoid, false, true, - changing_conids, lockmode); } } @@ -12916,7 +12883,6 @@ static void AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, Oid conrelid, bool recurse, bool recursing, - List *changing_conids, LOCKMODE lockmode) { SysScanDesc pscan; @@ -12946,21 +12912,18 @@ AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon, cmdcon->conname, get_rel_name(conrelid))); ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel, childtup, - recurse, recursing, changing_conids, - lockmode); + recurse, recursing, lockmode); systable_endscan(pscan); } /* * When setting an inherited CHECK constraint to NOT ENFORCED, look for a - * matching parent constraint that remains ENFORCED and is not part of the same - * ALTER. + * matching parent constraint that remains ENFORCED. */ static bool ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel, HeapTuple contuple, - List *changing_conids, Oid *enforced_parentoid) { Form_pg_constraint currcon; @@ -12990,7 +12953,6 @@ ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel, while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan))) { Oid parentoid; - Relation parentrel = NULL; SysScanDesc pscan; ScanKeyData pkey[3]; HeapTuple parenttup; @@ -13034,41 +12996,13 @@ ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel, RelationGetRelationName(rel), NameStr(parentcon->conname)); - /* - * A parent listed in changing_conids is being changed by the same - * ALTER, but it may not have been updated yet. For regular - * inheritance, recurse upward to check whether an equivalent - * enforced parent outside the ALTER will make it remain enforced. - * Partitions cannot have multiple parents, so they do not need - * this check. - */ - if (!rel->rd_rel->relispartition && - list_member_oid(changing_conids, parentcon->oid)) - { - Oid parent_enforced_parentoid = InvalidOid; - - if (parentrel == NULL) - parentrel = table_open(parentoid, NoLock); - - if (!ATCheckCheckConstrHasEnforcedParent(conrel, - parentrel, - parenttup, - changing_conids, - &parent_enforced_parentoid)) - continue; - } - *enforced_parentoid = parentoid; - if (parentrel != NULL) - table_close(parentrel, NoLock); systable_endscan(pscan); systable_endscan(scan); table_close(inhrel, AccessShareLock); return true; } - if (parentrel != NULL) - table_close(parentrel, NoLock); systable_endscan(pscan); } diff --git a/src/include/catalog/pg_inherits.h b/src/include/catalog/pg_inherits.h index cc874abaabb..66a811e50fa 100644 --- a/src/include/catalog/pg_inherits.h +++ b/src/include/catalog/pg_inherits.h @@ -58,6 +58,7 @@ extern List *find_inheritance_children_extended(Oid parentrelId, bool omit_detac extern List *find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents); +extern List *find_all_inheritors_ordered(Oid parentrelId, LOCKMODE lockmode); extern bool has_subclass(Oid relationId); extern bool has_superclass(Oid relationId); extern bool typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId); diff --git a/src/test/regress/expected/inherit.out b/src/test/regress/expected/inherit.out index 0136aa53c96..38b057a5e8e 100644 --- a/src/test/regress/expected/inherit.out +++ b/src/test/regress/expected/inherit.out @@ -1554,7 +1554,8 @@ drop cascades to table p1_c1 create table gp(a int constraint gp_a_check check (a > 0) enforced); create table p1_c1() inherits (gp); create table p1() inherits (gp); -alter table p1_c1 inherit p1; +create table p2() inherits (p1); +alter table p1_c1 inherit p2; alter table gp alter constraint gp_a_check not enforced; --ok select conname, conenforced, convalidated, conrelid::regclass from pg_constraint @@ -1565,11 +1566,13 @@ order by conrelid::regclass::text collate "C"; gp_a_check | f | f | gp gp_a_check | f | f | p1 gp_a_check | f | f | p1_c1 -(3 rows) + gp_a_check | f | f | p2 +(4 rows) drop table gp cascade; -NOTICE: drop cascades to 2 other objects +NOTICE: drop cascades to 3 other objects DETAIL: drop cascades to table p1 +drop cascades to table p2 drop cascades to table p1_c1 --for "no inherit" check constraint, it will not recurse to child table create table p1(f1 int constraint p1_a_check check (f1 > 0) no inherit not enforced); diff --git a/src/test/regress/sql/inherit.sql b/src/test/regress/sql/inherit.sql index 072fca13c13..db4f4abc709 100644 --- a/src/test/regress/sql/inherit.sql +++ b/src/test/regress/sql/inherit.sql @@ -579,7 +579,8 @@ drop table gp cascade; create table gp(a int constraint gp_a_check check (a > 0) enforced); create table p1_c1() inherits (gp); create table p1() inherits (gp); -alter table p1_c1 inherit p1; +create table p2() inherits (p1); +alter table p1_c1 inherit p2; alter table gp alter constraint gp_a_check not enforced; --ok select conname, conenforced, convalidated, conrelid::regclass from pg_constraint -- 2.50.1 (Apple Git-155) =
^ permalink raw reply [nested|flat] 10+ messages in thread

* Re: Introducing find_all_inheritors_ordered()
@ 2026-09-04 07:15  solai v <solai.cdac@gmail.com>
  parent: Chao Li <li.evan.chao@gmail.com>
  1 sibling, 0 replies; 10+ messages in thread

From: solai v @ 2026-09-04 07:15 UTC (permalink / raw)
  To: Chao Li <li.evan.chao@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Andrew Dunstan <andrew@dunslane.net>; jian he <jian.universality@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; Álvaro Herrera <alvherre@kurilemu.de>

Hi all,



On Mon, Aug 31, 2026 at 2:34 PM Chao Li <li.evan.chao@gmail.com> wrote:
>
> Hi,
>
> This is follow-up work to patch [1], which fixed a bug when altering a CHECK constraint's enforceability. The fix was not very elegant. It had to use upward recursion to traverse all ancestors when deciding a child table's enforceability. This was because the existing function find_all_inheritors() returns a list of descendants without ensuring that parents precede their children.
>
> This patch introduces a new function, find_all_inheritors_ordered(), which guarantees that every ancestor in the returned list appears before its descendants. With this new function, the original fix in commit 0cd17fdd3c0 is significantly simplified. The function could also potentially benefit other features that need to traverse inheritance trees in parent-before-child order.
>
> This patch also strengthens an existing test by adding another level of inheritance. My first version of the implementation failed with the following case:
> ```
> Root ———————————————> child
>      \                                                       /
>       \ ——————> a —————> b /
> ```
> (The diagram might not display well. Basically, “child" has parents “b" and “root", “b" has parent “a”, “a” has parent “root")
>
> The current version uses Kahn's topological sorting algorithm, which handles this case correctly. Please see the attached patch for details.
>
> [1] https://postgr.es/m/E74C57FA-1DD0-4C8E-8FB1-538034752592@gmail.com
>


I reviewed and tested the patch. I was able to reproduce the ordering
issue with find_all_inheritors() using a multiple-inheritance
hierarchy where a descendant can be returned before one of its
ancestors. After the patch, verified that the
find_all_inheritors_ordered() returns the relations in
ancestor-before-descendant order for the same hierarchy. And also
reviewed the changes in tablecmds.c. The removal of the
changing_conids handling and the upward recursive check looks correct
to me. The ordered traversal ensures that the affected parent
constraints are processed before their descendants, and the
CommandCounterIncrement() makes the updated parent constraint state
visible to subsequent processing. The updated regression test provides
coverage for a deeper inheritance hierarchy with multiple inheritance.
I also verified that the existing CHECK constraint enforceability
behavior is preserved. The inherit and constraints regression test
suites were executed successfully. The complete check-world test suite
was also run and all tests passed. I did not find any correctness
issues with the patch and the patch looks good to me.

Regards,
Solai






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

* Re: Introducing find_all_inheritors_ordered()
@ 2026-09-04 08:20  Ewan Young <kdbase.hack@gmail.com>
  parent: Chao Li <li.evan.chao@gmail.com>
  1 sibling, 1 reply; 10+ messages in thread

From: Ewan Young @ 2026-09-04 08:20 UTC (permalink / raw)
  To: Chao Li <li.evan.chao@gmail.com>; +Cc: PostgreSQL Hackers <pgsql-hackers@lists.postgresql.org>; Andrew Dunstan <andrew@dunslane.net>; jian he <jian.universality@gmail.com>; Zsolt Parragi <zsolt.parragi@percona.com>; Álvaro Herrera <alvherre@kurilemu.de>

On Thu, Jul 30, 2026 at 4:35 PM Chao Li <li.evan.chao@gmail.com> wrote:
>
> Hi,
>
> This is follow-up work to patch [1], which fixed a bug when altering a CHECK constraint's enforceability. The fix was not very elegant. It had to use upward recursion to traverse all ancestors when deciding a child table's enforceability. This was because the existing function find_all_inheritors() returns a list of descendants without ensuring that parents precede their children.
>
> This patch introduces a new function, find_all_inheritors_ordered(), which guarantees that every ancestor in the returned list appears before its descendants. With this new function, the original fix in commit 0cd17fdd3c0 is significantly simplified. The function could also potentially benefit other features that need to traverse inheritance trees in parent-before-child order.
>
> This patch also strengthens an existing test by adding another level of inheritance. My first version of the implementation failed with the following case:
> ```
> Root ———————————————> child
>      \                                                       /
>       \ ——————> a —————> b /
> ```
> (The diagram might not display well. Basically, “child" has parents “b" and “root", “b" has parent “a”, “a” has parent “root")
>
> The current version uses Kahn's topological sorting algorithm, which handles this case correctly. Please see the attached patch for details.

I reviewed and tested v1 on top of master (ac1ccbea98f).  The idea is a
clear improvement over the changing_conids + upward recursion in
0cd17fdd3c0: with parents guaranteed to be visited first, a child only
ever needs to look at the *current* state of its direct parents, and the
CommandCounterIncrement() makes that state visible.  That also matches
what ATExecAlterConstrInheritability() already does
(AlterConstrUpdateConstraintEntry() followed by CCI), so there is
precedent for the CCI inside the ALTER CONSTRAINT recursion.

What I checked:

- Kahn's algorithm implementation looks right.  Every non-root node
  enters the agenda as somebody's child and gets indegree++ at that
  moment, so indegrees are exactly the number of in-tree parents;
  appending to a List while iterating it with foreach_oid() is
  explicitly allowed by pg_list.h; dynahash entries do not move on
  HASH_ENTER, so keeping "current" across the inner loop is fine.
  Lock acquisition is identical to find_all_inheritors() (one
  find_inheritance_children(lockmode) call per node).

- Regression: 243/243 pass (cassert build).  I also confirmed that the
  extended test really guards the ordering: if I swap the call site back
  to find_all_inheritors() but keep the simplified tablecmds.c logic,
  p1_c1 stays ENFORCED and the test fails, because BFS order visits
  p1_c1 before p1/p2.

A few small things:

1. Stale comments left behind in tablecmds.c.  The block comment above
   the ATCheckCheckConstrHasEnforcedParent() call in
   ATExecAlterCheckConstrEnforceability() still says "remains ENFORCED
   and is not part of this ALTER" and "another parent outside this
   ALTER may still enforce ... Partitions do not need this recursive
   parent check".  The "not part of this ALTER" qualification and the
   word "recursive" no longer describe the code.  Likewise,
   ATCheckCheckConstrHasEnforcedParent() no longer recurses, so its
   "Since this function recurses, it could be driven to stack overflow"
   comment and the check_stack_depth() call can go.

2. OrderedSeenRelsEntry is missing from src/tools/pgindent/typedefs.list
   (that is why pgindent produced "}            OrderedSeenRelsEntry;"
   instead of "} OrderedSeenRelsEntry;").  Adding it fixes the layout.

3. Possible simplifications in find_all_inheritors_ordered():

   - The root is the only node that can have indegree 0 (see above), so
     the loop over agenda looking for zero-indegree nodes can be
     replaced by worklist = list_make1_oid(parentrelId), perhaps with an
     Assert or a comment explaining why.

   - "ordered" is always identical to "worklist": nodes are appended to
     worklist in exactly the order they are emitted.  You could drop
     "ordered" and just list_copy(worklist) into the caller's context.

Other than the comment cleanup, this looks good to me.

>
> [1] https://postgr.es/m/E74C57FA-1DD0-4C8E-8FB1-538034752592@gmail.com
>
> Best regards,
> --
> Chao Li (Evan)
> HighGo Software Co., Ltd.
> https://www.highgo.com/
>
>


-- 
Regards,
Ewan Young






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

* Re: Introducing find_all_inheritors_ordered()
@ 2026-09-04 21:48  Zsolt Parragi <zsolt.parragi@percona.com>
  parent: Ewan Young <kdbase.hack@gmail.com>
  0 siblings, 1 reply; 10+ messages in thread

From: Zsolt Parragi @ 2026-09-04 21:48 UTC (permalink / raw)
  To: Ewan Young <kdbase.hack@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org, Chao Li <li.evan.chao@gmail.com>

On Fri, 04 Sep 2026, Ewan Young <kdbase.hack@gmail.com> wrote:
> - Kahn's algorithm implementation looks right.

Not entirely, the implementation assumes that the graph is a DAG with
an assert, which unfortunately isn't the case:

At src/backend/commands/tablecmds.c:17958-17964 (ATExecAddInherit)

This is not completely bulletproof because of race conditions: in
multi-level inheritance trees, someone else could concurrently be
making another inheritance link that closes the loop but does not join
either of the rels we have locked. ...  find_all_inheritors() will
cope with circularity anyway, so don't sweat it too much."

This can be reproduced a parallel alter, e.g.:

With r->b, b->c, d->e already in place:
S1:  begin; alter table d inherit c;   -- AEL(d), SUE(c), AS(d,e)
S2:  begin; alter table b inherit e;   -- AEL(b), SUE(e), AS(b,c)
S1:  commit;
S2:  commit;

And then alters can either hit the

Assert(list_length(ordered) == list_length(agenda));

assertion in debug builds or end up with a inconsistent results in
release builds.






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

* Re: Introducing find_all_inheritors_ordered()
@ 2026-09-07 06:40  Chao Li <li.evan.chao@gmail.com>
  parent: Zsolt Parragi <zsolt.parragi@percona.com>
  0 siblings, 1 reply; 10+ messages in thread

From: Chao Li @ 2026-09-07 06:40 UTC (permalink / raw)
  To: Zsolt Parragi <zsolt.parragi@percona.com>; +Cc: Ewan Young <kdbase.hack@gmail.com>; pgsql-hackers@lists.postgresql.org



> On Sep 5, 2026, at 05:48, Zsolt Parragi <zsolt.parragi@percona.com> wrote:
> 
> On Fri, 04 Sep 2026, Ewan Young <kdbase.hack@gmail.com> wrote:
>> - Kahn's algorithm implementation looks right.
> 
> Not entirely, the implementation assumes that the graph is a DAG with
> an assert, which unfortunately isn't the case:
> 
> At src/backend/commands/tablecmds.c:17958-17964 (ATExecAddInherit)
> 
> This is not completely bulletproof because of race conditions: in
> multi-level inheritance trees, someone else could concurrently be
> making another inheritance link that closes the loop but does not join
> either of the rels we have locked. ...  find_all_inheritors() will
> cope with circularity anyway, so don't sweat it too much."
> 
> This can be reproduced a parallel alter, e.g.:
> 
> With r->b, b->c, d->e already in place:
> S1:  begin; alter table d inherit c;   -- AEL(d), SUE(c), AS(d,e)
> S2:  begin; alter table b inherit e;   -- AEL(b), SUE(e), AS(b,c)
> S1:  commit;
> S2:  commit;
> 
> And then alters can either hit the
> 
> Assert(list_length(ordered) == list_length(agenda));
> 
> assertion in debug builds or end up with a inconsistent results in
> release builds.

Hi Zsolt,

Thanks for pointing out that, I didn’t notice that piece of comments before.

My understanding is that PG doesn’t intend to support cyclic inheritance. The code explicitly rejects it:
```
	if (list_member_oid(children, RelationGetRelid(parent_rel)))
		ereport(ERROR,
				(errcode(ERRCODE_DUPLICATE_TABLE),
				 errmsg("circular inheritance not allowed"),
				 errdetail("\"%s\" is already a child of \"%s\".",
						   parent->relname,
						   RelationGetRelationName(child_rel))));
```

However, concurrent ALTER TABLE … INHERIT commands may create cycles, and preventing that would be too expensive. So, find_all_inheritors() handles cycles defensively.

Therefore, find_all_inheritors_ordered() should not be a general replacement for find_all_inheritors(). ATExecAddInherit() can continue using find_all_inheritors(), allowing ALTER TABLE … INHERIT to succeed if its check finds that the new link would not create a cycle. Other DDL commands that don’t change inheritance and need a topological ordering can use find_all_inheritors_ordered(). I have updated the function’s header comment to explain this and replaced the assertion with an error.

For the ALTER TABLE … ALTER CONSTRAINT … NOT ENFORCED command that this patch updates, the existing implementation recursively checks parents’ enforceability. A cycle can cause it to exceed the stack depth limit, so it is reasonable to fail the command when a cycle is detected.

Going one step further, perhaps ATExecAddInherit() could also use find_all_inheritors_ordered(). That would change the behavior: if the child being altered is in a cycle, or has descendants in a cycle, the command would fail, requiring the user to break the cycle first. This would not prevent concurrent commands from creating a cycle, but it could reveal an existing, unintended cycle that users might otherwise be unaware of.

PFA v2.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/

Attachments:

v2-0001-Add-find_all_inheritors_ordered.patch (application/octet-stream, 17.2K) download From 7c7b79cec94cc8c23e90582667f49be4187849f4 Mon Sep 17 00:00:00 2001 From: "Chao Li (Evan)" <lic@highgo.com> Date: Thu, 30 Jul 2026 16:03:49 +0800 Subject: [PATCH v2] Add find_all_inheritors_ordered() Add an inheritance traversal that guarantees every ancestor appears before its descendants. find_all_inheritors() does not provide this ordering when multiple inheritance creates both direct and indirect paths to a relation. Use Kahn's topological sorting algorithm to produce the ordered list without recursion. Use the new function to simplify the inherited CHECK constraint enforceability handling committed by 0cd17fdd3c0. Since parents are processed before their children, checking the current state of a child's direct parents is sufficient. Extend the direct-plus-indirect inheritance test with another intermediate level. Author: Chao Li <lic@highgo.com> Reviewed-by: solai v <solai.cdac@gmail.com> Reviewed-by: Ewan Young <kdbase.hack@gmail.com> Reviewed-by: Zsolt Parragi <zsolt.parragi@percona.com> Discussion: https://postgr.es/m/57100518-3FF1-48AD-B550-47B9A3E88688@gmail.com --- src/backend/catalog/pg_inherits.c | 138 ++++++++++++++++++++++++++ src/backend/commands/tablecmds.c | 110 ++++---------------- src/include/catalog/pg_inherits.h | 1 + src/test/regress/expected/inherit.out | 9 +- src/test/regress/sql/inherit.sql | 3 +- 5 files changed, 169 insertions(+), 92 deletions(-) diff --git a/src/backend/catalog/pg_inherits.c b/src/backend/catalog/pg_inherits.c index 23fb7886cfb..c80077dc643 100644 --- a/src/backend/catalog/pg_inherits.c +++ b/src/backend/catalog/pg_inherits.c @@ -29,6 +29,7 @@ #include "utils/builtins.h" #include "utils/fmgroids.h" #include "utils/hsearch.h" +#include "utils/memutils.h" #include "utils/snapmgr.h" #include "utils/syscache.h" @@ -41,6 +42,16 @@ typedef struct SeenRelsEntry int list_index; /* its position in output list(s) */ } SeenRelsEntry; +/* + * Entry of a hash table used in find_all_inheritors_ordered. + */ +typedef struct OrderedSeenRelsEntry +{ + Oid rel_id; + List *children; + int indegree; +} OrderedSeenRelsEntry; + /* * find_inheritance_children * @@ -335,6 +346,133 @@ find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents) return rels_list; } +/* + * find_all_inheritors_ordered - + * Same as find_all_inheritors(), except that an ancestor is always listed + * before its descendants. + * + * The ordering is produced using Kahn's topological sorting algorithm. + * Unlike find_all_inheritors(), this function reports an error if the + * inheritance graph contains a cycle, since no such ordering is possible. + * Concurrent ALTER TABLE ... INHERIT commands can create cycles despite + * the circularity check in ATExecAddInherit(). Callers that need to tolerate + * cycles should use find_all_inheritors() instead. + */ +List * +find_all_inheritors_ordered(Oid parentrelId, LOCKMODE lockmode) +{ + MemoryContext temp_context; + MemoryContext old_context; + HTAB *seen_rels; + HASHCTL ctl; + List *agenda; + List *worklist = NIL; + List *ordered = NIL; + List *result = NIL; + ListCell *lc; + OrderedSeenRelsEntry *node; + bool found; + + /* Use a temporary memory context to simplify cleanup */ + temp_context = AllocSetContextCreate(CurrentMemoryContext, + "find_all_inheritors_ordered", + ALLOCSET_SMALL_SIZES); + old_context = MemoryContextSwitchTo(temp_context); + + ctl.keysize = sizeof(Oid); + ctl.entrysize = sizeof(OrderedSeenRelsEntry); + ctl.hcxt = temp_context; + + seen_rels = hash_create("find_all_inheritors_ordered temporary table", + 32, /* start small and extend */ + &ctl, + HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); + + node = hash_search(seen_rels, &parentrelId, HASH_ENTER, &found); + Assert(!found); + node->children = NIL; + node->indegree = 0; + + /* + * Use the agenda to find every descendant and record every inheritance + * edge. The indegree is the number of direct parents within this + * inheritance graph. + */ + agenda = list_make1_oid(parentrelId); + foreach(lc, agenda) + { + Oid current_oid = lfirst_oid(lc); + List *children; + OrderedSeenRelsEntry *current; + + current = hash_search(seen_rels, &current_oid, HASH_FIND, NULL); + Assert(current != NULL); + + children = find_inheritance_children(current_oid, lockmode); + foreach_oid(child_oid, children) + { + node = hash_search(seen_rels, &child_oid, HASH_ENTER, &found); + if (!found) + { + node->children = NIL; + node->indegree = 0; + agenda = lappend_oid(agenda, child_oid); + } + + current->children = lappend_oid(current->children, child_oid); + node->indegree++; + } + list_free(children); + } + + /* + * Emit nodes in topological order. A node enters the worklist only after + * all of its direct parents have been emitted. + */ + foreach_oid(rel_oid, agenda) + { + node = hash_search(seen_rels, &rel_oid, HASH_FIND, NULL); + Assert(node != NULL); + if (node->indegree == 0) + worklist = lappend_oid(worklist, rel_oid); + } + + /* + * Move nodes from the worklist to the output list, and add their children + * to the worklist when all of their parents have been emitted. + */ + foreach_oid(rel_oid, worklist) + { + node = hash_search(seen_rels, &rel_oid, HASH_FIND, NULL); + Assert(node != NULL); + ordered = lappend_oid(ordered, rel_oid); + + foreach_oid(child_oid, node->children) + { + OrderedSeenRelsEntry *child; + + child = hash_search(seen_rels, &child_oid, HASH_FIND, NULL); + Assert(child != NULL); + Assert(child->indegree > 0); + if (--child->indegree == 0) + worklist = lappend_oid(worklist, child_oid); + } + } + + /* Any nodes not emitted are in a cycle or depend on one. */ + if (list_length(ordered) != list_length(agenda)) + ereport(ERROR, + errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot order relations with circular inheritance"), + errhint("Use ALTER TABLE ... NO INHERIT to break the cycle.")); + + MemoryContextSwitchTo(old_context); + result = list_copy(ordered); + MemoryContextDelete(temp_context); + + return result; +} + /* * has_subclass - does this relation have any children? diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index fd144d783d9..6024f804bfc 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -415,7 +415,6 @@ static bool ATExecAlterFKConstrEnforceability(List **wqueue, ATAlterConstraint * static bool ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, HeapTuple contuple, bool recurse, bool recursing, - List *changing_conids, LOCKMODE lockmode); static bool ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, Relation tgrel, Relation rel, @@ -438,7 +437,6 @@ static void AlterFKConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint static void AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, Oid conrelid, bool recurse, bool recursing, - List *changing_conids, LOCKMODE lockmode); static void AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, Relation tgrel, Relation rel, @@ -448,7 +446,6 @@ static void AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation HeapTuple contuple); static bool ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel, HeapTuple contuple, - List *changing_conids, Oid *enforced_parentoid); static ObjectAddress ATExecValidateConstraint(List **wqueue, Relation rel, char *constrName, @@ -12478,7 +12475,7 @@ ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon, else if (currcon->contype == CONSTRAINT_CHECK) changed = ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel, contuple, recurse, false, - NIL, lockmode); + lockmode); } else if (cmdcon->alterDeferrability && ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, rel, @@ -12666,7 +12663,6 @@ static bool ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, HeapTuple contuple, bool recurse, bool recursing, - List *changing_conids, LOCKMODE lockmode) { Form_pg_constraint currcon; @@ -12708,7 +12704,6 @@ ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, if (!cmdcon->is_enforced && (!recursing || !rel->rd_rel->relispartition) && ATCheckCheckConstrHasEnforcedParent(conrel, rel, contuple, - changing_conids, &enforced_parentoid)) { if (!recursing) @@ -12735,6 +12730,14 @@ ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, updatecon.is_enforced = target_enforced; AlterConstrUpdateConstraintEntry(&updatecon, conrel, contuple); changed = true; + + /* + * A later descendant must see this change when checking its direct + * parents. The ordered inheritance traversal guarantees that all + * affected parents are processed before their children. + */ + if (!cmdcon->is_enforced) + CommandCounterIncrement(); } /* @@ -12755,55 +12758,20 @@ ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, */ if (!recursing && !currcon->connoinherit) { - Assert(changing_conids == NIL); - - children = find_all_inheritors(RelationGetRelid(rel), - lockmode, NULL); + children = find_all_inheritors_ordered(RelationGetRelid(rel), + lockmode); /* - * When setting NOT ENFORCED, build the set of equivalent CHECK - * constraints that this command will attempt to change before - * visiting descendants. The root itself has already been checked - * above. + * If we are told not to recurse, there had better not be any + * child tables, because we can't change constraint enforceability + * on the parent unless we have changed enforceability for all + * children. */ - if (!cmdcon->is_enforced) - changing_conids = list_make1_oid(currcon->oid); - - foreach_oid(childoid, children) - { - if (childoid == RelationGetRelid(rel)) - continue; - - /* - * If we are told not to recurse, there had better not be any - * child tables, because we can't change constraint - * enforceability on the parent unless we have changed - * enforceability for all child. - */ - if (!recurse) - ereport(ERROR, - errcode(ERRCODE_INVALID_TABLE_DEFINITION), - errmsg("constraint must be altered on child tables too"), - errhint("Do not specify the ONLY keyword.")); - - /* - * It is sufficient to look up the constraint by name here. - * Supported DDL ensures that inheritable CHECK constraints - * with the same name have equivalent definitions when they - * are propagated to children or when inheritance is - * established. All descendants returned by - * find_all_inheritors must have this constraint: inherited - * CHECK constraints propagate to all children at - * inheritance-link creation time and cannot be dropped - * independently on child tables. - */ - if (!cmdcon->is_enforced) - changing_conids = - list_append_unique_oid(changing_conids, - get_relation_constraint_oid(childoid, - cmdcon->conname, - false)); - } + if (!recurse && list_length(children) > 1) + ereport(ERROR, + errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("constraint must be altered on child tables too"), + errhint("Do not specify the ONLY keyword.")); } foreach_oid(childoid, children) @@ -12813,7 +12781,6 @@ ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, AlterCheckConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, childoid, false, true, - changing_conids, lockmode); } } @@ -12865,7 +12832,6 @@ static void AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, Oid conrelid, bool recurse, bool recursing, - List *changing_conids, LOCKMODE lockmode) { SysScanDesc pscan; @@ -12895,21 +12861,18 @@ AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon, cmdcon->conname, get_rel_name(conrelid))); ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel, childtup, - recurse, recursing, changing_conids, - lockmode); + recurse, recursing, lockmode); systable_endscan(pscan); } /* * When setting an inherited CHECK constraint to NOT ENFORCED, look for a - * matching parent constraint that remains ENFORCED and is not part of the same - * ALTER. + * matching parent constraint that remains ENFORCED. */ static bool ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel, HeapTuple contuple, - List *changing_conids, Oid *enforced_parentoid) { Form_pg_constraint currcon; @@ -12939,7 +12902,6 @@ ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel, while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan))) { Oid parentoid; - Relation parentrel = NULL; SysScanDesc pscan; ScanKeyData pkey[3]; HeapTuple parenttup; @@ -12983,41 +12945,13 @@ ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel, RelationGetRelationName(rel), NameStr(parentcon->conname)); - /* - * A parent listed in changing_conids is being changed by the same - * ALTER, but it may not have been updated yet. For regular - * inheritance, recurse upward to check whether an equivalent - * enforced parent outside the ALTER will make it remain enforced. - * Partitions cannot have multiple parents, so they do not need - * this check. - */ - if (!rel->rd_rel->relispartition && - list_member_oid(changing_conids, parentcon->oid)) - { - Oid parent_enforced_parentoid = InvalidOid; - - if (parentrel == NULL) - parentrel = table_open(parentoid, NoLock); - - if (!ATCheckCheckConstrHasEnforcedParent(conrel, - parentrel, - parenttup, - changing_conids, - &parent_enforced_parentoid)) - continue; - } - *enforced_parentoid = parentoid; - if (parentrel != NULL) - table_close(parentrel, NoLock); systable_endscan(pscan); systable_endscan(scan); table_close(inhrel, AccessShareLock); return true; } - if (parentrel != NULL) - table_close(parentrel, NoLock); systable_endscan(pscan); } diff --git a/src/include/catalog/pg_inherits.h b/src/include/catalog/pg_inherits.h index cc874abaabb..66a811e50fa 100644 --- a/src/include/catalog/pg_inherits.h +++ b/src/include/catalog/pg_inherits.h @@ -58,6 +58,7 @@ extern List *find_inheritance_children_extended(Oid parentrelId, bool omit_detac extern List *find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents); +extern List *find_all_inheritors_ordered(Oid parentrelId, LOCKMODE lockmode); extern bool has_subclass(Oid relationId); extern bool has_superclass(Oid relationId); extern bool typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId); diff --git a/src/test/regress/expected/inherit.out b/src/test/regress/expected/inherit.out index 0136aa53c96..38b057a5e8e 100644 --- a/src/test/regress/expected/inherit.out +++ b/src/test/regress/expected/inherit.out @@ -1554,7 +1554,8 @@ drop cascades to table p1_c1 create table gp(a int constraint gp_a_check check (a > 0) enforced); create table p1_c1() inherits (gp); create table p1() inherits (gp); -alter table p1_c1 inherit p1; +create table p2() inherits (p1); +alter table p1_c1 inherit p2; alter table gp alter constraint gp_a_check not enforced; --ok select conname, conenforced, convalidated, conrelid::regclass from pg_constraint @@ -1565,11 +1566,13 @@ order by conrelid::regclass::text collate "C"; gp_a_check | f | f | gp gp_a_check | f | f | p1 gp_a_check | f | f | p1_c1 -(3 rows) + gp_a_check | f | f | p2 +(4 rows) drop table gp cascade; -NOTICE: drop cascades to 2 other objects +NOTICE: drop cascades to 3 other objects DETAIL: drop cascades to table p1 +drop cascades to table p2 drop cascades to table p1_c1 --for "no inherit" check constraint, it will not recurse to child table create table p1(f1 int constraint p1_a_check check (f1 > 0) no inherit not enforced); diff --git a/src/test/regress/sql/inherit.sql b/src/test/regress/sql/inherit.sql index 072fca13c13..db4f4abc709 100644 --- a/src/test/regress/sql/inherit.sql +++ b/src/test/regress/sql/inherit.sql @@ -579,7 +579,8 @@ drop table gp cascade; create table gp(a int constraint gp_a_check check (a > 0) enforced); create table p1_c1() inherits (gp); create table p1() inherits (gp); -alter table p1_c1 inherit p1; +create table p2() inherits (p1); +alter table p1_c1 inherit p2; alter table gp alter constraint gp_a_check not enforced; --ok select conname, conenforced, convalidated, conrelid::regclass from pg_constraint -- 2.50.1 (Apple Git-155) =
^ permalink raw reply [nested|flat] 10+ messages in thread

* Re: Introducing find_all_inheritors_ordered()
@ 2026-09-07 22:16  Zsolt Parragi <zsolt.parragi@percona.com>
  parent: Chao Li <li.evan.chao@gmail.com>
  0 siblings, 2 replies; 10+ messages in thread

From: Zsolt Parragi @ 2026-09-07 22:16 UTC (permalink / raw)
  To: Chao Li <li.evan.chao@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org, Ewan Young <kdbase.hack@gmail.com>

On Mon, 07 Sep 2026, Chao Li <li.evan.chao@gmail.com> wrote:
> My understanding is that PG doesn’t intend to support cyclic inheritance. The code explicitly rejects it:

To me it seems like that it discourages it and tries to prevent it
where it's possible to do so with reasonable effort, but it ends up
trying to support it because it's a valid scenario that can happen in
some workloads (as long as that also doesn't require too much effort).

> A cycle can cause it to exceed the stack depth limit, so it is reasonable to fail the command when a cycle is detected.

Or it might succeed in other cases.

Here's a repro with an isolation test. Perm 1 fails on master, works
with the patch. Perm 2 works on master, fails with the patch.
We could improve this by only using the new function in the enforced
direction, I don't have a better idea currently. With that, the
patched behavior would be the same as on master.

setup
{
  CREATE TABLE r (x int CONSTRAINT cc CHECK (x > 0));
  CREATE TABLE a (x int CONSTRAINT cc CHECK (x > 0));
  CREATE TABLE b (x int CONSTRAINT cc CHECK (x > 0));
  CREATE TABLE c (x int CONSTRAINT cc CHECK (x > 0));
  CREATE TABLE d (x int CONSTRAINT cc CHECK (x > 0));
  ALTER TABLE a INHERIT r;
  ALTER TABLE b INHERIT a;
  ALTER TABLE d INHERIT c;
}

teardown
{
  DROP TABLE IF EXISTS r, a, b, c, d CASCADE;
}

session s1
step s1b  { BEGIN; }
step s1i  { ALTER TABLE c INHERIT b; }
step s1c  { COMMIT; }

session s2
step s2b  { BEGIN; }
step s2i  { ALTER TABLE a INHERIT d; }
step s2c  { COMMIT; }

session s3
step s3pre { ALTER TABLE r ALTER CONSTRAINT cc NOT ENFORCED;
             ALTER TABLE c ALTER CONSTRAINT cc NOT ENFORCED; }
step s3e   { SELECT inhrelid::regclass::text AS child,
                    inhparent::regclass::text AS parent
             FROM pg_inherits
             WHERE inhrelid::regclass::text IN ('r','a','b','c','d')
             ORDER BY 1, 2; }
step s3not { ALTER TABLE r ALTER CONSTRAINT cc NOT ENFORCED; }
step s3enf { ALTER TABLE r ALTER CONSTRAINT cc ENFORCED; }
step s3s   { SELECT conrelid::regclass::text AS rel, conenforced
             FROM pg_constraint
             WHERE conname = 'cc'
               AND conrelid::regclass::text IN ('r','a','b','c','d')
             ORDER BY 1; }

permutation s1b s2b s1i s2i s1c s2c s3e s3not s3s
permutation s1b s2b s3pre s1i s2i s1c s2c s3e s3enf s3s






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

* Re: Introducing find_all_inheritors_ordered()
@ 2026-09-07 23:38  Tom Lane <tgl@sss.pgh.pa.us>
  parent: Zsolt Parragi <zsolt.parragi@percona.com>
  1 sibling, 1 reply; 10+ messages in thread

From: Tom Lane @ 2026-09-07 23:38 UTC (permalink / raw)
  To: Zsolt Parragi <zsolt.parragi@percona.com>; +Cc: Chao Li <li.evan.chao@gmail.com>; pgsql-hackers@lists.postgresql.org, Ewan Young <kdbase.hack@gmail.com>

Zsolt Parragi <zsolt.parragi@percona.com> writes:
> On Mon, 07 Sep 2026, Chao Li <li.evan.chao@gmail.com> wrote:
>> My understanding is that PG doesn’t intend to support cyclic inheritance. The code explicitly rejects it:

> To me it seems like that it discourages it and tries to prevent it
> where it's possible to do so with reasonable effort, but it ends up
> trying to support it because it's a valid scenario that can happen in
> some workloads (as long as that also doesn't require too much effort).

Why is it a valid scenario, and how would we reach it?  It's going to
cause tons of problems if it can happen, so I'd rather put effort into
blocking it than making some parts of the system cope.

I have a different concern about the patch as it stands: the
data-gathering part is unnecessarily duplicative of
find_all_inheritors.  It does its best to look like it's doing
something different, but actually it computes exactly the same list
of relation OIDs and the same number-of-parents data.  And indeed
it had better be doing the same things in the same order, because
otherwise we'd be risking deadlock failures instead of simple
blocking when two processes are acquiring exclusive locks on
overlapping inheritance trees.  (Note the comment about "we need to be
sure all backends lock children in the same order to avoid needless
deadlocks" in find_inheritance_children.)  I don't like having two
independent implementations that are invisibly tied like that: if
they diverge, we might not notice until somebody makes a bug report
and somebody else figures out what's causing the deadlock.  So IMO
those two functions need to be revised to use a common data-gathering
step.

			regards, tom lane






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

* Re: Introducing find_all_inheritors_ordered()
@ 2026-09-08 03:46  Chao Li <li.evan.chao@gmail.com>
  parent: Zsolt Parragi <zsolt.parragi@percona.com>
  1 sibling, 0 replies; 10+ messages in thread

From: Chao Li @ 2026-09-08 03:46 UTC (permalink / raw)
  To: Zsolt Parragi <zsolt.parragi@percona.com>; +Cc: pgsql-hackers@lists.postgresql.org, Ewan Young <kdbase.hack@gmail.com>



> On Sep 8, 2026, at 06:16, Zsolt Parragi <zsolt.parragi@percona.com> wrote:
> 
> On Mon, 07 Sep 2026, Chao Li <li.evan.chao@gmail.com> wrote:
>> My understanding is that PG doesn’t intend to support cyclic inheritance. The code explicitly rejects it:
> 
> To me it seems like that it discourages it and tries to prevent it
> where it's possible to do so with reasonable effort, but it ends up
> trying to support it because it's a valid scenario that can happen in
> some workloads (as long as that also doesn't require too much effort).

I think an important problem is that, in your earlier example, two users independently execute ALTER TABLE … INHERIT, but the commands together create an inheritance cycle without either user being notified. Even if PG currently tolerates this, I think preventing it would be preferable.

As Tom pointed out, cycles can also cause problems elsewhere in the system. So I agree that we should investigate whether we can prevent their creation at a reasonable cost.

> 
>> A cycle can cause it to exceed the stack depth limit, so it is reasonable to fail the command when a cycle is detected.
> 
> Or it might succeed in other cases.
> 
> Here's a repro with an isolation test. Perm 1 fails on master, works
> with the patch. Perm 2 works on master, fails with the patch.
> We could improve this by only using the new function in the enforced
> direction, I don't have a better idea currently. With that, the
> patched behavior would be the same as on master.
> 

This is a valid point. ENFORCED doesn’t need to check parents’ enforceability, so we can still use find_all_inheritors() to tolerate potential cycles and use find_all_inheritors_ordered() only for NOT ENFORCED. This preserves master’s success/failure outcomes in your test, while replacing the stack-depth error with an explicit cycle error. I have updated the code in v3.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/









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

* Re: Introducing find_all_inheritors_ordered()
@ 2026-09-08 03:54  Chao Li <li.evan.chao@gmail.com>
  parent: Tom Lane <tgl@sss.pgh.pa.us>
  0 siblings, 1 reply; 10+ messages in thread

From: Chao Li @ 2026-09-08 03:54 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Zsolt Parragi <zsolt.parragi@percona.com>; pgsql-hackers@lists.postgresql.org, Ewan Young <kdbase.hack@gmail.com>



> On Sep 8, 2026, at 07:38, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> 
> Zsolt Parragi <zsolt.parragi@percona.com> writes:
>> On Mon, 07 Sep 2026, Chao Li <li.evan.chao@gmail.com> wrote:
>>> My understanding is that PG doesn’t intend to support cyclic inheritance. The code explicitly rejects it:
> 
>> To me it seems like that it discourages it and tries to prevent it
>> where it's possible to do so with reasonable effort, but it ends up
>> trying to support it because it's a valid scenario that can happen in
>> some workloads (as long as that also doesn't require too much effort).
> 
> Why is it a valid scenario, and how would we reach it?  It's going to
> cause tons of problems if it can happen, so I'd rather put effort into
> blocking it than making some parts of the system cope.

+1

I can look into if we can prevent concurrent ALTER TABLE ... INHERIT commands from creating cycles at a reasonable cost, and start a separate discussion.

> 
> I have a different concern about the patch as it stands: the
> data-gathering part is unnecessarily duplicative of
> find_all_inheritors.  It does its best to look like it's doing
> something different, but actually it computes exactly the same list
> of relation OIDs and the same number-of-parents data.  And indeed
> it had better be doing the same things in the same order, because
> otherwise we'd be risking deadlock failures instead of simple
> blocking when two processes are acquiring exclusive locks on
> overlapping inheritance trees.  (Note the comment about "we need to be
> sure all backends lock children in the same order to avoid needless
> deadlocks" in find_inheritance_children.)  I don't like having two
> independent implementations that are invisibly tied like that: if
> they diverge, we might not notice until somebody makes a bug report
> and somebody else figures out what's causing the deadlock.  So IMO
> those two functions need to be revised to use a common data-gathering
> step.
> 

That’s a good point. In the initial version, I tried to avoid touching find_all_inheritors(), which resulted in some duplicate code. In v3, I have refactored the two functions to share the data-gathering and locking code.

Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/

Attachments:

v3-0001-Add-find_all_inheritors_ordered.patch (application/octet-stream, 19.1K) download From c8fe5c46f3fe2cf3087e3df79e4e85f3747d0a13 Mon Sep 17 00:00:00 2001 From: "Chao Li (Evan)" <lic@highgo.com> Date: Thu, 30 Jul 2026 16:03:49 +0800 Subject: [PATCH v3] Add find_all_inheritors_ordered() Add an inheritance traversal that guarantees every ancestor appears before its descendants. find_all_inheritors() does not provide this ordering when multiple inheritance creates both direct and indirect paths to a relation. Use Kahn's topological sorting algorithm to produce the ordered list without recursion. Use the new function to simplify the inherited CHECK constraint enforceability handling committed by 0cd17fdd3c0. Since parents are processed before their children, checking the current state of a child's direct parents is sufficient. Extend the direct-plus-indirect inheritance test with another intermediate level. Author: Chao Li <lic@highgo.com> Reviewed-by: solai v <solai.cdac@gmail.com> Reviewed-by: Ewan Young <kdbase.hack@gmail.com> Reviewed-by: Zsolt Parragi <zsolt.parragi@percona.com> Reviewed-by: Tom Lane <tgl@sss.pgh.pa.us> Discussion: https://postgr.es/m/57100518-3FF1-48AD-B550-47B9A3E88688@gmail.com --- src/backend/catalog/pg_inherits.c | 158 ++++++++++++++++++++++++++ src/backend/commands/tablecmds.c | 122 ++++++-------------- src/include/catalog/pg_inherits.h | 1 + src/test/regress/expected/inherit.out | 9 +- src/test/regress/sql/inherit.sql | 3 +- 5 files changed, 204 insertions(+), 89 deletions(-) diff --git a/src/backend/catalog/pg_inherits.c b/src/backend/catalog/pg_inherits.c index 23fb7886cfb..4525f77ad67 100644 --- a/src/backend/catalog/pg_inherits.c +++ b/src/backend/catalog/pg_inherits.c @@ -29,6 +29,7 @@ #include "utils/builtins.h" #include "utils/fmgroids.h" #include "utils/hsearch.h" +#include "utils/memutils.h" #include "utils/snapmgr.h" #include "utils/syscache.h" @@ -41,6 +42,19 @@ typedef struct SeenRelsEntry int list_index; /* its position in output list(s) */ } SeenRelsEntry; +/* + * Entry of a hash table used in find_all_inheritors_ordered. + */ +typedef struct OrderedSeenRelsEntry +{ + Oid rel_id; + List *children; + int indegree; +} OrderedSeenRelsEntry; + +static List *find_all_inheritors_internal(Oid parentrelId, LOCKMODE lockmode, + List **numparents, List **children); + /* * find_inheritance_children * @@ -254,6 +268,22 @@ find_inheritance_children_extended(Oid parentrelId, bool omit_detached, */ List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents) +{ + return find_all_inheritors_internal(parentrelId, lockmode, numparents, NULL); +} + +/* + * Common discovery and locking step for both inheritance traversals. Keep + * lock acquisition here so that ordering the result cannot change the order + * in which relations are locked. + * + * If requested, children receives a list of direct-child OID lists, parallel + * to the returned relation list and numparents. Retain these from the same + * scans that discover the relations and count their parents. + */ +static List * +find_all_inheritors_internal(Oid parentrelId, LOCKMODE lockmode, + List **numparents, List **children) { /* hash table for O(1) rel_oid -> rel_numparents cell lookup */ HTAB *seen_rels; @@ -262,6 +292,9 @@ find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents) *rel_numparents; ListCell *l; + if (children) + *children = NIL; + ctl.keysize = sizeof(Oid); ctl.entrysize = sizeof(SeenRelsEntry); ctl.hcxt = CurrentMemoryContext; @@ -323,6 +356,9 @@ find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents) rel_numparents = lappend_int(rel_numparents, 1); } } + + if (children) + *children = lappend(*children, currentchildren); } if (numparents) @@ -335,6 +371,128 @@ find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents) return rels_list; } +/* + * find_all_inheritors_ordered - + * Same as find_all_inheritors(), except that an ancestor is always listed + * before its descendants. + * + * The ordering is produced using Kahn's topological sorting algorithm. + * Unlike find_all_inheritors(), this function reports an error if the + * inheritance graph contains a cycle, since no such ordering is possible. + * Concurrent ALTER TABLE ... INHERIT commands can create cycles despite + * the circularity check in ATExecAddInherit(). Callers that need to tolerate + * cycles should use find_all_inheritors() instead. + */ +List * +find_all_inheritors_ordered(Oid parentrelId, LOCKMODE lockmode) +{ + MemoryContext temp_context; + MemoryContext old_context; + HTAB *seen_rels; + HASHCTL ctl; + List *agenda; + List *numparents; + List *children; + List *worklist = NIL; + List *ordered = NIL; + List *result = NIL; + ListCell *lc; + ListCell *lp; + ListCell *ll; + OrderedSeenRelsEntry *node; + bool found; + + /* Use a temporary memory context to simplify cleanup */ + temp_context = AllocSetContextCreate(CurrentMemoryContext, + "find_all_inheritors_ordered", + ALLOCSET_SMALL_SIZES); + old_context = MemoryContextSwitchTo(temp_context); + + agenda = find_all_inheritors_internal(parentrelId, lockmode, + &numparents, &children); + + ctl.keysize = sizeof(Oid); + ctl.entrysize = sizeof(OrderedSeenRelsEntry); + ctl.hcxt = temp_context; + + seen_rels = hash_create("find_all_inheritors_ordered temporary table", + 32, /* start small and extend */ + &ctl, + HASH_ELEM | HASH_BLOBS | HASH_CONTEXT); + + /* + * Index the collected graph for sorting. No more catalog scans or lock + * acquisitions are needed. The indegree counts direct parents within + * this inheritance graph. + */ + forthree(lc, agenda, lp, numparents, ll, children) + { + Oid current_oid = lfirst_oid(lc); + + node = hash_search(seen_rels, &current_oid, HASH_ENTER, &found); + + /* + * find_all_inheritors_internal() can return the root twice if it is + * in a cycle. + */ + if (found) + goto cycle; + node->children = lfirst(ll); + node->indegree = lfirst_int(lp); + } + + /* + * Emit nodes in topological order. A node enters the worklist only after + * all of its direct parents have been emitted. + */ + foreach_oid(rel_oid, agenda) + { + node = hash_search(seen_rels, &rel_oid, HASH_FIND, NULL); + Assert(node != NULL); + if (node->indegree == 0) + worklist = lappend_oid(worklist, rel_oid); + } + + /* + * Move nodes from the worklist to the output list, and add their children + * to the worklist when all of their parents have been emitted. + */ + foreach_oid(rel_oid, worklist) + { + node = hash_search(seen_rels, &rel_oid, HASH_FIND, NULL); + Assert(node != NULL); + ordered = lappend_oid(ordered, rel_oid); + + foreach_oid(child_oid, node->children) + { + OrderedSeenRelsEntry *child; + + child = hash_search(seen_rels, &child_oid, HASH_FIND, NULL); + Assert(child != NULL); + Assert(child->indegree > 0); + if (--child->indegree == 0) + worklist = lappend_oid(worklist, child_oid); + } + } + + /* Any nodes not emitted are in a cycle or depend on one. */ + if (list_length(ordered) != list_length(agenda)) + goto cycle; + + MemoryContextSwitchTo(old_context); + result = list_copy(ordered); + MemoryContextDelete(temp_context); + + return result; + +cycle: + ereport(ERROR, + errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("cannot order relations with circular inheritance"), + errhint("Use ALTER TABLE ... NO INHERIT to break the cycle.")); + return NIL; /* keep compiler quiet */ +} + /* * has_subclass - does this relation have any children? diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c index a1519297ec7..1c2df8ee4b2 100644 --- a/src/backend/commands/tablecmds.c +++ b/src/backend/commands/tablecmds.c @@ -409,7 +409,6 @@ static bool ATExecAlterFKConstrEnforceability(List **wqueue, ATAlterConstraint * static bool ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, HeapTuple contuple, bool recurse, bool recursing, - List *changing_conids, LOCKMODE lockmode); static bool ATExecAlterConstrDeferrability(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, Relation tgrel, Relation rel, @@ -432,7 +431,6 @@ static void AlterFKConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint static void AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, Oid conrelid, bool recurse, bool recursing, - List *changing_conids, LOCKMODE lockmode); static void AlterConstrDeferrabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, Relation tgrel, Relation rel, @@ -442,7 +440,6 @@ static void AlterConstrUpdateConstraintEntry(ATAlterConstraint *cmdcon, Relation HeapTuple contuple); static bool ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel, HeapTuple contuple, - List *changing_conids, Oid *enforced_parentoid); static ObjectAddress ATExecValidateConstraint(List **wqueue, Relation rel, char *constrName, @@ -12468,7 +12465,7 @@ ATExecAlterConstraintInternal(List **wqueue, ATAlterConstraint *cmdcon, else if (currcon->contype == CONSTRAINT_CHECK) changed = ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel, contuple, recurse, false, - NIL, lockmode); + lockmode); } else if (cmdcon->alterDeferrability && ATExecAlterConstrDeferrability(wqueue, cmdcon, conrel, tgrel, rel, @@ -12656,7 +12653,6 @@ static bool ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, HeapTuple contuple, bool recurse, bool recursing, - List *changing_conids, LOCKMODE lockmode) { Form_pg_constraint currcon; @@ -12698,7 +12694,6 @@ ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, if (!cmdcon->is_enforced && (!recursing || !rel->rd_rel->relispartition) && ATCheckCheckConstrHasEnforcedParent(conrel, rel, contuple, - changing_conids, &enforced_parentoid)) { if (!recursing) @@ -12725,6 +12720,14 @@ ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, updatecon.is_enforced = target_enforced; AlterConstrUpdateConstraintEntry(&updatecon, conrel, contuple); changed = true; + + /* + * A later descendant must see this change when checking its direct + * parents. The ordered inheritance traversal guarantees that all + * affected parents are processed before their children. + */ + if (!cmdcon->is_enforced) + CommandCounterIncrement(); } /* @@ -12745,55 +12748,38 @@ ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, */ if (!recursing && !currcon->connoinherit) { - Assert(changing_conids == NIL); - - children = find_all_inheritors(RelationGetRelid(rel), - lockmode, NULL); - - /* - * When setting NOT ENFORCED, build the set of equivalent CHECK - * constraints that this command will attempt to change before - * visiting descendants. The root itself has already been checked - * above. - */ - if (!cmdcon->is_enforced) - changing_conids = list_make1_oid(currcon->oid); - - foreach_oid(childoid, children) - { - if (childoid == RelationGetRelid(rel)) - continue; + if (cmdcon->is_enforced) /* - * If we are told not to recurse, there had better not be any - * child tables, because we can't change constraint - * enforceability on the parent unless we have changed - * enforceability for all child. + * ENFORCED does not need to check parents' enforceability, so + * use find_all_inheritors() to tolerate potential inheritance + * cycles. */ - if (!recurse) - ereport(ERROR, - errcode(ERRCODE_INVALID_TABLE_DEFINITION), - errmsg("constraint must be altered on child tables too"), - errhint("Do not specify the ONLY keyword.")); + children = find_all_inheritors(RelationGetRelid(rel), + lockmode, NULL); + else /* - * It is sufficient to look up the constraint by name here. - * Supported DDL ensures that inheritable CHECK constraints - * with the same name have equivalent definitions when they - * are propagated to children or when inheritance is - * established. All descendants returned by - * find_all_inheritors must have this constraint: inherited - * CHECK constraints propagate to all children at - * inheritance-link creation time and cannot be dropped - * independently on child tables. + * NOT ENFORCED needs to check parents' enforceability to + * ensure consistency. This requires each parent to appear + * before its children in the list, so call + * find_all_inheritors_ordered(). If there is an inheritance + * cycle, this will fail. */ - if (!cmdcon->is_enforced) - changing_conids = - list_append_unique_oid(changing_conids, - get_relation_constraint_oid(childoid, - cmdcon->conname, - false)); - } + children = find_all_inheritors_ordered(RelationGetRelid(rel), + lockmode); + + /* + * If we are told not to recurse, there had better not be any + * child tables, because we can't change constraint enforceability + * on the parent unless we have changed enforceability for all + * children. + */ + if (!recurse && list_length(children) > 1) + ereport(ERROR, + errcode(ERRCODE_INVALID_TABLE_DEFINITION), + errmsg("constraint must be altered on child tables too"), + errhint("Do not specify the ONLY keyword.")); } foreach_oid(childoid, children) @@ -12803,7 +12789,6 @@ ATExecAlterCheckConstrEnforceability(List **wqueue, ATAlterConstraint *cmdcon, AlterCheckConstrEnforceabilityRecurse(wqueue, cmdcon, conrel, childoid, false, true, - changing_conids, lockmode); } } @@ -12855,7 +12840,6 @@ static void AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon, Relation conrel, Oid conrelid, bool recurse, bool recursing, - List *changing_conids, LOCKMODE lockmode) { SysScanDesc pscan; @@ -12885,21 +12869,18 @@ AlterCheckConstrEnforceabilityRecurse(List **wqueue, ATAlterConstraint *cmdcon, cmdcon->conname, get_rel_name(conrelid))); ATExecAlterCheckConstrEnforceability(wqueue, cmdcon, conrel, childtup, - recurse, recursing, changing_conids, - lockmode); + recurse, recursing, lockmode); systable_endscan(pscan); } /* * When setting an inherited CHECK constraint to NOT ENFORCED, look for a - * matching parent constraint that remains ENFORCED and is not part of the same - * ALTER. + * matching parent constraint that remains ENFORCED. */ static bool ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel, HeapTuple contuple, - List *changing_conids, Oid *enforced_parentoid) { Form_pg_constraint currcon; @@ -12929,7 +12910,6 @@ ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel, while (HeapTupleIsValid(inheritsTuple = systable_getnext(scan))) { Oid parentoid; - Relation parentrel = NULL; SysScanDesc pscan; ScanKeyData pkey[3]; HeapTuple parenttup; @@ -12973,41 +12953,13 @@ ATCheckCheckConstrHasEnforcedParent(Relation conrel, Relation rel, RelationGetRelationName(rel), NameStr(parentcon->conname)); - /* - * A parent listed in changing_conids is being changed by the same - * ALTER, but it may not have been updated yet. For regular - * inheritance, recurse upward to check whether an equivalent - * enforced parent outside the ALTER will make it remain enforced. - * Partitions cannot have multiple parents, so they do not need - * this check. - */ - if (!rel->rd_rel->relispartition && - list_member_oid(changing_conids, parentcon->oid)) - { - Oid parent_enforced_parentoid = InvalidOid; - - if (parentrel == NULL) - parentrel = table_open(parentoid, NoLock); - - if (!ATCheckCheckConstrHasEnforcedParent(conrel, - parentrel, - parenttup, - changing_conids, - &parent_enforced_parentoid)) - continue; - } - *enforced_parentoid = parentoid; - if (parentrel != NULL) - table_close(parentrel, NoLock); systable_endscan(pscan); systable_endscan(scan); table_close(inhrel, AccessShareLock); return true; } - if (parentrel != NULL) - table_close(parentrel, NoLock); systable_endscan(pscan); } diff --git a/src/include/catalog/pg_inherits.h b/src/include/catalog/pg_inherits.h index cc874abaabb..66a811e50fa 100644 --- a/src/include/catalog/pg_inherits.h +++ b/src/include/catalog/pg_inherits.h @@ -58,6 +58,7 @@ extern List *find_inheritance_children_extended(Oid parentrelId, bool omit_detac extern List *find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents); +extern List *find_all_inheritors_ordered(Oid parentrelId, LOCKMODE lockmode); extern bool has_subclass(Oid relationId); extern bool has_superclass(Oid relationId); extern bool typeInheritsFrom(Oid subclassTypeId, Oid superclassTypeId); diff --git a/src/test/regress/expected/inherit.out b/src/test/regress/expected/inherit.out index 0136aa53c96..38b057a5e8e 100644 --- a/src/test/regress/expected/inherit.out +++ b/src/test/regress/expected/inherit.out @@ -1554,7 +1554,8 @@ drop cascades to table p1_c1 create table gp(a int constraint gp_a_check check (a > 0) enforced); create table p1_c1() inherits (gp); create table p1() inherits (gp); -alter table p1_c1 inherit p1; +create table p2() inherits (p1); +alter table p1_c1 inherit p2; alter table gp alter constraint gp_a_check not enforced; --ok select conname, conenforced, convalidated, conrelid::regclass from pg_constraint @@ -1565,11 +1566,13 @@ order by conrelid::regclass::text collate "C"; gp_a_check | f | f | gp gp_a_check | f | f | p1 gp_a_check | f | f | p1_c1 -(3 rows) + gp_a_check | f | f | p2 +(4 rows) drop table gp cascade; -NOTICE: drop cascades to 2 other objects +NOTICE: drop cascades to 3 other objects DETAIL: drop cascades to table p1 +drop cascades to table p2 drop cascades to table p1_c1 --for "no inherit" check constraint, it will not recurse to child table create table p1(f1 int constraint p1_a_check check (f1 > 0) no inherit not enforced); diff --git a/src/test/regress/sql/inherit.sql b/src/test/regress/sql/inherit.sql index 072fca13c13..db4f4abc709 100644 --- a/src/test/regress/sql/inherit.sql +++ b/src/test/regress/sql/inherit.sql @@ -579,7 +579,8 @@ drop table gp cascade; create table gp(a int constraint gp_a_check check (a > 0) enforced); create table p1_c1() inherits (gp); create table p1() inherits (gp); -alter table p1_c1 inherit p1; +create table p2() inherits (p1); +alter table p1_c1 inherit p2; alter table gp alter constraint gp_a_check not enforced; --ok select conname, conenforced, convalidated, conrelid::regclass from pg_constraint -- 2.50.1 (Apple Git-155) =
^ permalink raw reply [nested|flat] 10+ messages in thread

* Re: Introducing find_all_inheritors_ordered()
@ 2026-09-08 20:42  Zsolt Parragi <zsolt.parragi@percona.com>
  parent: Chao Li <li.evan.chao@gmail.com>
  0 siblings, 0 replies; 10+ messages in thread

From: Zsolt Parragi @ 2026-09-08 20:42 UTC (permalink / raw)
  To: Chao Li <li.evan.chao@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org, Tom Lane <tgl@sss.pgh.pa.us>

On Tue, 08 Sep 2026, Chao Li <li.evan.chao@gmail.com> wrote:
> > Why is it a valid scenario, and how would we reach it? It's going to
> > cause tons of problems if it can happen, so I'd rather put effort into
> > blocking it than making some parts of the system cope.
>
> +1
>
> I can look into if we can prevent concurrent ALTER TABLE ... INHERIT commands from creating cycles at a reasonable cost, and start a separate discussion.

+1 for that, if it is doable, I didn't investigate it further than the
comment's claim that it is too difficult.

I didn't want to say that I think it is a real-usable scenario, I
meant valid as currently reachable (as showcased by the isolation
tester spec I posted), that probably wasn't the best word to describe
it.






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


end of thread, other threads:[~2026-09-08 20:42 UTC | newest]

Thread overview: 10+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-07-30 08:35 Introducing find_all_inheritors_ordered() Chao Li <li.evan.chao@gmail.com>
2026-09-04 07:15 ` solai v <solai.cdac@gmail.com>
2026-09-04 08:20 ` Ewan Young <kdbase.hack@gmail.com>
2026-09-04 21:48   ` Zsolt Parragi <zsolt.parragi@percona.com>
2026-09-07 06:40     ` Chao Li <li.evan.chao@gmail.com>
2026-09-07 22:16       ` Zsolt Parragi <zsolt.parragi@percona.com>
2026-09-07 23:38         ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-08 03:54           ` Chao Li <li.evan.chao@gmail.com>
2026-09-08 20:42             ` Zsolt Parragi <zsolt.parragi@percona.com>
2026-09-08 03:46         ` Chao Li <li.evan.chao@gmail.com>

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