From: Tomas Vondra <tomas.vondra@2ndquadrant.com>
To: Simon Riggs <simon@2ndQuadrant.com>
Cc: David Rowley <david.rowley@2ndquadrant.com>
Cc: Tom Lane <tgl@sss.pgh.pa.us>
Cc: Julien Rouhaud <julien.rouhaud@dalibo.com>
Cc: Michael Paquier <michael.paquier@gmail.com>
Cc: Stefan Huehner <stefan@huehner.org>
Cc: PostgreSQL mailing lists <pgsql-hackers@postgresql.org>
Subject: Re: pg9.6 segfault using simple query (related to use fk for join estimates)
Date: Mon, 9 May 2016 00:24:36 +0200
Message-ID: <23f49b29-6b46-7691-b418-67c05d828f8a@2ndquadrant.com> (raw)
In-Reply-To: <CANP8+jKR3fpUaBwj-sveoag4UPw0iBoLe8MF6+823x3fgUW7BQ@mail.gmail.com>
References: <20160429102531.GA13701@huehner.biz>
<CAB7nPqRj2EsGdoNESsWVC-RHV918Scd1xQEcYt3dK9Rs5RpuAQ@mail.gmail.com>
<572384D7.1020602@dalibo.com>
<17639.1461945908@sss.pgh.pa.us>
<57238E64.8010702@dalibo.com>
<22731.1462037712@sss.pgh.pa.us>
<8344835e-18af-9d40-aed7-bd2261be9162@2ndquadrant.com>
<CAKJS1f9VMZGfPCDWeuLoD1rgvTr5JzGLh7vc4YWQCSDrmRCKbQ@mail.gmail.com>
<CAKJS1f-Eqa23_K1x_jpgVn97TigcTm7RucuD=tpSEpGpLx4ULw@mail.gmail.com>
<16807.1462388069@sss.pgh.pa.us>
<CAKJS1f-5WjfJLu0Y4hnfR01ZCBsd5FrDQ7kz5ayAt1t7DZ5vLQ@mail.gmail.com>
<CAKJS1f8iHbN4KC+=BK=M_UTeCsTsfjqQWBZjN3w9NxqKKfL7dw@mail.gmail.com>
<4cf45f48-5e92-903b-9f29-af5215fdf715@2ndquadrant.com>
<CANP8+jKR3fpUaBwj-sveoag4UPw0iBoLe8MF6+823x3fgUW7BQ@mail.gmail.com>
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-hackers>
Hi,
Attached is a minor revision of the patch posted by David a few days
ago, rebased on the current master (which already includes 68d704 fixing
the segfault that started this thread).
The modifications are fairly small:
* The 'possibleRef' flag is renamed to 'use_for_estimation' which I
think better describes the purpose of the flag.
* The mark_useful_foreign_keys now skips foreign keys on a single
column, as those are not useful for the patch at all. This should
further reduce performance impact in the common case.
* I've slightly reworded some of the comments, hopefully for the better.
But now the bad news - while reviewing the David's fixup patch, I've
noticed this comment
/* XXX do we need to add entries for the append_rel_list here? */
and I've realized that the estimation does not quite work with
partitioned tables, as it only checks foreign keys on the parent tables,
but the child tables may not use the foreign keys at all, or even use
different foreign keys (a bit bizzare, but possible).
Obviously the simplest solution would be to simply stop considering
foreign keys with partitioned tables - that seems a bit unfortunate, but
AFAIK we don't inspect child tables during planning anyway, and in the
worst case we fall back to the current estimate.
It might be possible to improve this by checking that all child tables
have a matching foreign key (referencing the same table), which would
allow us to handle the case with one side partitioned. And maybe some
other (more complex) cases, like equi-partitioned tables. But all of
this would require a fair amount of new code, far more than we should
commit in beta mode.
To summarize all of this, I think David's patch marking usable foreign
keys greatly reduces the overhead compared to the committed version. The
'skip 1-column FKs' significantly reduces (or even eliminates) the
overhead for the common case where only few FKs use multiple columns.
Not handling the inheritance properly is clearly a serious oversight,
though. Tom is clearly right that this got committed a bit too early.
If the conclusion is that the current performance impact is still not
acceptable, or that we need a better solution to the inheritance issue
than simply disabling the FK estimates, then I think reverting the patch
is the only possible solution at this point.
regards
--
Tomas Vondra http://www.2ndQuadrant.com
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services
--
Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-hackersAttachments:fkest_fixes_v2.patch (binary/octet-stream, 10.8K) downloaddiff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.cindex 873a764..105ba68 100644--- a/src/backend/optimizer/path/allpaths.c+++ b/src/backend/optimizer/path/allpaths.c@@ -67,6 +67,7 @@ join_search_hook_type join_search_hook = NULL;
static void set_base_rel_consider_startup(PlannerInfo *root);
static void set_base_rel_sizes(PlannerInfo *root);
static void set_base_rel_pathlists(PlannerInfo *root);
+static void mark_useful_foreign_keys(PlannerInfo *root);
static void set_rel_size(PlannerInfo *root, RelOptInfo *rel,
Index rti, RangeTblEntry *rte);
static void set_rel_pathlist(PlannerInfo *root, RelOptInfo *rel,
@@ -168,6 +169,7 @@ make_one_rel(PlannerInfo *root, List *joinlist)
*/
set_base_rel_sizes(root);
set_base_rel_pathlists(root);
+ mark_useful_foreign_keys(root);
/*
* Generate access paths for the entire join tree.
@@ -301,6 +303,90 @@ set_base_rel_pathlists(PlannerInfo *root)
}
/*
+ * mark_useful_foreign_keys+ * Determine foreign keys that may be useful for improving join estimates.+ *+ * That means both relations referenced by the foreign key must must be part+ * of the query. The function simply builds a hash table of relids of base+ * relations, and then walks through the foreign keys and marks them.+ *+ * The function also ignores foreign keys on a single column, as the primary+ * point of using foreign keys is to improve estimates with joins on multiple+ * columns.+ */+static void+mark_useful_foreign_keys(PlannerInfo *root)+{+ HTAB *htab;+ HASHCTL hash_ctl;+ Index rti;+ ListCell *lc;++ memset(&hash_ctl, 0, sizeof(hash_ctl));+ hash_ctl.keysize = sizeof(Oid);+ hash_ctl.entrysize = sizeof(Oid);+ hash_ctl.hcxt = CurrentMemoryContext;+ htab = hash_create("mark_useful_foreign_keys",+ root->simple_rel_array_size,+ &hash_ctl,+ HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);++ /* build a hash table with all rel OIDs that are in the query */+ for (rti = 1; rti < root->simple_rel_array_size; rti++)+ {+ RelOptInfo *rel = root->simple_rel_array[rti];+ RangeTblEntry *rte;++ if (rel == NULL)+ continue;++ /* ignore RTEs that are "other rels" */+ if (rel->reloptkind != RELOPT_BASEREL)+ continue;++ rte = root->simple_rte_array[rti];++ (void) hash_search(htab, (void *) &(rte->relid), HASH_ENTER, NULL);+ }++ /* XXX do we need to add entries for the append_rel_list here? */++ /*+ * Now go over each rel and set each foreign key's 'use_for_estimates' flag+ * according to if the FKs confrelid was found to be in the query or not+ * (conrelid matches the current relation, so we don't need to check it).+ */+ for (rti = 1; rti < root->simple_rel_array_size; rti++)+ {+ RelOptInfo *rel = root->simple_rel_array[rti];++ if (rel == NULL)+ continue;++ /* ignore RTEs that are "other rels" */+ if (rel->reloptkind != RELOPT_BASEREL)+ continue;++ foreach(lc, rel->fkeylist)+ {+ ForeignKeyOptInfo *fkinfo = (ForeignKeyOptInfo *) lfirst(lc);+ bool found;++ /* ignore single-column FKs (only those with multiple cols matter) */+ if (fkinfo->nkeys == 1)+ continue;++ hash_search(htab, (void *) &(fkinfo->confrelid), HASH_FIND, &found);+ if (found)+ fkinfo->use_for_estimates = true;+ }+ }++ /* Done with the hash table. */+ hash_destroy(htab);+}++/*
* set_rel_size
* Set size estimates for a base relation
*/
diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.cindex 4c9d8d9..030596c 100644--- a/src/backend/optimizer/path/costsize.c+++ b/src/backend/optimizer/path/costsize.c@@ -3913,16 +3913,19 @@ quals_match_foreign_key(PlannerInfo *root, ForeignKeyOptInfo *fkinfo,
Bitmapset *fkmatches = NULL;
/*
- * Loop over each column of the foreign key and build a bitmapset- * of each joinqual which matches. Note that we don't stop when we find- * the first match, as the expression could be duplicated in the- * joinquals, and we want to generate a bitmapset which has bits set for- * every matching join qual.+ * Loop over each column of the foreign key and build a 0-based bitmapset+ * of the list position of each joinqual which matches the foreign key. We+ * also maintain the fkmatches bitmapsets to mark which keys have been+ * matched. We must do this rather than maintain a simple count of the+ * number of keys matched in order to determine at the end of all the keys+ * were matched, a count is not good enough as it's possible to match to+ * the same key more than once with duplicated join conditions.
*/
for (i = 0; i < nkeys; i++)
{
ListCell *lc;
int quallstidx = -1;
+ bool found = false;
foreach(lc, joinquals)
{
@@ -3953,9 +3956,12 @@ quals_match_foreign_key(PlannerInfo *root, ForeignKeyOptInfo *fkinfo,
/*
* If the operator does not match then there's little point in
- * checking the operands.+ * checking the operands. We must also check for the commutative+ * operator since the condition could be the reverse of the+ * foreign key relationship.
*/
- if (clause->opno != fkinfo->conpfeqop[i])+ if ((clause->opno != fkinfo->conpfeqop[i]) ||+ (get_commutator(clause->opno) != fkinfo->conpfeqop[i]))
continue;
leftvar = (Var *) get_leftop((Expr *) clause);
@@ -3970,8 +3976,8 @@ quals_match_foreign_key(PlannerInfo *root, ForeignKeyOptInfo *fkinfo,
* member of the eclass as rinfo's operands may not belong to the
* foreign key. For efficient tracking of which Vars we've found,
* since we're only tracking 2 Vars, we use a bitmask. We can
- * safely finish searching when both of the least significant bits- * are set.+ * safely finish searching when the two least significant bits are+ * set.
*/
if (rinfo->parent_ec)
{
@@ -4004,6 +4010,7 @@ quals_match_foreign_key(PlannerInfo *root, ForeignKeyOptInfo *fkinfo,
{
qualmatches = bms_add_member(qualmatches, quallstidx);
fkmatches = bms_add_member(fkmatches, i);
+ found = true;
break;
}
}
@@ -4023,6 +4030,7 @@ quals_match_foreign_key(PlannerInfo *root, ForeignKeyOptInfo *fkinfo,
{
qualmatches = bms_add_member(qualmatches, quallstidx);
fkmatches = bms_add_member(fkmatches, i);
+ found = true;
}
else if ((foreignrel->relid == rightvar->varno) &&
(fkrel->relid == leftvar->varno) &&
@@ -4031,9 +4039,18 @@ quals_match_foreign_key(PlannerInfo *root, ForeignKeyOptInfo *fkinfo,
{
qualmatches = bms_add_member(qualmatches, quallstidx);
fkmatches = bms_add_member(fkmatches, i);
+ found = true;
}
}
}
++ /*+ * If any key was not found, then we need not bother searching any+ * further. We'll just break out of the loop and let the code below+ * clean up for us.+ */+ if (!found)+ break;
}
/* can't find more matches than columns in the foreign key */
@@ -4099,6 +4116,13 @@ find_best_foreign_key_quals(PlannerInfo *root, RelOptInfo *fkrel,
Bitmapset *qualsmatched;
/*
+ * Skip any foreign keys where we determined the referenced rel was+ * not part of this query.+ */+ if (!fkinfo->use_for_estimates)+ continue;++ /*
* We make no attempt in checking that this foreign key actually
* references 'foreignrel', the reasoning here is that we may be able
* to match the foreign key to an eclass member Var of a RestrictInfo
@@ -4164,8 +4188,13 @@ clauselist_join_selectivity(PlannerInfo *root, List *joinquals,
int outermatches;
/*
- * check which quals are matched by a foreign key referencing the- * innerrel.+ * Attempt to find the "best matching" foreign key which backs up+ * the join condition. Here we define the "best match" as the+ * foreign key with the most keys. We must perform this search+ * twice; once for FKs where outerrel referencing innerrel, and+ * also the reverse of that.We can perform simply by calling+ * find_best_foreign_key_quals() twice and swapping the input+ * parameters.
*/
outermatches = find_best_foreign_key_quals(root, outerrel,
innerrel, joinquals, &outer2inner);
@@ -4175,15 +4204,25 @@ clauselist_join_selectivity(PlannerInfo *root, List *joinquals,
outerrel, joinquals, &inner2outer);
/*
- * did we find any matches at all? If so we need to see which one is- * the best/longest match+ * Check if we found any matches at all and use that match. It's+ * perhaps unlikely that a foreign key exists in both directions,+ * but we'll handle that case, and just take the longer of the+ * two. If both matches happen to be the same length, then we'll+ * prefer the inner2outer match, there's little reason for this,+ * we simply need to pick something.
*/
if (outermatches != 0 || innermatches != 0)
{
double referenced_tuples;
bool overlap;
- /* either could be zero, but not both. */+ /*+ * Determine the best match and add the quals belonging to the+ * match to the bitmap of quals found so far. We'll also check+ * for any quals which were already matched to a foreign key+ * by an earlier check as this determines if we must take into+ * account the existing selectivity or start from scratch.+ */
if (outermatches < innermatches)
{
overlap = bms_overlap(foundfkquals, inner2outer);
@@ -4199,14 +4238,10 @@ clauselist_join_selectivity(PlannerInfo *root, List *joinquals,
referenced_tuples = Max(innerrel->tuples, 1.0);
}
- /*- * XXX should we ignore these overlapping matches?- * Or perhaps take the Max() or Min()?- */
if (overlap)
{
if (jointype == JOIN_SEMI || jointype == JOIN_ANTI)
- sel = Min(sel,Min(1.0 / (outerrel->tuples / Max(innerrel->tuples, 1.0)), 1.0));+ sel = Min(sel, Min(1.0 / (outerrel->tuples / Max(innerrel->tuples, 1.0)), 1.0));
else
sel = Min(sel, 1.0 / referenced_tuples);
}
diff --git a/src/include/nodes/relation.h b/src/include/nodes/relation.hindex 45739c3..d21fffb 100644--- a/src/include/nodes/relation.h+++ b/src/include/nodes/relation.h@@ -642,7 +642,7 @@ typedef struct ForeignKeyOptInfo
int *conkeys; /* attnums of columns in the constrained table */
int *confkeys; /* attnums of columns in the referenced table */
Oid *conpfeqop; /* OIDs of equality operators used by the FK */
-+ bool use_for_estimates; /* both relations are in the query */
} ForeignKeyOptInfo;
/*
diff --git a/src/include/optimizer/paths.h b/src/include/optimizer/paths.hindex e0ac451..f3b25e2 100644--- a/src/include/optimizer/paths.h+++ b/src/include/optimizer/paths.h@@ -76,8 +76,6 @@ extern Expr *adjust_rowcompare_for_index(RowCompareExpr *clause,
int indexcol,
List **indexcolnos,
bool *var_on_left_p);
-extern bool has_matching_fkey(RelOptInfo *rel, RelOptInfo *frel, List *clauses,- bool reverse);
/*
* tidpath.h
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-hackers@postgresql.org
Cc: tomas.vondra@2ndquadrant.com, simon@2ndQuadrant.com, david.rowley@2ndquadrant.com, tgl@sss.pgh.pa.us, julien.rouhaud@dalibo.com, michael.paquier@gmail.com, stefan@huehner.org
Subject: Re: pg9.6 segfault using simple query (related to use fk for join estimates)
In-Reply-To: <23f49b29-6b46-7691-b418-67c05d828f8a@2ndquadrant.com>
References: <20160429102531.GA13701@huehner.biz> <CAB7nPqRj2EsGdoNESsWVC-RHV918Scd1xQEcYt3dK9Rs5RpuAQ@mail.gmail.com> <572384D7.1020602@dalibo.com> <17639.1461945908@sss.pgh.pa.us> <57238E64.8010702@dalibo.com> <22731.1462037712@sss.pgh.pa.us> <8344835e-18af-9d40-aed7-bd2261be9162@2ndquadrant.com> <CAKJS1f9VMZGfPCDWeuLoD1rgvTr5JzGLh7vc4YWQCSDrmRCKbQ@mail.gmail.com> <CAKJS1f-Eqa23_K1x_jpgVn97TigcTm7RucuD=tpSEpGpLx4ULw@mail.gmail.com> <16807.1462388069@sss.pgh.pa.us> <CAKJS1f-5WjfJLu0Y4hnfR01ZCBsd5FrDQ7kz5ayAt1t7DZ5vLQ@mail.gmail.com> <CAKJS1f8iHbN4KC+=BK=M_UTeCsTsfjqQWBZjN3w9NxqKKfL7dw@mail.gmail.com> <4cf45f48-5e92-903b-9f29-af5215fdf715@2ndquadrant.com> <CANP8+jKR3fpUaBwj-sveoag4UPw0iBoLe8MF6+823x3fgUW7BQ@mail.gmail.com> <23f49b29-6b46-7691-b418-67c05d828f8a@2ndquadrant.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
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