Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.84_2) (envelope-from ) id 1azX85-00025m-LC for pgsql-hackers@arkaria.postgresql.org; Sun, 08 May 2016 22:24:49 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.84_2) (envelope-from ) id 1azX85-0000Vn-8J for pgsql-hackers@arkaria.postgresql.org; Sun, 08 May 2016 22:24:49 +0000 Received: from makus.postgresql.org ([2001:4800:1501:1::229]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84_2) (envelope-from ) id 1azX81-0000SB-3k for pgsql-hackers@postgresql.org; Sun, 08 May 2016 22:24:45 +0000 Received: from mail-wm0-x230.google.com ([2a00:1450:400c:c09::230]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.84_2) (envelope-from ) id 1azX7x-0006pT-CS for pgsql-hackers@postgresql.org; Sun, 08 May 2016 22:24:43 +0000 Received: by mail-wm0-x230.google.com with SMTP id a17so158062398wme.0 for ; Sun, 08 May 2016 15:24:40 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=2ndquadrant-com.20150623.gappssmtp.com; s=20150623; h=subject:to:references:cc:from:message-id:date:user-agent :mime-version:in-reply-to; bh=b1QBWnxuBARSXTw4ly3J/CbJK0KF46Lm+KFCWATCjHw=; b=aJIskb8C9NupeJIz0OhUznrDa/dMif1koG6Yzp47+LX0NxLDSU+p/AnXbkTRriU2gS yVpWDGQMTtRp1vDyALGyz4A1qpdvKPZtIjsgYnhZFrCwwEeKlG+42+WSIRTGxcdyZPZX jLvcOjsPCP/pZvfseQ6pYl7v722kMAwYkc8aFHTxf6b34j7t9jDtDMlXHhoRxgaMaswr E7+9MBz2AEPwd19Z4C7Oe0HdcalY5OdvBoIL/Gdw571oH44xWGptr9hIjjfdqya6RNvi +1T8PtFwp0cJN7qeakBtJCu8mveMGIiVoyiiUR275zZ4Wvckg8LYa27RwRWjj4V4DjPS YylA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20130820; h=x-gm-message-state:subject:to:references:cc:from:message-id:date :user-agent:mime-version:in-reply-to; bh=b1QBWnxuBARSXTw4ly3J/CbJK0KF46Lm+KFCWATCjHw=; b=d+p4qiq+fOHubT+Ou7e72UsCaWziXqwuFOD7eaxZJvOAI9EUpbwLs5TzjjSYOYVMuD WE+mKO3DCIF3bpnV5IpnhdWrHiDr+VuNtxYJkHFHGjfEZ8kXc7RndNpbIBPqzhWn0pw/ u/z1IztIhl/maFjoAfZfYUXeofOFRH9PbJXNXjENCgE9o9kaRaYteFsYPszM6Jm8AK8V 4KnenfhGb4t5Z6pnb14noW1uaG5JRf98UNp3brmZLZacDI2IaNbi8jRy/dQAdw6626wG n01p29trQNCK0kH17NjUjFGZnDLRPD87WVzHv+kDY9P+83Uv1Lj1+9802oAlTjl+wsBK 5myA== X-Gm-Message-State: AOPr4FWwQDkhKdVdIGq5Npj30iTa6yMrYOC55gJVHCPu5XpNCFKSoobUjMagqKnCrmWSdV6c1zBkjrAj71ToEWSdyLIiTU8pOzXsKdcS/zj1kRlDrPur1djh73i6TOmuJplnRK3FQUcOZ8Z2ciBQKLoYbyTOvtJt1/MWkpjZtZxLN+pnhtdrPGMyns/kY9MYdxx0ocIAorSZ X-Received: by 10.28.223.86 with SMTP id w83mr7908300wmg.95.1462746279042; Sun, 08 May 2016 15:24:39 -0700 (PDT) Received: from [10.137.2.17] (ip-89-177-44-58.net.upcbroadband.cz. [89.177.44.58]) by smtp.gmail.com with ESMTPSA id jq1sm27519401wjc.28.2016.05.08.15.24.37 (version=TLSv1/SSLv3 cipher=OTHER); Sun, 08 May 2016 15:24:37 -0700 (PDT) Subject: Re: pg9.6 segfault using simple query (related to use fk for join estimates) To: Simon Riggs References: <20160429102531.GA13701@huehner.biz> <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> <16807.1462388069@sss.pgh.pa.us> <4cf45f48-5e92-903b-9f29-af5215fdf715@2ndquadrant.com> Cc: David Rowley , Tom Lane , Julien Rouhaud , Michael Paquier , Stefan Huehner , PostgreSQL mailing lists From: Tomas Vondra Message-ID: <23f49b29-6b46-7691-b418-67c05d828f8a@2ndquadrant.com> Date: Mon, 9 May 2016 00:24:36 +0200 User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:46.0) Gecko/20100101 Thunderbird/46.0a2 MIME-Version: 1.0 In-Reply-To: Content-Type: multipart/mixed; boundary="------------0E456CD446E139AAE5FB1B65" X-Pg-Spam-Score: -2.6 (--) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-hackers Precedence: bulk Sender: pgsql-hackers-owner@postgresql.org This is a multi-part message in MIME format. --------------0E456CD446E139AAE5FB1B65 Content-Type: text/plain; charset=utf-8; format=flowed Content-Transfer-Encoding: 7bit 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 --------------0E456CD446E139AAE5FB1B65 Content-Type: binary/octet-stream; name="fkest_fixes_v2.patch" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename="fkest_fixes_v2.patch" diff --git a/src/backend/optimizer/path/allpaths.c b/src/backend/optimizer/path/allpaths.c index 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.c index 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.h index 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.h index 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 --------------0E456CD446E139AAE5FB1B65 Content-Type: text/plain Content-Disposition: inline Content-Transfer-Encoding: 8bit MIME-Version: 1.0 -- Sent via pgsql-hackers mailing list (pgsql-hackers@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-hackers --------------0E456CD446E139AAE5FB1B65--