threads
listlengths
1
2.99k
[ { "msg_contents": "Hi,\n\nI'm not subscribed to the list, so please include me directly if you want my attention. This is a \"drive-by\" patch as it were.\n\nAttached is a minor patch to fix the name param documentation for create role, just adding a direct quote from user-manag.sgml talking about what the role name is allowed to be. I was searching for this information and figured the reference page should have it as well.\n\nHope this helps,\n-Tara", "msg_date": "Sat, 17 Aug 2019 04:17:07 +0000", "msg_from": "tara@anne.cat", "msg_from_op": true, "msg_subject": "[PATCH] minor doc fix for create-role" }, { "msg_contents": "tara@anne.cat writes:\n> Attached is a minor patch to fix the name param documentation for create role, just adding a direct quote from user-manag.sgml talking about what the role name is allowed to be. I was searching for this information and figured the reference page should have it as well.\n\nHm, I guess my reaction to this proposal is \"why just here?\". We have\nan awful lot of different CREATE commands, and none of them say more\nabout the target name than this one does. (Not to mention ALTER, DROP,\netc.) Perhaps it's worth adding some boilerplate text to all those\nplaces, but I'm dubious.\n\nAlso, the specific text proposed for addition doesn't seem that helpful,\nsince it doesn't define which characters are \"special characters\".\nI'd rather see something like \"The name must be a valid SQL identifier\nas defined in <link to section 4.1.1>.\" But, while that would work fine\nin HTML output, it would not be particularly short or useful in man-page\noutput.\n\nPerhaps the ideal solution would be further markup on the synopsis\nsections that somehow identifies each term as an \"identifier\" or\nother appropriate syntactic category, and provides a hyperlink to\na definition (in output formats that are friendly to that). Seems\nlike a lot of work though :-(\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 18 Aug 2019 12:41:23 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] minor doc fix for create-role" }, { "msg_contents": "Hi Tom,\n\nI agree mostly. It actually does have the words “SQL identifier” in the patch. But you are right it doesn’t link to what a SQL identifier is, but it does provide a practical solution of quoting. That was the part I cared about as a user, I just wanted to solve my problem of an email address as a role name (yes I know that’s sort of dumb as email addresses change). This also addresses the question, why just here, because this was a pain point in the docs for me yesterday :)\n\n I also agree your ideal solution is definitely better than what I pushed. But I’m not ready to take that on. If someone else is, I welcome their patch over mine.\n\n-Tara\n\n —\n“Rivers know this: there is no hurry. We shall get there some day.”\n\n> On Aug 18, 2019, at 9:41 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> tara@anne.cat writes:\n>> Attached is a minor patch to fix the name param documentation for create role, just adding a direct quote from user-manag.sgml talking about what the role name is allowed to be. I was searching for this information and figured the reference page should have it as well.\n> \n> Hm, I guess my reaction to this proposal is \"why just here?\". We have\n> an awful lot of different CREATE commands, and none of them say more\n> about the target name than this one does. (Not to mention ALTER, DROP,\n> etc.) Perhaps it's worth adding some boilerplate text to all those\n> places, but I'm dubious.\n> \n> Also, the specific text proposed for addition doesn't seem that helpful,\n> since it doesn't define which characters are \"special characters\".\n> I'd rather see something like \"The name must be a valid SQL identifier\n> as defined in <link to section 4.1.1>.\" But, while that would work fine\n> in HTML output, it would not be particularly short or useful in man-page\n> output.\n> \n> Perhaps the ideal solution would be further markup on the synopsis\n> sections that somehow identifies each term as an \"identifier\" or\n> other appropriate syntactic category, and provides a hyperlink to\n> a definition (in output formats that are friendly to that). Seems\n> like a lot of work though :-(\n> \n> regards, tom lane\n\n\n\n", "msg_date": "Sun, 18 Aug 2019 18:00:46 -0700", "msg_from": "Tara Anne <tara@anne.cat>", "msg_from_op": false, "msg_subject": "Re: [PATCH] minor doc fix for create-role" } ]
[ { "msg_contents": "I was a bit confused by some of the comments around the SCRAM function\nread_any_attr(), used to skip over extensions.\n\nThe comment \"Returns NULL if there is attribute.\", besides being\nstrangely worded, appears to be wrong anyway, because the function never\nreturns NULL.\n\nThis lead me to wonder how this loop would terminate if there is no \"p\"\nattribute in the message:\n\n /* ignore optional extensions */\n do\n {\n proof = p - 1;\n value = read_any_attr(&p, &attr);\n } while (attr != 'p');\n\nWhat actually happens is\n\nERROR: malformed SCRAM message\nDETAIL: Attribute expected, but found invalid character \"0x00\".\n\nwhich serves the purpose but was probably not quite intended that way.\n\nI propose the attached patch to clean this up a bit, with better\ncomments and a better error message.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Sat, 17 Aug 2019 10:11:27 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "some SCRAM read_any_attr() confusion" }, { "msg_contents": "On Sat, Aug 17, 2019 at 10:11:27AM +0200, Peter Eisentraut wrote:\n> I was a bit confused by some of the comments around the SCRAM function\n> read_any_attr(), used to skip over extensions.\n> \n> The comment \"Returns NULL if there is attribute.\", besides being\n> strangely worded, appears to be wrong anyway, because the function never\n> returns NULL.\n\nThis may have come from an incorrect merge with a past version when\nthis code has been developed. +1 for me for your suggestions and your\npatch.\n--\nMichael", "msg_date": "Sat, 17 Aug 2019 21:57:50 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: some SCRAM read_any_attr() confusion" }, { "msg_contents": "On 2019-08-17 14:57, Michael Paquier wrote:\n> On Sat, Aug 17, 2019 at 10:11:27AM +0200, Peter Eisentraut wrote:\n>> I was a bit confused by some of the comments around the SCRAM function\n>> read_any_attr(), used to skip over extensions.\n>>\n>> The comment \"Returns NULL if there is attribute.\", besides being\n>> strangely worded, appears to be wrong anyway, because the function never\n>> returns NULL.\n> \n> This may have come from an incorrect merge with a past version when\n> this code has been developed. +1 for me for your suggestions and your\n> patch.\n\ncommitted\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 21 Aug 2019 09:18:50 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: some SCRAM read_any_attr() confusion" } ]
[ { "msg_contents": "Hello,\n\nattached you find a patch that adds a new GUC:\n\nprepared_statement_limit:\n\n         Specifies the maximum amount of memory used in each session to \ncache\n         parsed-and-rewritten queries and execution plans. This affects \nthe maximum memory\n         a backend threads will reserve when many prepared statements \nare used.\n         The default value of 0 disables this setting, but it is \nrecommended to set this\n         value to a bit lower than the maximum memory a backend worker \nthread should reserve\n         permanently.\n\nIf the GUC is configured after each save of a CachedPlanSource, or after \ncreating a CachedPlan from it, the function \nEnforcePreparedStatementLimit is called now. It checks the mem usage of \nthe existing saved CachedPlanSources and invalidates the query_list and \nthe gplan if available until the memory limit is met again.\n\nCachedPlanSource are removed-and-tailadded in the saved_plan_list \neverytime GetCachedPlan is called on them so it can be used as a LRU list.\n\nI also reworked ResetPlanCache, PlanCacheRelCallback and \nPlanCacheObjectCallback a bit so when a CachedPlanSource is invalidated \nthe query_list is not only marked as invalid but it is also fully \nreleased to free memory here.\n\nRegards,\nDaniel Migowski\n\nPS@Konstantin: This patch also includes the CachedPlanMemoryUsage \nfunction you like, maybe you like the review the patch for me?", "msg_date": "Sat, 17 Aug 2019 15:57:47 +0200", "msg_from": "Daniel Migowski <dmigowski@ikoffice.de>", "msg_from_op": true, "msg_subject": "Patch: New GUC prepared_statement_limit to limit memory used by\n prepared statements" }, { "msg_contents": "On Sat, Aug 17, 2019 at 6:58 PM Daniel Migowski <dmigowski@ikoffice.de>\nwrote:\n\n> Hello,\n>\n> attached you find a patch that adds a new GUC:\n>\n\nQuick questions before looking at the patch.\n\n>\n> prepared_statement_limit:\n>\n> - Do we have a consensus about the name of GUC? I don't think it is\nthe right name for that.\n\n - Is this a WIP patch or the final patch? Because I can see TODO and\nnon-standard\ncomments in the patch.\n\n\n\n> Specifies the maximum amount of memory used in each session to\n> cache\n> parsed-and-rewritten queries and execution plans. This affects\n> the maximum memory\n> a backend threads will reserve when many prepared statements\n> are used.\n> The default value of 0 disables this setting, but it is\n> recommended to set this\n> value to a bit lower than the maximum memory a backend worker\n> thread should reserve\n> permanently.\n>\n> If the GUC is configured after each save of a CachedPlanSource, or after\n> creating a CachedPlan from it, the function\n> EnforcePreparedStatementLimit is called now. It checks the mem usage of\n> the existing saved CachedPlanSources and invalidates the query_list and\n> the gplan if available until the memory limit is met again.\n>\n> CachedPlanSource are removed-and-tailadded in the saved_plan_list\n> everytime GetCachedPlan is called on them so it can be used as a LRU list.\n>\n> I also reworked ResetPlanCache, PlanCacheRelCallback and\n> PlanCacheObjectCallback a bit so when a CachedPlanSource is invalidated\n> the query_list is not only marked as invalid but it is also fully\n> released to free memory here.\n>\n> Regards,\n> Daniel Migowski\n>\n> PS@Konstantin: This patch also includes the CachedPlanMemoryUsage\n> function you like, maybe you like the review the patch for me?\n>\n>\n\n\n\n-- \nIbrar Ahmed\n\nOn Sat, Aug 17, 2019 at 6:58 PM Daniel Migowski <dmigowski@ikoffice.de> wrote:Hello,\n\nattached you find a patch that adds a new GUC:Quick questions before looking at the patch. \n\nprepared_statement_limit:\n - Do we have a consensus about the name of GUC? I don't think it isthe right name for that.  - Is this a WIP patch or the final patch? Because I can see TODO and non-standardcomments in the patch. \n         Specifies the maximum amount of memory used in each session to \ncache\n         parsed-and-rewritten queries and execution plans. This affects \nthe maximum memory\n         a backend threads will reserve when many prepared statements \nare used.\n         The default value of 0 disables this setting, but it is \nrecommended to set this\n         value to a bit lower than the maximum memory a backend worker \nthread should reserve\n         permanently.\n\nIf the GUC is configured after each save of a CachedPlanSource, or after \ncreating a CachedPlan from it, the function \nEnforcePreparedStatementLimit is called now. It checks the mem usage of \nthe existing saved CachedPlanSources and invalidates the query_list and \nthe gplan if available until the memory limit is met again.\n\nCachedPlanSource are removed-and-tailadded in the saved_plan_list \neverytime GetCachedPlan is called on them so it can be used as a LRU list.\n\nI also reworked ResetPlanCache, PlanCacheRelCallback and \nPlanCacheObjectCallback a bit so when a CachedPlanSource is invalidated \nthe query_list is not only marked as invalid but it is also fully \nreleased to free memory here.\n\nRegards,\nDaniel Migowski\n\nPS@Konstantin: This patch also includes the CachedPlanMemoryUsage \nfunction you like, maybe you like the review the patch for me?\n -- Ibrar Ahmed", "msg_date": "Sat, 17 Aug 2019 22:10:45 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Patch: New GUC prepared_statement_limit to limit memory used by\n prepared statements" }, { "msg_contents": "Am 17.08.2019 um 19:10 schrieb Ibrar Ahmed:\n> On Sat, Aug 17, 2019 at 6:58 PM Daniel Migowski <dmigowski@ikoffice.de \n> <mailto:dmigowski@ikoffice.de>> wrote:\n>\n>\n> attached you find a patch that adds a new GUC:\n>\n>\n> Quick questions before looking at the patch.\n>\n>\n> prepared_statement_limit:\n>\n>  - Do we have a consensus about the name of GUC? I don't think it is\n> the right name for that.\nNo, it is a proposal. It could also be named plancache_mem or \ncachedplansource_maxmem or anything else. It was intended to make \nprepared statements not use up all my mem, but development has shown \nthat it could also be used for other CachedPlans, as long as it is a \nsaved plan.\n>  - Is this a WIP patch or the final patch? Because I can see TODO and \n> non-standard\n> comments in the patch.\n\nDefinitely work in progress! The current implementation seems to work \nfor me, but might be improved, but I wanted some input from the mailing \nlist before I optimize things.\n\nThe most important question is, if such a feature would find some love \nhere. Personally it is essential for me because a single prepared \nstatement uses up to 45MB in my application and there were cases where \nORM-generated prepared statememts would crash my server after some time.\n\nThen I would like to know if the current implementation would at least \nnot crash (even it might by slow a bit) or if I have to take more care \nfor locking in some places. I believe a backend is a single thread of \nexecution but there were notes of invalidation messages that seem to be \nrun asynchronously to the main thread. Could someone care to explain the \ntreading model of a single backend to me? Does it react so signals and \nwhat would those signals change? Can I assume that only the \nResetPlanCache, PlanCacheRelCallback and PlanCacheObjectCallback will be \ncalled async?\n\n>          Specifies the maximum amount of memory used in each\n> session to\n> cache\n>          parsed-and-rewritten queries and execution plans. This\n> affects\n> the maximum memory\n>          a backend threads will reserve when many prepared statements\n> are used.\n>          The default value of 0 disables this setting, but it is\n> recommended to set this\n>          value to a bit lower than the maximum memory a backend\n> worker\n> thread should reserve\n>          permanently.\n>\n> If the GUC is configured after each save of a CachedPlanSource, or\n> after\n> creating a CachedPlan from it, the function\n> EnforcePreparedStatementLimit is called now. It checks the mem\n> usage of\n> the existing saved CachedPlanSources and invalidates the\n> query_list and\n> the gplan if available until the memory limit is met again.\n>\n> CachedPlanSource are removed-and-tailadded in the saved_plan_list\n> everytime GetCachedPlan is called on them so it can be used as a\n> LRU list.\n>\nCould be a single move-to-tail function I would add.\n>\n> I also reworked ResetPlanCache, PlanCacheRelCallback and\n> PlanCacheObjectCallback a bit so when a CachedPlanSource is\n> invalidated\n> the query_list is not only marked as invalid but it is also fully\n> released to free memory here.\n>\nBecause this seems to work I was able to reuse the new ReleaseQueryList \nin my implementation.\n>\n>\n> Regards,\n> Daniel Migowski\n>\n> PS@Konstantin: This patch also includes the CachedPlanMemoryUsage\n> function you like, maybe you like the review the patch for me?\n>\n> -- \n> Ibrar Ahmed\nDaniel Migowski\n\n\n\n\n\n\nAm 17.08.2019 um 19:10 schrieb Ibrar\n Ahmed:\n\n\n\nOn Sat, Aug 17, 2019 at 6:58 PM Daniel Migowski\n <dmigowski@ikoffice.de> wrote:\n\n\n\n attached you find a patch that adds a new GUC:\n\n\n\nQuick questions before looking at the patch. \n\n\n prepared_statement_limit:\n\n\n - Do we have a consensus about the name of GUC? I don't\n think it is\nthe right name for that. \n\n\n\n\n No, it is a proposal. It could also be named plancache_mem or\n cachedplansource_maxmem or anything else. It was intended to make\n prepared statements not use up all my mem, but development has shown\n that it could also be used for other CachedPlans, as long as it is a\n saved plan.\n\n\n\n - Is this a WIP patch or the final patch? Because I can\n see TODO and non-standard\ncomments in the patch.\n\n\n\nDefinitely work in progress! The current implementation seems to\n work for me, but might be improved, but I wanted some input from\n the mailing list before I optimize things. \n\nThe most important question is, if such a feature would find some\n love here. Personally it is essential for me because a single\n prepared statement uses up to 45MB in my application and there\n were cases where ORM-generated prepared statememts would crash my\n server after some time.\nThen I would like to know if the current implementation would at\n least not crash (even it might by slow a bit) or if I have to take\n more care for locking in some places. I believe a backend is a\n single thread of execution but there were notes of invalidation\n messages that seem to be run asynchronously to the main thread.\n Could someone care to explain the treading model of a single\n backend to me? Does it react so signals and what would those\n signals change? Can I assume that only the ResetPlanCache,\n PlanCacheRelCallback and PlanCacheObjectCallback will be called\n async? \n\n\n\n\n \n\n          Specifies the maximum amount of memory used in each\n session to \n cache\n          parsed-and-rewritten queries and execution plans.\n This affects \n the maximum memory\n          a backend threads will reserve when many prepared\n statements \n are used.\n          The default value of 0 disables this setting, but\n it is \n recommended to set this\n          value to a bit lower than the maximum memory a\n backend worker \n thread should reserve\n          permanently.\n\n If the GUC is configured after each save of a\n CachedPlanSource, or after \n creating a CachedPlan from it, the function \n EnforcePreparedStatementLimit is called now. It checks the\n mem usage of \n the existing saved CachedPlanSources and invalidates the\n query_list and \n the gplan if available until the memory limit is met again.\n\n CachedPlanSource are removed-and-tailadded in the\n saved_plan_list \n everytime GetCachedPlan is called on them so it can be used\n as a LRU list.\n\n\n\n\n Could be a single move-to-tail function I would add.\n\n\n\n\n I also reworked ResetPlanCache, PlanCacheRelCallback and \n PlanCacheObjectCallback a bit so when a CachedPlanSource is\n invalidated \n the query_list is not only marked as invalid but it is also\n fully \n released to free memory here.\n\n\n\n\n Because this seems to work I was able to reuse the new\n ReleaseQueryList in my implementation.\n\n\n\n\n\n Regards,\n Daniel Migowski\n\n PS@Konstantin: This patch also includes the\n CachedPlanMemoryUsage \n function you like, maybe you like the review the patch for\n me?\n\n\n -- \n\n\nIbrar Ahmed\n\n\n\n\n Daniel Migowski", "msg_date": "Sun, 18 Aug 2019 09:43:09 +0200", "msg_from": "Daniel Migowski <dmigowski@ikoffice.de>", "msg_from_op": true, "msg_subject": "Re: Patch: New GUC prepared_statement_limit to limit memory used by\n prepared statements" }, { "msg_contents": "Hello,\n\nAt Sun, 18 Aug 2019 09:43:09 +0200, Daniel Migowski <dmigowski@ikoffice.de> wrote in <6e25ca12-9484-8994-a1ee-40fdbe6afa8b@ikoffice.de>\n> Am 17.08.2019 um 19:10 schrieb Ibrar Ahmed:\n> > On Sat, Aug 17, 2019 at 6:58 PM Daniel Migowski <dmigowski@ikoffice.de\n> > <mailto:dmigowski@ikoffice.de>> wrote:\n> >\n> >\n> > attached you find a patch that adds a new GUC:\n> >\n> >\n> > Quick questions before looking at the patch.\n> >\n> >\n> > prepared_statement_limit:\n> >\n> >  - Do we have a consensus about the name of GUC? I don't think it is\n> > the right name for that.\n\nThe almost same was proposed [1] as a part of syscache-pruning\npatch [2], but removed to concentrate on defining how to do that\non the first instance - syscache. We have some mechanisms that\nhave the same characteristics - can be bloat and no means to keep\nit in a certain size. It is better that they are treated the same\nway, or at leaast on the same principle.\n\n[1] https://www.postgresql.org/message-id/20180315.141246.130742928.horiguchi.kyotaro%40lab.ntt.co.jp\n[2] https://commitfest.postgresql.org/23/931/\n\nPruning plancaches in any means is valuable, but we haven't\nreached a concsensus on how to do that. My old patch does that\nbased on the number of entries because precise memory accounting\nof memory contexts is too expensive. I didn't look this patch\ncloser but it seems to use MemoryContext->methods->stats to count\nmemory usage, which would be too expensive for the purpose. We\ncurrently use it only for debug output on critical errors like\nOOM.\n\n> No, it is a proposal. It could also be named plancache_mem or\n> cachedplansource_maxmem or anything else. It was intended to make\n> prepared statements not use up all my mem, but development has shown\n> that it could also be used for other CachedPlans, as long as it is a\n> saved plan.\n> >  - Is this a WIP patch or the final patch? Because I can see TODO and\n> > non-standard\n> > comments in the patch.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Mon, 19 Aug 2019 12:57:22 +0900 (Tokyo Standard Time)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Patch: New GUC prepared_statement_limit to limit memory used\n by prepared statements" }, { "msg_contents": "Am 19.08.2019 um 05:57 schrieb Kyotaro Horiguchi:\n> At Sun, 18 Aug 2019 09:43:09 +0200, Daniel Migowski <dmigowski@ikoffice.de> wrote in <6e25ca12-9484-8994-a1ee-40fdbe6afa8b@ikoffice.de>\n>> Am 17.08.2019 um 19:10 schrieb Ibrar Ahmed:\n>>> On Sat, Aug 17, 2019 at 6:58 PM Daniel Migowski <dmigowski@ikoffice.de\n>>> <mailto:dmigowski@ikoffice.de>> wrote:\n>>>\n>>>\n>>> attached you find a patch that adds a new GUC:\n>>>\n>>>\n>>> Quick questions before looking at the patch.\n>>>\n>>>\n>>> prepared_statement_limit:\n>>>\n>>>  - Do we have a consensus about the name of GUC? I don't think it is\n>>> the right name for that.\n> The almost same was proposed [1] as a part of syscache-pruning\n> patch [2], but removed to concentrate on defining how to do that\n> on the first instance - syscache. We have some mechanisms that\n> have the same characteristics - can be bloat and no means to keep\n> it in a certain size. It is better that they are treated the same\n> way, or at least on the same principle.\nCorrect. However, I don't know the backend well enough to see how to \nunify this. Also time based eviction isn't that important for me, and \nI'd rather work with the memory used. I agree that memory leaks are all \nbad, and a time based eviction for some small cache entries might \nsuffice, but CachedPlanSources take up up to 45MB EACH here, and looking \nat the memory directly seems desirable in that case.\n> [1] https://www.postgresql.org/message-id/20180315.141246.130742928.horiguchi.kyotaro%40lab.ntt.co.jp\n> [2] https://commitfest.postgresql.org/23/931/\n>\n> Pruning plancaches in any means is valuable, but we haven't\n> reached a concsensus on how to do that. My old patch does that\n> based on the number of entries because precise memory accounting\n> of memory contexts is too expensive. I didn't look this patch\n> closer but it seems to use MemoryContext->methods->stats to count\n> memory usage, which would be too expensive for the purpose. We\n> currently use it only for debug output on critical errors like\n> OOM.\n\nYes, this looks like a place to improve. I hadn't looked at the stats \nfunction before, and wasn't aware it iterates over all chunks of the \ncontext. We really don't need all the mem stats, just the total usage \nand this calculates solely from the size of the blocks. Maybe we should \nadd this counter (totalmemusage) to the MemoryContexts themselves to \nstart to be able to make decisions based on the memory usage fast. \nShouldn't be too slow because blocks seem to be aquired much less often \nthan chunks and when they are aquired an additional add to variable in \nmemory wouldn't hurt. One the other hand they should be as fast as \npossible given how often they are used in the database, so that might be \nbad.\n\nAlso one could precompute the memory usage of a CachedPlanSource when it \nis saved, when the query_list gets calculated (for plans about to be \nsaved) and when the generic plan is stored in it. In combination with a \nfast stats function which only calculates the total usage this looks \ngood for me. Also one could store the sum in a session global variable \nto make checking for the need of a prune run faster.\n\nWhile time based eviction also makes sense in a context where the \ndatabase is not alone on a server, contraining the memory used directly \nattacks the problem one tries to solve with time based eviction.\n\n\n\n", "msg_date": "Mon, 19 Aug 2019 08:04:32 +0200", "msg_from": "Daniel Migowski <dmigowski@ikoffice.de>", "msg_from_op": true, "msg_subject": "Re: Patch: New GUC prepared_statement_limit to limit memory used by\n prepared statements" }, { "msg_contents": "On 2019-Aug-18, Daniel Migowski wrote:\n\n> > �- Is this a WIP patch or the final patch? Because I can see TODO\n> > and non-standard comments in the patch.\n> \n> Definitely work in progress! The current implementation seems to work for\n> me, but might be improved, but I wanted some input from the mailing list\n> before I optimize things.\n> \n> The most important question is, if such a feature would find some love here.\n> Personally it is essential for me because a single prepared statement uses\n> up to 45MB in my application and there were cases where ORM-generated\n> prepared statememts would crash my server after some time.\n> \n> Then I would like to know if the current implementation would at least not\n> crash (even it might by slow a bit) or if I have to take more care for\n> locking in some places.\n\nOn this patch, beyond the fact that it's causing a crash in the\nregression tests as evidenced by the CFbot, we seem to be waiting on the\ninput of the larger community on whether it's a desired feature or not.\nWe have Kyotaro's vote for it, but it would be good to get more.\n\nI'm switching it as Needs Review, so that others chime in.\n\nIn the meantime, please do fix the code style: brace location and\nwhitespacing are not per style, as well as usage of //-comments.\nAlso please research and fix the crash.\n\nThanks\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 3 Sep 2019 12:25:50 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Patch: New GUC prepared_statement_limit to limit memory used by\n prepared statements" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On this patch, beyond the fact that it's causing a crash in the\n> regression tests as evidenced by the CFbot, we seem to be waiting on the\n> input of the larger community on whether it's a desired feature or not.\n> We have Kyotaro's vote for it, but it would be good to get more.\n\nI'm pretty dubious about this (just as I am with the somewhat-related\ntopic of syscache/relcache size limits). It's hard to tell where\nperformance is going to fall off a cliff if you limit the cache size.\n\nAnother point is that, because this only gets rid of the regeneratable\nparts of a plancache entry, it isn't really going to move the needle\nall that far in terms of total space consumption. As an experiment,\nI instrumented GetCachedPlan right after where it fills in the gplan field\nto see the relative sizes of the cache entry's contexts. Running that\nover the core + PL regression tests, I get\n\n 14 GetCachedPlan: 1024 context, 1024 query_context, 1024 gplan\n 4 GetCachedPlan: 1024 context, 2048 query_context, 1024 gplan\n 1 GetCachedPlan: 1024 context, 2048 query_context, 2048 gplan\n 2109 GetCachedPlan: 2048 context, 2048 query_context, 2048 gplan\n 29 GetCachedPlan: 2048 context, 2048 query_context, 4096 gplan\n 6 GetCachedPlan: 2048 context, 4096 query_context, 2048 gplan\n 33 GetCachedPlan: 2048 context, 4096 query_context, 4096 gplan\n 2 GetCachedPlan: 2048 context, 4096 query_context, 8192 gplan\n 1 GetCachedPlan: 2048 context, 8192 query_context, 16384 gplan\n 4 GetCachedPlan: 2048 context, 8192 query_context, 4096 gplan\n 2 GetCachedPlan: 2048 context, 8192 query_context, 8192 gplan\n 8 GetCachedPlan: 3480 context, 8192 query_context, 8192 gplan\n 250 GetCachedPlan: 4096 context, 2048 query_context, 2048 gplan\n 107 GetCachedPlan: 4096 context, 2048 query_context, 4096 gplan\n 3 GetCachedPlan: 4096 context, 4096 query_context, 16384 gplan\n 1 GetCachedPlan: 4096 context, 4096 query_context, 2048 gplan\n 7 GetCachedPlan: 4096 context, 4096 query_context, 32768 gplan\n 190 GetCachedPlan: 4096 context, 4096 query_context, 4096 gplan\n 61 GetCachedPlan: 4096 context, 4096 query_context, 8192 gplan\n 11 GetCachedPlan: 4096 context, 8192 query_context, 4096 gplan\n 587 GetCachedPlan: 4096 context, 8192 query_context, 8192 gplan\n 1 GetCachedPlan: 4096 context, 16384 query_context, 8192 gplan\n 5 GetCachedPlan: 4096 context, 32768 query_context, 32768 gplan\n 1 GetCachedPlan: 4096 context, 65536 query_context, 65536 gplan\n 12 GetCachedPlan: 8192 context, 4096 query_context, 4096 gplan\n 2 GetCachedPlan: 8192 context, 4096 query_context, 8192 gplan\n 49 GetCachedPlan: 8192 context, 8192 query_context, 16384 gplan\n 46 GetCachedPlan: 8192 context, 8192 query_context, 8192 gplan\n 10 GetCachedPlan: 8192 context, 16384 query_context, 16384 gplan\n 1 GetCachedPlan: 8192 context, 16384 query_context, 32768 gplan\n 1 GetCachedPlan: 8192 context, 16384 query_context, 8192 gplan\n 1 GetCachedPlan: 8192 context, 32768 query_context, 32768 gplan\n 2 GetCachedPlan: 8192 context, 131072 query_context, 131072 gplan\n 3 GetCachedPlan: 16384 context, 8192 query_context, 16384 gplan\n 1 GetCachedPlan: 16384 context, 16384 query_context, 16384 gplan\n 2 GetCachedPlan: 16384 context, 16384 query_context, 17408 gplan\n 1 GetCachedPlan: 16384 context, 16384 query_context, 32768 gplan\n 1 GetCachedPlan: 16384 context, 16384 query_context, 65536 gplan\n\n(The first column is the number of occurrences of the log entry;\nI got this list from \"grep|sort|uniq -c\" on the postmaster log.)\nPatch for this is attached, just in the interests of full disclosure.\n\nSo yeah, there are cases where you can save a whole lot by deleting\nthe query_context and/or gplan, but they're pretty few and far between;\nmore commonly, the nonreclaimable data in \"context\" accounts for a third\nof the usage.\n\n(BTW, it looks to me like the code tries to keep the *total* usage under\nthe GUC limit, not the freeable usage. Which means it won't be hard at all\nto drive it to the worst case where it tries to free everything all the\ntime, if the nonreclaimable data is already over the limit.)\n\nAdmittedly, the regression tests might well not be representative of\ncommon usage, but if you don't want to take them as a benchmark then\nwe need some other benchmark we can look at.\n\nI also notice that this doesn't seem to be doing anything with\nCachedExpressions, which are likely to be a pretty big factor in\nthe usage of e.g. plpgsql.\n\nNow, I'd be the first to say that my thoughts about this are probably\nbiased by my time at Salesforce, where their cache-consumption problems\nwere driven by lots and lots and lots and lots (and lots) of plpgsql code.\nMaybe with another usage pattern you'd come to a different conclusion,\nbut if I were trying to deal with that situation, what I'd look at\ndoing is reclaiming stuff starting at the plpgsql function cache level,\nand then cascading down to the plancache entries referenced by a plpgsql\nfunction body you've chosen to free. One major advantage of doing that\nis that plpgsql has a pretty clear idea of when a given function cache\ninstance has gone to zero refcount, whereas plancache.c simply doesn't\nknow that.\n\nAs far as the crash issue is concerned, I notice that right now the\ncfbot is showing green for this patch, but that seems to just be because\nthe behavior is unstable. I see crashes in \"make installcheck-parallel\"\nabout 50% of the time with this patch applied. Since, in fact,\nthe patch is not supposed to be doing anything at all with\nprepared_statement_limit set to zero, that suggests sloppiness in the\nrefactoring that was done to separate out the resource-freeing code.\n\nOn the other hand, if I do ALTER SYSTEM SET prepared_statement_limit = 1\nand then run \"make installcheck-parallel\", I see a different set of\nfailures. It rather looks like the patch is deleting plans out from\nunder plpgsql, which connects back to my point about plancache.c not\nreally knowing whether a plan is in use or not. Certainly,\nEnforcePreparedStatementLimit as coded here has no idea about that.\n\n(Speaking of ALTER SYSTEM, why the devil is the variable PGC_POSTMASTER?\nThat seems entirely silly.)\n\nAside from Alvaro's style points, I'm fairly concerned about the overhead\nthe patch will add when active. Running through the entire plancache\nand collecting memory stats is likely to be quite an expensive\nproposition when there are lots of entries, yet this is willing to do that\nover again at the drop of a hat. It won't be hard to get this to expend\nO(N^2) time with N entries. I think that for acceptable performance,\nit'll be necessary to track total usage incrementally instead of doing\nit this way.\n\n\t\t\tregards, tom lane", "msg_date": "Tue, 03 Sep 2019 17:27:21 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Patch: New GUC prepared_statement_limit to limit memory used by\n prepared statements" }, { "msg_contents": "I wrote:\n> As far as the crash issue is concerned, I notice that right now the\n> cfbot is showing green for this patch, but that seems to just be because\n> the behavior is unstable. I see crashes in \"make installcheck-parallel\"\n> about 50% of the time with this patch applied. Since, in fact,\n> the patch is not supposed to be doing anything at all with\n> prepared_statement_limit set to zero, that suggests sloppiness in the\n> refactoring that was done to separate out the resource-freeing code.\n\nOh ... actually, I bet the problem is that the patch thinks it's okay\nto immediately free space in PlanCacheRelCallback and friends, rather\nthan just marking invalid entries as invalid. Nope, you cannot do that.\nYou can't tell whether that data is being examined in an outer call\nlevel.\n\nIn principle I think you could decrement-the-refcount-and-possibly-free\nright away on the gplan, since any outside uses of that ought to have\ntheir own refcounts. But the query_context data isn't refcounted.\nAlso, some of the failures I saw looked like premature deletion of a\nplan, not query_context data, so the patch seems to be too aggressive\non that side too.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 03 Sep 2019 18:30:32 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Patch: New GUC prepared_statement_limit to limit memory used by\n prepared statements" }, { "msg_contents": "On Tue, Sep 03, 2019 at 06:30:32PM -0400, Tom Lane wrote:\n> Oh ... actually, I bet the problem is that the patch thinks it's okay\n> to immediately free space in PlanCacheRelCallback and friends, rather\n> than just marking invalid entries as invalid. Nope, you cannot do that.\n> You can't tell whether that data is being examined in an outer call\n> level.\n> \n> In principle I think you could decrement-the-refcount-and-possibly-free\n> right away on the gplan, since any outside uses of that ought to have\n> their own refcounts. But the query_context data isn't refcounted.\n> Also, some of the failures I saw looked like premature deletion of a\n> plan, not query_context data, so the patch seems to be too aggressive\n> on that side too.\n\nWe are a couple of months after this update, and the patch has not\nbeen updated, so I am marking it as returned with feedack.\n--\nMichael", "msg_date": "Thu, 28 Nov 2019 11:42:50 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Patch: New GUC prepared_statement_limit to limit memory used by\n prepared statements" } ]
[ { "msg_contents": "Try this:\nalter system set max_parallel_workers = 20;\nand restart the system.\n\nmax_parallel_workers is still 8, according to both SHOW and\npg_controldata, nor can you launch more than 8 workers.\n\nEven odder, if you just do\n\nregression=# set max_parallel_workers = 200;\nSET\nregression=# show max_parallel_workers; \n max_parallel_workers \n----------------------\n 200\n(1 row)\n\nwhich should certainly not happen for a PGC_POSTMASTER parameter.\n\nWe seem to have an awful lot of mechanism that's concerned with\nadjustments of max_parallel_workers, for something that apparently\nmight as well be a compile-time #define ... so I assume it's supposed\nto be changeable at restart and somebody broke it. But it's not\nworking as I'd expect in any branch from 10 onwards.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 17 Aug 2019 13:41:18 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "max_parallel_workers can't actually be set?" }, { "msg_contents": "Hi,\n\nOn my PG11 I have set it to 64 upon setup and it propogated to\npostgresql.auto.conf and is set after restart. I've upgraded to PG12 since\nthen, and parameter is read from postgresql.auto.conf correctly and is\ndisplayed via SHOW (just checked on 12beta3).\n\nI also spent some time trying to get a plan that will give me 32 workers.\nLargest I ever got without taking a hammer was 16, which is half of\navailable cores, or all non-HT ones. I still haven't found a way to set\ncosts and limits to load all the system with a query.\n\nALTER TABLE ... SET (parallel_workers=32); is currently my most favorite\nhammer. I set max_worker_processes to 512 and letting OS scheduler resolve\nthe hours when four queries run 128 CPU-bound processes on 32-core machine,\nit's not as good as if the limits were adjusted dynamically after the query\nstart but much better than running a second query with just 1 worker even\nafter first one finishes.\n\nOn Sat, Aug 17, 2019 at 8:41 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Try this:\n> alter system set max_parallel_workers = 20;\n> and restart the system.\n>\n> max_parallel_workers is still 8, according to both SHOW and\n> pg_controldata, nor can you launch more than 8 workers.\n>\n> Even odder, if you just do\n>\n> regression=# set max_parallel_workers = 200;\n> SET\n> regression=# show max_parallel_workers;\n> max_parallel_workers\n> ----------------------\n> 200\n> (1 row)\n>\n> which should certainly not happen for a PGC_POSTMASTER parameter.\n>\n> We seem to have an awful lot of mechanism that's concerned with\n> adjustments of max_parallel_workers, for something that apparently\n> might as well be a compile-time #define ... so I assume it's supposed\n> to be changeable at restart and somebody broke it. But it's not\n> working as I'd expect in any branch from 10 onwards.\n>\n> regards, tom lane\n>\n>\n>\n\n-- \nDarafei Praliaskouski\nSupport me: http://patreon.com/komzpa\n\nHi,On my PG11 I have set it to 64 upon setup and it propogated to postgresql.auto.conf and is set after restart. I've upgraded to PG12 since then, and parameter is read from postgresql.auto.conf correctly and is displayed via SHOW (just checked on 12beta3).I also spent some time trying to get a plan that will give me 32 workers. Largest I ever got without taking a hammer was 16, which is half of available cores, or all non-HT ones. I still haven't found a way to set costs and limits to load all the system with a query.ALTER TABLE ... SET (parallel_workers=32); is currently my most favorite hammer. I set max_worker_processes to 512 and letting OS scheduler resolve the hours when four queries run 128 CPU-bound processes on 32-core machine, it's not as good as if the limits were adjusted dynamically after the query start but much better than running a second query with just 1 worker even after first one finishes.On Sat, Aug 17, 2019 at 8:41 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:Try this:\nalter system set max_parallel_workers = 20;\nand restart the system.\n\nmax_parallel_workers is still 8, according to both SHOW and\npg_controldata, nor can you launch more than 8 workers.\n\nEven odder, if you just do\n\nregression=# set max_parallel_workers = 200;\nSET\nregression=# show max_parallel_workers;      \n max_parallel_workers \n----------------------\n 200\n(1 row)\n\nwhich should certainly not happen for a PGC_POSTMASTER parameter.\n\nWe seem to have an awful lot of mechanism that's concerned with\nadjustments of max_parallel_workers, for something that apparently\nmight as well be a compile-time #define ... so I assume it's supposed\nto be changeable at restart and somebody broke it.  But it's not\nworking as I'd expect in any branch from 10 onwards.\n\n                        regards, tom lane\n\n\n-- Darafei PraliaskouskiSupport me: http://patreon.com/komzpa", "msg_date": "Sat, 17 Aug 2019 21:07:17 +0300", "msg_from": "=?UTF-8?Q?Darafei_=22Kom=D1=8Fpa=22_Praliaskouski?= <me@komzpa.net>", "msg_from_op": false, "msg_subject": "Re: max_parallel_workers can't actually be set?" }, { "msg_contents": "Hello\n\n> Try this:\n> alter system set max_parallel_workers = 20;\n> and restart the system.\n> max_parallel_workers is still 8\n\nHmm, I got 20 on my local 11.5 and on HEAD.\n\n> which should certainly not happen for a PGC_POSTMASTER parameter.\n\nBut max_parallel_workers is PGC_USERSET and this behavior seems be documented:\n\n> Also, note that a setting for this value which is higher than max_worker_processes will have no effect, since parallel workers are taken from the pool of worker processes established by that setting.\n\nregards, Sergei\n\n\n", "msg_date": "Sat, 17 Aug 2019 21:08:07 +0300", "msg_from": "Sergei Kornilov <sk@zsrv.org>", "msg_from_op": false, "msg_subject": "Re: max_parallel_workers can't actually be set?" }, { "msg_contents": "On Sat, Aug 17, 2019 at 10:41 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Try this:\n> alter system set max_parallel_workers = 20;\n> and restart the system.\n>\n> max_parallel_workers is still 8, according to both SHOW and\n> pg_controldata, nor can you launch more than 8 workers.\n>\n> Even odder, if you just do\n>\n> regression=# set max_parallel_workers = 200;\n> SET\n> regression=# show max_parallel_workers;\n> max_parallel_workers\n> ----------------------\n> 200\n> (1 row)\n>\n> which should certainly not happen for a PGC_POSTMASTER parameter.\n>\n> We seem to have an awful lot of mechanism that's concerned with\n> adjustments of max_parallel_workers, for something that apparently\n> might as well be a compile-time #define ... so I assume it's supposed\n> to be changeable at restart and somebody broke it. But it's not\n> working as I'd expect in any branch from 10 onwards.\n>\n> regards, tom lane\n>\n>\n>\nIf I understand that correctly it works for me.\n\npostgres=# alter system set max_parallel_workers = 1;\n$ pg_ctl restart -l log\n$ psql postgres\npsql (13devel)\npostgres=# explain analyze select * from test where b > 1;\n\n\n QUERY PLAN\n\n-----------------------------------------------------------------------------------------------------------------------\n Gather (cost=1000.00..98294.84 rows=1 width=8) (actual\ntime=1635.959..1636.028 rows=0 loops=1)\n Workers Planned: 2\n Workers Launched: 1\n -> Parallel Seq Scan on test (cost=0.00..97294.74 rows=1 width=8)\n(actual time=1632.239..1632.239 rows=0 loops=2)\n Filter: (b > 1)\n Rows Removed by Filter: 5050000\n\n Planning Time: 0.533 ms\n Execution Time: 1636.080 ms\n(8 rows)\n\n\n\npostgres=# alter system set max_parallel_workers = 2;\nALTER SYSTEM\npostgres=# \\q\nvagrant@vagrant:~/percona/postgresql$ pg_ctl restart -l log\nvagrant@vagrant:~/percona/postgresql$ psql postgres\npsql (13devel)\nType \"help\" for help.\npostgres=# explain analyze select * from test where b > 1;\n QUERY PLAN\n\n-----------------------------------------------------------------------------------------------------------------------\n Gather (cost=1000.00..98294.84 rows=1 width=8) (actual\ntime=1622.210..1622.274 rows=0 loops=1)\n Workers Planned: 2\n Workers Launched: 2\n -> Parallel Seq Scan on test (cost=0.00..97294.74 rows=1 width=8)\n(actual time=1616.000..1616.000 rows=0 loops=3)\n Filter: (b > 1)\n Rows Removed by Filter: 3366667\n Planning Time: 0.699 ms\n Execution Time: 1622.325 ms\n(8 rows)\n\n\n\n\n--\nIbrar Ahmed\n\nOn Sat, Aug 17, 2019 at 10:41 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:Try this:\nalter system set max_parallel_workers = 20;\nand restart the system.\n\nmax_parallel_workers is still 8, according to both SHOW and\npg_controldata, nor can you launch more than 8 workers.\n\nEven odder, if you just do\n\nregression=# set max_parallel_workers = 200;\nSET\nregression=# show max_parallel_workers;      \n max_parallel_workers \n----------------------\n 200\n(1 row)\n\nwhich should certainly not happen for a PGC_POSTMASTER parameter.\n\nWe seem to have an awful lot of mechanism that's concerned with\nadjustments of max_parallel_workers, for something that apparently\nmight as well be a compile-time #define ... so I assume it's supposed\nto be changeable at restart and somebody broke it.  But it's not\nworking as I'd expect in any branch from 10 onwards.\n\n                        regards, tom lane\n\nIf I understand that correctly it works for me.postgres=# alter system set max_parallel_workers = 1;$ pg_ctl restart -l log$ psql postgrespsql (13devel)postgres=# explain analyze select * from test where b > 1;                                                                                                                     QUERY PLAN                                                       ----------------------------------------------------------------------------------------------------------------------- Gather  (cost=1000.00..98294.84 rows=1 width=8) (actual time=1635.959..1636.028 rows=0 loops=1)   Workers Planned: 2   Workers Launched: 1   ->  Parallel Seq Scan on test  (cost=0.00..97294.74 rows=1 width=8) (actual time=1632.239..1632.239 rows=0 loops=2)         Filter: (b > 1)         Rows Removed by Filter: 5050000 Planning Time: 0.533 ms Execution Time: 1636.080 ms(8 rows)postgres=# alter system set max_parallel_workers = 2;ALTER SYSTEMpostgres=# \\qvagrant@vagrant:~/percona/postgresql$ pg_ctl restart -l logvagrant@vagrant:~/percona/postgresql$ psql postgrespsql (13devel)Type \"help\" for help.postgres=# explain analyze select * from test where b > 1;                                                      QUERY PLAN                                                       ----------------------------------------------------------------------------------------------------------------------- Gather  (cost=1000.00..98294.84 rows=1 width=8) (actual time=1622.210..1622.274 rows=0 loops=1)   Workers Planned: 2   Workers Launched: 2   ->  Parallel Seq Scan on test  (cost=0.00..97294.74 rows=1 width=8) (actual time=1616.000..1616.000 rows=0 loops=3)         Filter: (b > 1)         Rows Removed by Filter: 3366667 Planning Time: 0.699 ms Execution Time: 1622.325 ms(8 rows) --Ibrar Ahmed", "msg_date": "Sat, 17 Aug 2019 23:12:45 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: max_parallel_workers can't actually be set?" }, { "msg_contents": "Sergei Kornilov <sk@zsrv.org> writes:\n>> which should certainly not happen for a PGC_POSTMASTER parameter.\n\n> But max_parallel_workers is PGC_USERSET and this behavior seems be documented:\n\nArgh! I was looking at max_worker_processes in one window and\nmax_parallel_workers in another, and failed to see the discrepancy.\n\nThose GUCs are too confusingly named :-(.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 17 Aug 2019 16:23:44 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: max_parallel_workers can't actually be set?" }, { "msg_contents": "Hi,\n\nOn 2019-08-17 13:41:18 -0400, Tom Lane wrote:\n> Try this:\n> alter system set max_parallel_workers = 20;\n> and restart the system.\n> \n> max_parallel_workers is still 8, according to both SHOW and\n> pg_controldata, nor can you launch more than 8 workers.\n\nHm. I can't reproduce that. I do get whatever number I configure. Note\nalso that pg_controldata shows max_worker_processes, not\nmax_parallel_workers.\n\n\n> Even odder, if you just do\n> \n> regression=# set max_parallel_workers = 200;\n> SET\n> regression=# show max_parallel_workers; \n> max_parallel_workers \n> ----------------------\n> 200\n> (1 row)\n> \n> which should certainly not happen for a PGC_POSTMASTER parameter.\n\nIt's not PGC_POSTMASTER. That's max_worker_processes. The max_parallel_*\nGUCs just control how many of max_worker_processes are used for $task.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sat, 17 Aug 2019 13:28:19 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: max_parallel_workers can't actually be set?" } ]
[ { "msg_contents": "Hello,\n\nGoing through the current items in the wiki's todo list, I have been\nlooking into: \"Allow to_date () and to_timestamp () to accept\nlocalized month names\".\n\nIt seems to me that the code is almost there, so I would like to know\nif something like the attached patch would be a reasonable way to go.\n\nRegards,\n\nJuan José Santamaría Flecha", "msg_date": "Sun, 18 Aug 2019 10:42:52 +0200", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Sun, Aug 18, 2019 at 10:42 AM Juan José Santamaría Flecha\n<juanjo.santamaria@gmail.com> wrote:\n>\n> Going through the current items in the wiki's todo list, I have been\n> looking into: \"Allow to_date () and to_timestamp () to accept\n> localized month names\".\n>\n\nI have gone through a second take on this, trying to give it a better\nshape but it would surely benefit from some review, so I will open an\nitem in the commitfest.\n\nRegards,\n\nJuan José Santamaría Flecha", "msg_date": "Thu, 22 Aug 2019 21:38:35 +0200", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Thu, Aug 22, 2019 at 9:38 PM Juan José Santamaría Flecha\n<juanjo.santamaria@gmail.com> wrote:\n>\n> >\n> > Going through the current items in the wiki's todo list, I have been\n> > looking into: \"Allow to_date () and to_timestamp () to accept\n> > localized month names\".\n> >\n>\n> I have gone through a second take on this, trying to give it a better\n> shape but it would surely benefit from some review, so I will open an\n> item in the commitfest.\n\nFor reviewers, the current aproach for this patch is:\n\nBreak seq_search() into two functions:\n * seq_search_sqlascii() that supports seq_search() current usage.\n * seq_search_localized() similar to the previous but supports multibyte input.\nTo avoid code duplication most of current seq_search() logic has been\nmoved to a new function str_compare().\nfrom_char_seq_search() is now responsible to choose between\nseq_search_sqlascii() or seq_search_localized().\nAlso, since localized names is not a null terminated array,\nseq_search() now receives the dimension as input and terminating nulls\nhave been removed from static arrays.\n\nThe commitfest item is:\n\nhttps://commitfest.postgresql.org/24/2255/\n\nRegards,\n\nJuan José Santamaría Flecha\n\n\n", "msg_date": "Fri, 23 Aug 2019 10:33:22 +0200", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2019-Aug-22, Juan Jos� Santamar�a Flecha wrote:\n\n> On Sun, Aug 18, 2019 at 10:42 AM Juan Jos� Santamar�a Flecha\n> <juanjo.santamaria@gmail.com> wrote:\n> >\n> > Going through the current items in the wiki's todo list, I have been\n> > looking into: \"Allow to_date () and to_timestamp () to accept\n> > localized month names\".\n> \n> I have gone through a second take on this, trying to give it a better\n> shape but it would surely benefit from some review, so I will open an\n> item in the commitfest.\n\nI'm confused why we acquire the MONTH_DIM / etc definitions. Can't we\njust use lengthof() of the corresponding array? AFAICS it should work\njust as well.\n\nI wonder if the \"compare first char\" thing (seq_search_localized) really\nworks when there are multibyte chars in the day/month names. I think\nthe code compares just the first char ... but what if the original\nstring uses those funny Unicode non-normalized letters and the locale\ntranslation uses normalized letters? My guess is that the first-char\ncomparison will fail, but surely you'll want the name to match.\n(There's no month/day name in Spanish that doesn't start with an ASCII\nletter, but I bet there are some in other languages.) I think the\nlocalized comparison should avoid the first-char optimization, just\ncompare the whole string all the time, and avoid possible weird issues.\n\nBut then, I'm not 100% sure of this code. formatting.c is madness\ndistilled.\n\nThanks,\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 13 Sep 2019 17:31:09 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Fri, Sep 13, 2019 at 10:31 PM Alvaro Herrera\n<alvherre@2ndquadrant.com> wrote:\n>\nThanks for taking a look at this.\n\n> I'm confused why we acquire the MONTH_DIM / etc definitions. Can't we\n> just use lengthof() of the corresponding array? AFAICS it should work\n> just as well.\n>\n\nIt was because of the length difference between ascii-name arrays,\nwhich were all null-ended, and localized-name arrays. The attached\nversion uses lengthof().\n\n> I wonder if the \"compare first char\" thing (seq_search_localized) really\n> works when there are multibyte chars in the day/month names. I think\n> the code compares just the first char ... but what if the original\n> string uses those funny Unicode non-normalized letters and the locale\n> translation uses normalized letters? My guess is that the first-char\n> comparison will fail, but surely you'll want the name to match.\n> (There's no month/day name in Spanish that doesn't start with an ASCII\n> letter, but I bet there are some in other languages.) I think the\n> localized comparison should avoid the first-char optimization, just\n> compare the whole string all the time, and avoid possible weird issues.\n\nThe localized search is reformulated in this version to deal with\nmultibyte normalization. A regression test for this issue is included.\n\n\nRegards,\n\nJuan José Santamaría Flecha", "msg_date": "Wed, 18 Sep 2019 11:09:52 +0200", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Wed, Sep 18, 2019 at 11:09 AM Juan José Santamaría Flecha\n<juanjo.santamaria@gmail.com> wrote:\n>\n> On Fri, Sep 13, 2019 at 10:31 PM Alvaro Herrera\n> <alvherre@2ndquadrant.com> wrote:\n> >\n> Thanks for taking a look at this.\n>\n> > I'm confused why we acquire the MONTH_DIM / etc definitions. Can't we\n> > just use lengthof() of the corresponding array? AFAICS it should work\n> > just as well.\n> >\n>\n> It was because of the length difference between ascii-name arrays,\n> which were all null-ended, and localized-name arrays. The attached\n> version uses lengthof().\n>\n> > I wonder if the \"compare first char\" thing (seq_search_localized) really\n> > works when there are multibyte chars in the day/month names. I think\n> > the code compares just the first char ... but what if the original\n> > string uses those funny Unicode non-normalized letters and the locale\n> > translation uses normalized letters? My guess is that the first-char\n> > comparison will fail, but surely you'll want the name to match.\n> > (There's no month/day name in Spanish that doesn't start with an ASCII\n> > letter, but I bet there are some in other languages.) I think the\n> > localized comparison should avoid the first-char optimization, just\n> > compare the whole string all the time, and avoid possible weird issues.\n>\n> The localized search is reformulated in this version to deal with\n> multibyte normalization. A regression test for this issue is included.\n\nThis version is updated to optimize the need for dynamic allocation.\n\n\n> Regards,\n>\n> Juan José Santamaría Flecha", "msg_date": "Sun, 22 Sep 2019 14:33:22 +0200", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "This patch no longer applies. Can you please rebase?\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 25 Sep 2019 16:57:45 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Wed, Sep 25, 2019 at 9:57 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n>\n> This patch no longer applies. Can you please rebase?\n\nThank you for the notification.\n\nThe patch rot after commit 1a950f3, a rebased version is attached.\n\nRegards,\n\nJuan José Santamaría Flecha", "msg_date": "Thu, 26 Sep 2019 20:36:25 +0200", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Thu, Sep 26, 2019 at 08:36:25PM +0200, Juan Jos� Santamar�a Flecha wrote:\n>On Wed, Sep 25, 2019 at 9:57 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n>>\n>> This patch no longer applies. Can you please rebase?\n>\n>Thank you for the notification.\n>\n>The patch rot after commit 1a950f3, a rebased version is attached.\n>\n\nThanks. I did a quick review of this patch, and I think it's almost RFC.\nI only found a couple of minor issue:\n\n- In func.sgml, it seems we've lost this bit:\n\n <para>\n <literal>TM</literal> does not include trailing blanks.\n <function>to_timestamp</function> and <function>to_date</function> ignore\n the <literal>TM</literal> modifier.\n </para>\n\n Does that mean the function no longer ignore the TM modifier? That\n would be somewhat problematic (i.e. it might break some user code).\n But looking at the code I don't see why the patch would have this\n effect, so I suppose it's merely a doc bug.\n\n- I don't think we need to include examples how to_timestmap ignores\n case, I'd say just stating the fact is clear enough. But if we want to\n have examples, I think we should not inline in the para but use the\n established pattern:\n\n <para>\n Some examples:\n<programlisting>\n...\n</programlisting>\n </para>\n\n which is used elsewhere in the func.sgml file.\n\n- In formatting.c the \"common/unicode_norm.h\" should be right after\n includes from \"catalog/\" to follow the alphabetic order (unless\n there's a reason why that does not work).\n\n- I rather dislike the \"dim\" parameter name, because I immediately think\n \"dimension\" which makes little sense. I suggest renaming to \"nitems\"\n or \"nelements\" or something like that. \n\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services \n\n\n", "msg_date": "Sat, 11 Jan 2020 17:06:02 +0100", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Sat, Jan 11, 2020 at 5:06 PM Tomas Vondra <tomas.vondra@2ndquadrant.com>\nwrote:\n\n>\n> Thanks. I did a quick review of this patch, and I think it's almost RFC.\n>\n>\nThanks for reviewing.\n\n\n> - In func.sgml, it seems we've lost this bit:\n>\n> <para>\n> <literal>TM</literal> does not include trailing blanks.\n> <function>to_timestamp</function> and <function>to_date</function>\n> ignore\n> the <literal>TM</literal> modifier.\n> </para>\n>\n> Does that mean the function no longer ignore the TM modifier? That\n> would be somewhat problematic (i.e. it might break some user code).\n> But looking at the code I don't see why the patch would have this\n> effect, so I suppose it's merely a doc bug.\n>\n>\nIt is intentional. This patch uses the TM modifier to identify the usage of\nlocalized names as input for to_timestamp() and to_date().\n\n\n> - I don't think we need to include examples how to_timestmap ignores\n> case, I'd say just stating the fact is clear enough. But if we want to\n> have examples, I think we should not inline in the para but use the\n> established pattern:\n>\n> <para>\n> Some examples:\n> <programlisting>\n> ...\n> </programlisting>\n> </para>\n>\n> which is used elsewhere in the func.sgml file.\n>\n\nI was trying to match the style surrounding the usage notes for date/time\nformatting [1]. Agreed that it is not worth an example on its own, so\ndropped.\n\n\n>\n> - In formatting.c the \"common/unicode_norm.h\" should be right after\n> includes from \"catalog/\" to follow the alphabetic order (unless\n> there's a reason why that does not work).\n>\n\nFixed.\n\n\n>\n> - I rather dislike the \"dim\" parameter name, because I immediately think\n> \"dimension\" which makes little sense. I suggest renaming to \"nitems\"\n> or \"nelements\" or something like that.\n>\n\n\nAgreed, using \"nelements\" as a better style matchup.\n\nPlease, find attached a version addressing the above mentioned.\n\n[1] https://www.postgresql.org/docs/current/functions-formatting.html\n\nRegards,\n\nJuan José Santamaría Flecha\n\n>", "msg_date": "Mon, 13 Jan 2020 13:04:48 +0100", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "Hello!\n\nOn 2020/01/13 21:04, Juan José Santamaría Flecha wrote:\n> Please, find attached a version addressing the above mentioned.\n\nI have some couple picky notes.\n\n> +\tif (name_len != norm_len)\n> +\t\tpfree(norm_name);\n\nI'm not sure here. Is it save to assume that if it was allocated a new \nnorm_name name_len and norm_len always will differ?\n\n> static const char *const months_full[] = {\n> \t\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\",\n> -\t\"August\", \"September\", \"October\", \"November\", \"December\", NULL\n> +\t\"August\", \"September\", \"October\", \"November\", \"December\"\n> };\n\nUnfortunately I didn't see from the patch why it was necessary to remove \nlast null element from months_full, days_short, adbc_strings, \nadbc_strings_long and other arrays. I think it is not good because \nunnecessarily increases the patch and adds code like the following:\n\n> +\t\t\t\tfrom_char_seq_search(&value, &s, months, localized_names,\n> +\t\t\t\t\t\t\t\t\t ONE_UPPER, MAX_MON_LEN, n, have_error,\n> +\t\t\t\t\t\t\t\t\t lengthof(months_full));\n\nHere it passes \"months\" from datetime.c to from_char_seq_search() and \ncalculates its length using \"months_full\" array from formatting.c.\n\n-- \nArthur\n\n\n", "msg_date": "Wed, 15 Jan 2020 19:20:25 +0900", "msg_from": "Arthur Zakirov <zaartur@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Wed, Jan 15, 2020 at 11:20 AM Arthur Zakirov <zaartur@gmail.com> wrote:\n\n>\n> I have some couple picky notes.\n>\n>\nThanks for the review.\n\n\n> > + if (name_len != norm_len)\n> > + pfree(norm_name);\n>\n> I'm not sure here. Is it save to assume that if it was allocated a new\n> norm_name name_len and norm_len always will differ?\n>\n\nGood call, that check can be more robust.\n\n\n>\n> > static const char *const months_full[] = {\n> > \"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\",\n> > - \"August\", \"September\", \"October\", \"November\", \"December\", NULL\n> > + \"August\", \"September\", \"October\", \"November\", \"December\"\n> > };\n>\n> Unfortunately I didn't see from the patch why it was necessary to remove\n> last null element from months_full, days_short, adbc_strings,\n> adbc_strings_long and other arrays. I think it is not good because\n> unnecessarily increases the patch and adds code like the following:\n>\n> > + from_char_seq_search(&value, &s, months,\n> localized_names,\n> > +\n> ONE_UPPER, MAX_MON_LEN, n, have_error,\n> > +\n> lengthof(months_full));\n>\n> Here it passes \"months\" from datetime.c to from_char_seq_search() and\n> calculates its length using \"months_full\" array from formatting.c.\n>\n\n\nWith the introduction of seq_search_localized() that can be avoided,\nminimizing code churn.\n\nPlease, find attached a version addressing the above mentioned.\n\nRegards,\n\nJuan José Santamaría Flecha\n\n>\n>", "msg_date": "Wed, 15 Jan 2020 19:21:11 +0100", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?= <juanjo.santamaria@gmail.com> writes:\n> [ 0001-Allow-localized-month-names-to_date-v6.patch ]\n\nI took a quick look through this.\n\nOne thing I completely don't understand is why it's sufficient for\nseq_search_localized to do \"initcap\" semantics. Shouldn't it cover\nthe all-upper and all-lower cases as well, as the existing seq_search\ncode does? (That is, why is it okay to ignore the \"type\" argument?)\n\nOn the other hand, you probably *should* be ignoring the \"max\"\nargument, because AFAICS the values that are passed for that are\nspecific to the English ASCII spellings of the day and month names.\nIt seems very likely that they could be too small for some sets of\nnon-English names.\n\nRelated to that, the business with\n\n+\tmb_max = max * pg_encoding_max_length(encoding);\n+\tname_len = strlen(name);\n+\tname_len = name_len < mb_max ? name_len : mb_max;\n\nseems wrong even if we assume that \"max\" is a sane limit on the number of\ncharacters to consider. This coding is likely to truncate a long \"name\"\nstring in the middle of a multibyte character, leading to bad-encoding\nerrors from later functions.\n\nI also am confused by the \"if (mb_max > max ...)\" bit. It looks to me\nlike that's an obscure way of writing \"if (pg_encoding_max_length() > 1)\",\nwhich is a rather pointless check considering that the if() then goes on\nto insist on encoding == PG_UTF8.\n\nA bit further down, you have an \"if (name_wlen > norm_wlen)\"\ncondition that seems pretty fishy. Is it really guaranteed that\nunicode_normalize_kc cannot transform the string without shortening it?\nI don't see that specified in its header comment, for sure.\n\nAlso, it's purely accidental if this:\n\n\tnorm_name = (char *) palloc((norm_wlen + 1) * sizeof(pg_wchar));\n\nallocates a long enough string for the conversion back to multibyte form,\nbecause that output is not pg_wchars. I think you want something more\nlike \"norm_wlen * MAX_MULTIBYTE_CHAR_LEN + 1\". (I wonder whether we\nneed to be worrying about integer overflow in any of this.)\n\nIt seems like you could eliminate a lot of messiness by extending\nlocalized_abbrev_days[] and related arrays by one element that's\nalways NULL. That would waste, hmm, four 8-byte pointers on typical\nmachines --- but you're eating a lot more than 32 bytes of code to\npass around the array lengths, plus it's really ugly that the plain\nand localized arrays are handled differently.\n\nI don't think the way you're managing the \"localized_names\" variable\nin DCH_from_char is very sensible. The reader has to do a lot of\nreverse engineering just to discover that the value is constant NULL\nin most references, something that you've not helped by declaring\nit outside the loop rather than inside. I think you could drop\nthe variable and write constant NULL in most places, with something\nlike\n\tS_TM(n->suffix) ? localized_full_days : NULL\nin those from_char_seq_search calls where it's relevant.\n\nIn general I'm displeased with the lack of attention to comments.\nNotably, you added arguments to from_char_seq_search without updating\nits header comment ... not that that comment is a great API spec, but\nat the least you shouldn't be making it worse. I think the bug I\ncomplained of above is directly traceable to the lack of a clear spec\nhere for what \"max\" means, so failure to keep these comments up to\nspeed does have demonstrable bad consequences.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 21 Jan 2020 18:20:24 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "I wrote:\n> One thing I completely don't understand is why it's sufficient for\n> seq_search_localized to do \"initcap\" semantics. Shouldn't it cover\n> the all-upper and all-lower cases as well, as the existing seq_search\n> code does? (That is, why is it okay to ignore the \"type\" argument?)\n\nI took a closer look at this and decided you were probably doing that\njust because the seq_search code uses initcap-style case folding to\nmatch month and day names, relying on the assumption that the constant\narrays it's passed are cased that way. But we shouldn't (and the patch\ndoesn't) assume that the localized names we'll get from pg_locale.c are\ncased that way.\n\nHowever ... it seems to me that the way seq_search is defined is\nplenty bogus. In the first place, it scribbles on its source string,\nwhich is surely not okay. You can see that in error messages that\nare thrown on match failures:\n\nregression=# select to_date('3 JANUZRY 1999', 'DD MONTH YYYY');\nERROR: invalid value \"JanuzRY 1\" for \"MONTH\"\nDETAIL: The given value did not match any of the allowed values for this field.\n\nNow, maybe somebody out there thinks this is a cute way of highlighting\nhow much of the string we examined, but it looks more like a bug from\nwhere I sit. It's mere luck that what's being clobbered is a local\nstring copy created by do_to_timestamp(), and not the original input\ndata passed to to_date().\n\nIn the second place, there's really no need at all for seq_search to\nrely on any assumptions about the case state of the array it's\nsearching. pg_toupper() is pretty cheap already, and we can make it\nguaranteed cheap if we use pg_ascii_toupper() instead. So I think\nwe ought to just remove the \"type\" argument altogether and have\nseq_search dynamically convert all the strings it examines to upper\ncase (or lower case would work as well, at least for English).\n\n> On the other hand, you probably *should* be ignoring the \"max\"\n> argument, because AFAICS the values that are passed for that are\n> specific to the English ASCII spellings of the day and month names.\n> It seems very likely that they could be too small for some sets of\n> non-English names.\n\nCloser examination shows that the \"max\" argument is pretty bogus as\nwell. It doesn't do anything except confuse the reader, because there\nare no cases where the value passed is less than the maximum array entry\nlength, so it never acts to change seq_search's behavior. So we should\njust drop that behavior from seq_search, too, and redefine \"max\" as\nhaving no purpose except to specify how much of the string to show in\nerror messages. There's still a question of what that should be for\nnon-English cases, but at least we now have a clear idea of what we\nneed the value to do.\n\nI also noted while I was looking at it that from_char_seq_search()\nwould truncate at \"max\" bytes even when dealing with multibyte input.\nThat has a clear risk of generating an invalidly-encoded error message.\n\nThe 0001 patch attached cleans up all the above complaints. I felt\nthat given the business about scribbling on strings we shouldn't,\nit would also be wise to const-ify the string pointers if possible.\nThat seems not too painful, per 0002 attached.\n\nI'm tempted to go a bit further than 0001 does, and remove the 'max'\nargument from from_char_seq_search() altogether. Since we only need\n'max' in error cases, which don't need to be super-quick, we could drop\nthe requirement for the caller to specify that and instead compute it\nwhen we do need it as the largest of the constant array's string\nlengths. That'd carry over into the localized-names case in a\nreasonably straightforward way (though we might need to count characters\nnot bytes for that to work nicely).\n\nBecause of the risk of incorrectly-encoded error messages, I'm rather\ntempted to claim that these patches (or at least 0001) are a bug fix\nand should be back-patched. In any case I think we should apply this\nto HEAD and then rebase the localized-names patch over it. It makes\na whole lot more sense, IMO, for the localized-names comparison logic\nto match what this is doing than what seq_search does today.\n\nComments?\n\n\t\t\tregards, tom lane", "msg_date": "Wed, 22 Jan 2020 17:11:27 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2020/01/23 7:11, Tom Lane wrote:\n> Closer examination shows that the \"max\" argument is pretty bogus as\n> well. It doesn't do anything except confuse the reader, because there\n> are no cases where the value passed is less than the maximum array entry\n> length, so it never acts to change seq_search's behavior. So we should\n> just drop that behavior from seq_search, too, and redefine \"max\" as\n> having no purpose except to specify how much of the string to show in\n> error messages. There's still a question of what that should be for\n> non-English cases, but at least we now have a clear idea of what we\n> need the value to do.\n\nShouldn't we just show all remaining string instead of truncating it? \nFor example I get the following output:\n\n=# select to_timestamp('3 ЯНВАРЯ 1999', 'DD MONTH YYYY');\nERROR: invalid value \"ЯНВА\" for \"MONTH\"\nDETAIL: The given value did not match any of the allowed values for \nthis field.\n\nThis behavior is reproduced without the patch though (on Postgres 12).\n\nAnd the English case might confuse too I think:\n\n=# select to_date('3 JANUZRY 1999', 'DD MONTH YYYY');\nERROR: invalid value \"JANUZRY 1\" for \"MONTH\"\nDETAIL: The given value did not match any of the allowed values for \nthis field.\n\nUsers might think what means \"1\" in \"JANUZRY 1\" string.\n\nI attached the draft patch, which shows all remaining string. So the \nquery above will show the following:\n\n=# select to_timestamp('3 ЯНВАРЯ 1999', 'DD MONTH YYYY');\nERROR: invalid value \"ЯНВАРЯ 1999\" for \"MONTH\"\nDETAIL: The remaining value did not match any of the allowed values for \nthis field.\n\n> The 0001 patch attached cleans up all the above complaints. I felt\n> that given the business about scribbling on strings we shouldn't,\n> it would also be wise to const-ify the string pointers if possible.\n> That seems not too painful, per 0002 attached.\n\n+1 on the patch.\n\n-- \nArthur", "msg_date": "Thu, 23 Jan 2020 12:17:22 +0900", "msg_from": "Arthur Zakirov <zaartur@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "Arthur Zakirov <zaartur@gmail.com> writes:\n> On 2020/01/23 7:11, Tom Lane wrote:\n>> Closer examination shows that the \"max\" argument is pretty bogus as\n>> well. It doesn't do anything except confuse the reader, because there\n>> are no cases where the value passed is less than the maximum array entry\n>> length, so it never acts to change seq_search's behavior. So we should\n>> just drop that behavior from seq_search, too, and redefine \"max\" as\n>> having no purpose except to specify how much of the string to show in\n>> error messages. There's still a question of what that should be for\n>> non-English cases, but at least we now have a clear idea of what we\n>> need the value to do.\n\n> Shouldn't we just show all remaining string instead of truncating it? \n\nThat would avoid a bunch of arbitrary decisions, for sure.\nAnybody have an objection?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 22 Jan 2020 23:42:01 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2020-Jan-22, Tom Lane wrote:\n\n> Arthur Zakirov <zaartur@gmail.com> writes:\n> > On 2020/01/23 7:11, Tom Lane wrote:\n> >> Closer examination shows that the \"max\" argument is pretty bogus as\n> >> well. It doesn't do anything except confuse the reader, because there\n> >> are no cases where the value passed is less than the maximum array entry\n> >> length, so it never acts to change seq_search's behavior. So we should\n> >> just drop that behavior from seq_search, too, and redefine \"max\" as\n> >> having no purpose except to specify how much of the string to show in\n> >> error messages. There's still a question of what that should be for\n> >> non-English cases, but at least we now have a clear idea of what we\n> >> need the value to do.\n> \n> > Shouldn't we just show all remaining string instead of truncating it? \n> \n> That would avoid a bunch of arbitrary decisions, for sure.\n> Anybody have an objection?\n\nI think it would be clearer to search for whitespace starting at the\nstart of the bogus token and stop there. It might not be perfect,\nparticularly if any language has whitespace in a month etc name (I don't\nknow any example but I guess it's not impossible for it to exist;\nPortuguese weekday names maybe?), but it seems better than either of the\nbehaviors shown above.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 23 Jan 2020 12:55:52 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2020-Jan-22, Tom Lane wrote:\n>> Arthur Zakirov <zaartur@gmail.com> writes:\n>>> Shouldn't we just show all remaining string instead of truncating it? \n\n>> That would avoid a bunch of arbitrary decisions, for sure.\n>> Anybody have an objection?\n\n> I think it would be clearer to search for whitespace starting at the\n> start of the bogus token and stop there. It might not be perfect,\n> particularly if any language has whitespace in a month etc name (I don't\n> know any example but I guess it's not impossible for it to exist;\n> Portuguese weekday names maybe?), but it seems better than either of the\n> behaviors shown above.\n\nI'm okay with that. It won't work so well for cases like\n\"1-Januzry-1999\", but it's still better than what happens now:\n\nregression=# select to_date('1-Januzry-1999', 'DD MONTH YYYY');\nERROR: invalid value \"Januzry-1\" for \"MONTH\"\n\nThat particular case could be improved by stopping at a dash ... but\nsince this code is also used to match strings like \"A.M.\", we can't\njust exclude punctuation in general. Breaking at whitespace seems\nlike a reasonable compromise.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 23 Jan 2020 11:15:23 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2020-Jan-23, Tom Lane wrote:\n\n> That particular case could be improved by stopping at a dash ... but\n> since this code is also used to match strings like \"A.M.\", we can't\n> just exclude punctuation in general. Breaking at whitespace seems\n> like a reasonable compromise.\n\nYeah, and there are cases where dashes are used in names -- browsing\nthrough glibc for example I quickly found Akan, for which the month names are:\n\nmon \"Sanda-<U0186>p<U025B>p<U0254>n\";/\n \"Kwakwar-<U0186>gyefuo\";/\n \"Eb<U0254>w-<U0186>benem\";/\n\nand so on. Even whitespace is problematic for some languages, such as Afan,\n\nmon \"Qunxa Garablu\";/\n \"Naharsi Kudo\";/\n \"Ciggilta Kudo\";/\n(etc) but I think whitespace-splitting is going to be more comprehensible\nin the vast majority of cases, even if not perfect.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 23 Jan 2020 13:49:55 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> Even whitespace is problematic for some languages, such as Afan,\n\n> mon \"Qunxa Garablu\";/\n> \"Naharsi Kudo\";/\n> \"Ciggilta Kudo\";/\n\n> (etc) but I think whitespace-splitting is going to be more comprehensible\n> in the vast majority of cases, even if not perfect.\n\nInteresting. Given that to_date et al are often willing to ignore\nwhitespace in input, I wonder whether we won't have some other issues\nwith names like that --- not so much that basic cases wouldn't work,\nas that people might reasonably expect that, say, we'd be flexible\nabout the amount of whitespace. Seems like a problem for another day\nthough.\n\nIn the meantime, I agree that \"truncate at whitespace\" is a better\nheuristic for the error messages than what we've got. I'll go make it so.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 23 Jan 2020 12:53:16 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "Here's a v7 patch, rebased over my recent hacking, and addressing\nmost of the complaints I raised in <31691.1579648824@sss.pgh.pa.us>.\nHowever, I've got some new complaints now that I've looked harder\nat the code:\n\n* It's not exactly apparent to me why this code should be concerned\nabout non-normalized characters when noplace else in the backend is.\nI think we should either rip that out entirely, or move the logic\ninto str_tolower (and hence also str_toupper etc). I'd tend to favor\nthe former, but of course I don't speak any languages where this would\nbe an issue. Perhaps a better idea is to invent a new SQL function\nthat normalizes a given string, and expect users to call that first\nif they'd like to_date() to match unnormalized text.\n\n* I have no faith in this calculation that decides how long the match\nlength was:\n\n\t\t*len = element_len + name_len - norm_len;\n\nI seriously doubt that this does the right thing if either the\nnormalization or the downcasing changed the byte length of the\nstring. I'm not actually sure how we can do that correctly.\nThere's no good way to know whether the changes happened within\nthe part of the \"name\" string that we matched, or the part beyond\nwhat we matched, but we only want to count the former. So this\nseems like a pretty hard problem, and even if this logic is somehow\ncorrect as it stands, it needs a comment explaining why.\n\n* I'm still concerned about the risk of integer overflow in the\nstring allocations in seq_search_localized(). Those need to be\nadjusted to be more paranoid, similar to the code in e.g. str_tolower.\n\n\t\t\tregards, tom lane", "msg_date": "Thu, 23 Jan 2020 17:00:53 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Thu, Jan 23, 2020 at 11:00 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\nThank you for your time looking into this.\n\nHere's a v7 patch, rebased over my recent hacking, and addressing\n> most of the complaints I raised in <31691.1579648824@sss.pgh.pa.us>.\n> However, I've got some new complaints now that I've looked harder\n> at the code:\n>\n> * It's not exactly apparent to me why this code should be concerned\n> about non-normalized characters when noplace else in the backend is.\n> I think we should either rip that out entirely, or move the logic\n> into str_tolower (and hence also str_toupper etc). I'd tend to favor\n> the former, but of course I don't speak any languages where this would\n> be an issue. Perhaps a better idea is to invent a new SQL function\n> that normalizes a given string, and expect users to call that first\n> if they'd like to_date() to match unnormalized text.\n>\n>\nThere is an open patch that will make the normalization functionality user\nvisible [1]. So, if a user can call to_date(normalize('01 ŞUB 2010'), 'DD\nTMMON YYYY') I would vote to drop the normalization logic inside this patch\naltogether.\n\n* I have no faith in this calculation that decides how long the match\n> length was:\n>\n> *len = element_len + name_len - norm_len;\n>\n> I seriously doubt that this does the right thing if either the\n> normalization or the downcasing changed the byte length of the\n> string. I'm not actually sure how we can do that correctly.\n> There's no good way to know whether the changes happened within\n> the part of the \"name\" string that we matched, or the part beyond\n> what we matched, but we only want to count the former. So this\n> seems like a pretty hard problem, and even if this logic is somehow\n> correct as it stands, it needs a comment explaining why.\n>\n>\nThe proper logic would come from do_to_timestamp() receiving a normalized\n\"date_txt\" input, so we do not operate with unnormalize and normalize\nstrings at the same time.\n\n\n> * I'm still concerned about the risk of integer overflow in the\n> string allocations in seq_search_localized(). Those need to be\n> adjusted to be more paranoid, similar to the code in e.g. str_tolower.\n>\n\nPlease find attached a patch with the normalization logic removed, thus no\ndirect allocations in seq_search_localized().\n\nI would like to rise a couple of questions myself:\n\n* When compiled with DEBUG_TO_FROM_CHAR, there is a warning \"‘dump_node’\ndefined but not used\". Should we drop this function or uncomment its usage?\n\n* Would it be worth moving str_tolower(localized_name)\nfrom seq_search_localized() into cache_locale_time()?\n\n[1]\nhttps://www.postgresql.org/message-id/014866c8-d7ff-2a4f-c185-cf7e3ceb7028%402ndquadrant.com\n\nRegards,\n\nJuan José Santamaría Flecha", "msg_date": "Fri, 24 Jan 2020 10:48:19 +0100", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2020-Jan-24, Juan José Santamaría Flecha wrote:\n\n> There is an open patch that will make the normalization functionality user\n> visible [1]. So, if a user can call to_date(normalize('01 ŞUB 2010'), 'DD\n> TMMON YYYY') I would vote to drop the normalization logic inside this patch\n> altogether.\n\nI was reading the SQL standard on this point, and it says this (4.2.8\nUniversal character sets):\n\n An SQL-implementation may assume that all UCS strings are normalized\n in one of [Unicode normalization forms].\n\nwhich seems to agree with what you're saying.\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 24 Jan 2020 08:44:41 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?= <juanjo.santamaria@gmail.com> writes:\n> On Thu, Jan 23, 2020 at 11:00 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> * It's not exactly apparent to me why this code should be concerned\n>> about non-normalized characters when noplace else in the backend is.\n\n> There is an open patch that will make the normalization functionality user\n> visible [1]. So, if a user can call to_date(normalize('01 ŞUB 2010'), 'DD\n> TMMON YYYY') I would vote to drop the normalization logic inside this patch\n> altogether.\n\nWorks for me.\n\n> * I have no faith in this calculation that decides how long the match\n>> length was:\n>> \t*len = element_len + name_len - norm_len;\n\n> The proper logic would come from do_to_timestamp() receiving a normalized\n> \"date_txt\" input, so we do not operate with unnormalize and normalize\n> strings at the same time.\n\nNo, that only solves half the problem, because the downcasing\ntransformation can change the string length too. Two easy examples:\n\n* In German, I believe \"ß\" downcases to \"ss\". In Latin-1 encoding that's\na length change, though I think it might accidentally not be in UTF8.\n\n* The Turks distinguish dotted and dotless \"i\", so that \"İ\" downcases to\n\"i\", and conversely \"I\" downcases to \"ı\". Those are length changes in\nUTF8, though not in whichever Latin-N encoding works for Turkish.\n\nEven if these cases happen not to apply to any month or day name of\nthe relevant language, we still have a problem, arising from the fact\nthat we're downcasing the whole remaining string --- so length changes\nafter the match could occur anyway.\n\n> I would like to rise a couple of questions myself:\n\n> * When compiled with DEBUG_TO_FROM_CHAR, there is a warning \"‘dump_node’\n> defined but not used\". Should we drop this function or uncomment its usage?\n\nMaybe, but I don't think it belongs in this patch.\n\n> * Would it be worth moving str_tolower(localized_name)\n> from seq_search_localized() into cache_locale_time()?\n\nI think it'd complicate tracking when that cache has to be invalidated\n(i.e. it now depends on more than just LC_TIME). On the whole I wouldn't\nbother unless someone does the measurements to show there'd be a useful\nspeedup.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 24 Jan 2020 10:20:30 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2020-01-24 12:44, Alvaro Herrera wrote:\n> On 2020-Jan-24, Juan José Santamaría Flecha wrote:\n> \n>> There is an open patch that will make the normalization functionality user\n>> visible [1]. So, if a user can call to_date(normalize('01 ŞUB 2010'), 'DD\n>> TMMON YYYY') I would vote to drop the normalization logic inside this patch\n>> altogether.\n> \n> I was reading the SQL standard on this point, and it says this (4.2.8\n> Universal character sets):\n> \n> An SQL-implementation may assume that all UCS strings are normalized\n> in one of [Unicode normalization forms].\n> \n> which seems to agree with what you're saying.\n\nWhen you interact with glibc locale functions, you essentially have to \nassume that everything is in NFC. When using ICU locale functions \n(which we don't here, but just for the sake of argument), then I would \nexpect that ICU does appropriate normalization itself when I call \nicu_what_month_is_this(string) returns int. So I think it is \nappropriate to not deal with normalization in this patch.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 24 Jan 2020 16:24:15 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2020-Jan-24, Peter Eisentraut wrote:\n\n> When you interact with glibc locale functions, you essentially have to\n> assume that everything is in NFC. When using ICU locale functions (which we\n> don't here, but just for the sake of argument), then I would expect that ICU\n> does appropriate normalization itself when I call\n> icu_what_month_is_this(string) returns int. So I think it is appropriate to\n> not deal with normalization in this patch.\n\nBut that's a different POV. The input to this function could come from\narbitrary user input from any application whatsoever. So the only\nreason we can get away with that is because the example regression case\nJuan Jos� added (which uses non-normals) does not conform to the\nstandard.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 24 Jan 2020 13:18:14 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> But that's a different POV. The input to this function could come from\n> arbitrary user input from any application whatsoever. So the only\n> reason we can get away with that is because the example regression case\n> Juan José added (which uses non-normals) does not conform to the\n> standard.\n\nI'm unsure about \"conforming to standard\", but I think it's reasonable\nto put the onus of doing normalization when necessary on the user.\nOtherwise, we need to move normalization logic into basically all\nthe string processing functions (even texteq), which seems like a\npretty huge cost that will benefit only a small minority of people.\n(If it's not a small minority, then where's the bug reports complaining\nthat we don't do it today?)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 24 Jan 2020 11:22:59 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2020-01-24 17:22, Tom Lane wrote:\n> Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n>> But that's a different POV. The input to this function could come from\n>> arbitrary user input from any application whatsoever. So the only\n>> reason we can get away with that is because the example regression case\n>> Juan José added (which uses non-normals) does not conform to the\n>> standard.\n> \n> I'm unsure about \"conforming to standard\", but I think it's reasonable\n> to put the onus of doing normalization when necessary on the user.\n> Otherwise, we need to move normalization logic into basically all\n> the string processing functions (even texteq), which seems like a\n> pretty huge cost that will benefit only a small minority of people.\n> (If it's not a small minority, then where's the bug reports complaining\n> that we don't do it today?)\n\nThese reports do exist, and this behavior is known. However, the impact \nis mostly that results \"look wrong\" (looks the same but doesn't compare \nas equal) rather than causing inconsistency and corruption, so it's \nmostly shrugged off. The nondeterministic collation feature was \nintroduced in part to be able to deal with this; the pending \nnormalization patch is another. However, this behavior is baked deeply \ninto Unicode, so no single feature or facility will simply make it go away.\n\nAFAICT, we haven't so far had any code that does a lookup of non-ASCII \nstrings in a table, so that's why we haven't had this discussion yet.\n\nNow that I think about it, you could also make an argument that this \nshould be handled through collation, so the function that looks up the \nstring in the locale table should go through texteq. However, this \nwould mostly satisfy the purists but create a bizarre user experience.\n\nLooking through the patch quickly, if you want to get Unicode-fancy, \ndoing a case-insensitive comparison by running lower-case on both \nstrings is also wrong in corner cases. All the Greek month names end in \nsigma, so I suspect that this patch might not work correctly in such cases.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 24 Jan 2020 17:42:31 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> Looking through the patch quickly, if you want to get Unicode-fancy, \n> doing a case-insensitive comparison by running lower-case on both \n> strings is also wrong in corner cases. All the Greek month names end in \n> sigma, so I suspect that this patch might not work correctly in such cases.\n\nHm. That's basically what citext does, and I don't recall hearing\ncomplaints about that. What other definition of \"case insensitive\"\nwould you suggest?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 24 Jan 2020 11:46:48 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Fri, Jan 24, 2020 at 5:46 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> > Looking through the patch quickly, if you want to get Unicode-fancy,\n> > doing a case-insensitive comparison by running lower-case on both\n> > strings is also wrong in corner cases. All the Greek month names end in\n> > sigma, so I suspect that this patch might not work correctly in such\n> cases.\n>\n> Hm. That's basically what citext does, and I don't recall hearing\n> complaints about that. What other definition of \"case insensitive\"\n> would you suggest?\n>\n>\nTo illustrate the issue, it does not work as expected:\n\npostgres=# select lower(to_char(now(),'TMMONTH'));\n lower\n------------\n ιανουάριοσ\n(1 row)\n\npostgres=# select to_char(now(),'TMmonth');\n to_char\n------------\n ιανουάριος\n(1 row)\n\nRegards,\n\nJuan José Santamaría Flecha\n\nOn Fri, Jan 24, 2020 at 5:46 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> Looking through the patch quickly, if you want to get Unicode-fancy, \n> doing a case-insensitive comparison by running lower-case on both \n> strings is also wrong in corner cases.  All the Greek month names end in \n> sigma, so I suspect that this patch might not work correctly in such cases.\n\nHm.  That's basically what citext does, and I don't recall hearing\ncomplaints about that.  What other definition of \"case insensitive\"\nwould you suggest?To illustrate the issue, it does not work as expected:postgres=# select lower(to_char(now(),'TMMONTH'));   lower------------ ιανουάριοσ(1 row)postgres=# select to_char(now(),'TMmonth');  to_char------------ ιανουάριος(1 row)Regards,Juan José Santamaría Flecha", "msg_date": "Fri, 24 Jan 2020 18:25:11 +0100", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2020-01-24 18:25, Juan José Santamaría Flecha wrote:\n> To illustrate the issue, it does not work as expected:\n> \n> postgres=# select lower(to_char(now(),'TMMONTH'));\n>    lower\n> ------------\n>  ιανουάριοσ\n> (1 row)\n> \n> postgres=# select to_char(now(),'TMmonth');\n>   to_char\n> ------------\n>  ιανουάριος\n> (1 row)\n\nWell, this is interesting, because on macOS and Debian stable I get\n\npostgres=# select to_char(now(),'TMmonth');\n to_char\n------------\n ιανουαρίου\n(1 row)\n\nwhich is the genitive of ιανουάριος. You use the genitive form for a \ndate (24th of January) but the nominative otherwise. But the reverse \nmapping can only take one of these forms. So here\n\nselect to_date('Ιανουαριος', 'TMMonth');\n\nfails, which is bad.\n\nIn the glibc locale data sources they have both forms listed, but \napparently the API were are using only accepts one of them.\n\n(I don't know any Greek, I'm just extrapolating from Wikipedia and \nlocale data.)\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 24 Jan 2020 19:01:41 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2020-01-24 19:01, Peter Eisentraut wrote:\n> postgres=# select to_char(now(),'TMmonth');\n> to_char\n> ------------\n> ιανουαρίου\n> (1 row)\n> \n> which is the genitive of ιανουάριος. You use the genitive form for a\n> date (24th of January) but the nominative otherwise. But the reverse\n> mapping can only take one of these forms. So here\n> \n> select to_date('Ιανουαριος', 'TMMonth');\n> \n> fails, which is bad.\n\nFor the record, the correct form of that would appear to be\n\nselect to_date('Ιανουάριος', 'TMMonth');\n\nwith the accent. I had tried different variations of that and they all \nfailed.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Sat, 25 Jan 2020 10:31:42 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> For the record, the correct form of that would appear to be\n> select to_date('Ιανουάριος', 'TMMonth');\n> with the accent. I had tried different variations of that and they all \n> failed.\n\nOK, so for anyone who is as confused as I was, the main point here\nseems to be this: the upper case form of Greek sigma is 'Σ',\nand the lower case form is 'σ' ... except as the final letter of\na word, where it is supposed to be written like 'ς'.\n\nIf I set lc_collate, lc_ctype, and lc_time to 'el_GR.utf8',\nthen (on a somewhat hoary glibc platform) I get\n\nu8=# select to_char('2020-01-01'::timestamptz, 'TMMONTH'); \n to_char \n----------------------\n ΙΑΝΟΥΆΡΙΟΣ\n(1 row)\n\nu8=# select to_char('2020-01-01'::timestamptz, 'TMMonth');\n to_char \n----------------------\n Ιανουάριος\n(1 row)\n\nu8=# select to_char('2020-01-01'::timestamptz, 'TMmonth');\n to_char \n----------------------\n ιανουάριος\n(1 row)\n\nwhich is correct AFAICS ... but\n\nu8=# select lower(to_char('2020-01-01'::timestamptz, 'TMMONTH'));\n lower \n----------------------\n ιανουάριοσ\n(1 row)\n\nSo what we actually have here, ISTM, is a bug in lower() not to_char().\nThe bug is unsurprising because str_tolower() simply applies towlower_l()\nto each character independently, so there's no way for it to account for\nthe word-final rule. I'm not aware that glibc provides any API whereby\nthat could be done correctly. On the other hand, we get it right when\nusing an ICU collation for lower():\n\nu8=# select lower(to_char('2020-01-01'::timestamptz, 'TMMONTH') collate \"el-gr-x-icu\");\n lower \n----------------------\n ιανουάριος\n(1 row)\n\nbecause that code path passes the whole string to ICU at once, and\nof course getting this right is ICU's entire job.\n\nI haven't double-checked, but I imagine that the reason that to_char\ngets the month name case-folding right is that what comes out of\nstrftime(...\"%B\"...) is \"Ιανουάριος\" which we are able to upcase\ncorrectly, while the downcasing code paths don't affect 'ς'.\n\nI thought for a little bit about trying to dodge this issue in the\npatch by folding to upper case, not lower, before comparing month/day\nnames. I fear that that would just shift the problem cases to some\nother language(s). However, it makes Greek better, and I think it\nmakes German better (does 'ß' appear in any month/day names there?),\nso maybe we should just roll with that. In the end, it doesn't seem\nright to reject this patch just because lower() is broken on some\nplatforms.\n\nThe other question your example raises is whether we should be trying\nto de-accent before comparison, ie was it right for 'Ιανουάριος' to\nbe treated differently from 'Ιανουαριος'. I don't know enough Greek\nto say, but it kind of feels like that should be outside to_date's\npurview.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 27 Jan 2020 21:11:57 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "\n\n> On Jan 27, 2020, at 6:11 PM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> and I think it\n> makes German better (does 'ß' appear in any month/day names there?),\n> so maybe we should just roll with that. \n\nTo my knowledge, neither /ß/ nor /ss/ occur in day or month names in German, neither presently nor in recent times, so I wouldn’t expect it to matter for German whether you use uppercase or lowercase.\n\n> \n> The other question your example raises is whether we should be trying\n> to de-accent before comparison, ie was it right for 'Ιανουάριος' to\n> be treated differently from 'Ιανουαριος'. I don't know enough Greek\n> to say, but it kind of feels like that should be outside to_date's\n> purview.\n\nI’m getting a little lost here. German uses both Sonnabend and Samstag for Saturday, so don’t you have to compare to a list of values anyway? I don’t know Norwegian, but Wikipedia shows both sundag and søndag for Sunday in Norwegian Nynorsk. Faroese seems to have a few similar cases. Whether those languages have alternate day names both in common usage, I can’t say, but both Sonnabend and Samstag are still in use in the German speaking world. If you need to compare against lists, then I would think you could put both ιανουάριοσ and ιανουάριος into a list, even if only one of them is grammatically correct Greek. I’d think that unaccented versions of names might also go into the list, depending on whether speakers of that language consider them equivalent. That sounds like something for the translators to hash out.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Mon, 27 Jan 2020 19:05:48 -0800", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2020-01-28 04:05, Mark Dilger wrote:\n> German uses both Sonnabend and Samstag for Saturday, so don’t you have to compare to a list of values anyway?\n\nYeah, good point. If it doesn't accept both \"Sonnabend\" and \"Samstag\", \nthen it's not really usable.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 28 Jan 2020 09:00:16 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2020-01-28 03:11, Tom Lane wrote:\n> The other question your example raises is whether we should be trying\n> to de-accent before comparison, ie was it right for 'Ιανουάριος' to\n> be treated differently from 'Ιανουαριος'. I don't know enough Greek\n> to say, but it kind of feels like that should be outside to_date's\n> purview.\n\nTo clarify, nothing in my examples was meant to imply that de-accenting \nmight be necessary. AFAICT, the accented forms are the only \nlinguistically acceptable forms and all the locale libraries accept them \ncorrectly in their accented forms.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 28 Jan 2020 09:02:36 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> On 2020-01-28 04:05, Mark Dilger wrote:\n>> German uses both Sonnabend and Samstag for Saturday, so don’t you have to compare to a list of values anyway?\n\n> Yeah, good point. If it doesn't accept both \"Sonnabend\" and \"Samstag\", \n> then it's not really usable.\n\nIf we're going to insist on that, then the entire patch is junk.\nIndeed, I don't even know where we could get the knowledge of which\nname(s) to accept, because strftime is surely only going to tell us\none of them.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 28 Jan 2020 09:51:27 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "\n\n> On Jan 28, 2020, at 6:51 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n>> On 2020-01-28 04:05, Mark Dilger wrote:\n>>> German uses both Sonnabend and Samstag for Saturday, so don’t you have to compare to a list of values anyway?\n> \n>> Yeah, good point. If it doesn't accept both \"Sonnabend\" and \"Samstag\", \n>> then it's not really usable.\n> \n> If we're going to insist on that, then the entire patch is junk.\n\nI’m not insisting, just asking about the design. If it only works with one name supported per weekday per language, and per month per language, I’m not going to object. I was just curious if you were going to support multiple names anyway, and if that made the question about the Greek case folding less pressing.\n\n> Indeed, I don't even know where we could get the knowledge of which\n> name(s) to accept, because strftime is surely only going to tell us\n> one of them.\n\nI haven’t played with this yet, but per the manual page for strftime_l:\n\n> %A is replaced by national representation of the full weekday name.\n> \n> %a is replaced by national representation of the abbreviated weekday name.\n> \n> %B is replaced by national representation of the full month name.\n> \n> %b is replaced by national representation of the abbreviated month name.\n\nWhich I think gives you just the preferred name, by whatever means the library decides which of Sonnabend/Samstag is the preferred name. But then the manual page goes on to say:\n\n> %E* %O*\n> POSIX locale extensions. The sequences %Ec %EC %Ex %EX %Ey %EY %Od %Oe %OH %OI %Om %OM %OS %Ou %OU %OV %Ow %OW %Oy are supposed to provide alternate representations.\n> \n> Additionally %OB implemented to represent alternative months names (used standalone, without day mentioned).\n\nThis is the part I haven’t played with, but it sounds like it can handle at least one alternate name. Perhaps you can get the alternates this way?\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Tue, 28 Jan 2020 07:06:15 -0800", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Tue, Jan 28, 2020 at 4:06 PM Mark Dilger <mark.dilger@enterprisedb.com>\nwrote:\n\n>\n> I’m not insisting, just asking about the design. If it only works with\n> one name supported per weekday per language, and per month per language,\n> I’m not going to object. I was just curious if you were going to support\n> multiple names anyway, and if that made the question about the Greek case\n> folding less pressing.\n>\n>\nThis patch targets to do something symmetrical to to_char(), which will\njust return a single value.\n\nThe issue with the greek locale is that it cannot hold this equivalent\nbehaviour, as in:\n\npostgres=# select to_date(to_char(now(), 'TMMONTH'), 'TMMONTH');\nERROR: invalid value \"ΙΑΝΟΥΆΡΙΟΣ\" for \"MONTH\"\n\nBecause of the particular behaviour sigma (Σσς) casing has, which is also\nuser visible with a lower().\n\n\n>\n> > %E* %O*\n> > POSIX locale extensions. The sequences %Ec %EC %Ex %EX %Ey\n> %EY %Od %Oe %OH %OI %Om %OM %OS %Ou %OU %OV %Ow %OW %Oy are supposed to\n> provide alternate representations.\n> >\n> > Additionally %OB implemented to represent alternative months\n> names (used standalone, without day mentioned).\n>\n> This is the part I haven’t played with, but it sounds like it can handle\n> at least one alternate name. Perhaps you can get the alternates this way?\n>\n>\nThis looks like a POSIX feature that some systems might not like (Windows\n[1]). But if this is something that the patch should aim to, I am fine with\na RWF and give it another try in the future.\n\n[1]\nhttps://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/strftime-wcsftime-strftime-l-wcsftime-l?view=vs-2019\n\nRegards,\n\nJuan José Santamaría Flecha\n\nOn Tue, Jan 28, 2020 at 4:06 PM Mark Dilger <mark.dilger@enterprisedb.com> wrote:I’m not insisting, just asking about the design.  If it only works with one name supported per weekday per language, and per month per language, I’m not going to object.  I was just curious if you were going to support multiple names anyway, and if that made the question about the Greek case folding less pressing.\nThis patch targets to do something symmetrical to to_char(), which will just return a single value.The issue with the greek locale is that it cannot hold this equivalent behaviour, as in:postgres=# select to_date(to_char(now(), 'TMMONTH'), 'TMMONTH');ERROR:  invalid value \"ΙΑΝΟΥΆΡΙΟΣ\" for \"MONTH\"Because of the particular behaviour\n\nsigma (Σσς) casing has, which is also user visible with a lower(). >      %E* %O*\n>            POSIX locale extensions.  The sequences %Ec %EC %Ex %EX %Ey %EY %Od %Oe %OH %OI %Om %OM %OS %Ou %OU %OV %Ow %OW %Oy are supposed to provide alternate representations.\n> \n>            Additionally %OB implemented to represent alternative months names (used standalone, without day mentioned).\n\nThis is the part I haven’t played with, but it sounds like it can handle at least one alternate name.  Perhaps you can get the alternates this way?This looks like a POSIX feature that some systems might not like (Windows [1]). But if this is something that the patch should aim to, I am fine with a RWF and give it another try in the future.[1] https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/strftime-wcsftime-strftime-l-wcsftime-l?view=vs-2019Regards,Juan José Santamaría Flecha", "msg_date": "Tue, 28 Jan 2020 16:47:27 +0100", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "\n\n> On Jan 28, 2020, at 7:47 AM, Juan José Santamaría Flecha <juanjo.santamaria@gmail.com> wrote:\n> \n> This looks like a POSIX feature that some systems might not like (Windows [1]). But if this is something that the patch should aim to, I am fine with a RWF and give it another try in the future.\n\nAs long as this implementation doesn’t create a backward-compatibility problem when doing a more complete implementation later, I’m fine with this patch not tackling the whole problem.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Tue, 28 Jan 2020 08:06:27 -0800", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2020-Jan-28, Peter Eisentraut wrote:\n\n> On 2020-01-28 04:05, Mark Dilger wrote:\n> > German uses both Sonnabend and Samstag for Saturday, so don’t you have to compare to a list of values anyway?\n> \n> Yeah, good point. If it doesn't accept both \"Sonnabend\" and \"Samstag\", then\n> it's not really usable.\n\nThe string \"Sonnabend\" never appears in the glibc sources, so that will\ncertainly not work. I vote not to care about that, but of course my\nlanguage is not one that has alternate weekday/month names. I guess if\nwe're intent on recognizing alternate names, we'll have to build our own\nlist of them :-(\n\nI don't have the ICU sources here to check the status there.\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 28 Jan 2020 13:21:44 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n> But then the manual page goes on to say:\n\n>> %E* %O*\n>> POSIX locale extensions. The sequences %Ec %EC %Ex %EX %Ey %EY %Od %Oe %OH %OI %Om %OM %OS %Ou %OU %OV %Ow %OW %Oy are supposed to provide alternate representations.\n>> \n>> Additionally %OB implemented to represent alternative months names (used standalone, without day mentioned).\n\n> This is the part I haven’t played with, but it sounds like it can handle at least one alternate name. Perhaps you can get the alternates this way?\n\nThis sounded promising, but the POSIX strftime spec doesn't mention %OB,\nso I'm afraid we can't count on it to do much. At this point I'm not\nreally convinced that there are no languages with more than two forms,\nanyway :-(.\n\nI also wondered whether we could get any further by using strptime() to\nconvert localized month and day names on-the-fly, rather than the patch's\ncurrent approach of re-using strftime() results. If strptime() fails\nto support alternative names, it's their bug not ours. Unfortunately,\nglibc has got said bug (AFAICS anyway), so in practice this would only\noffer us plausible deniability and not much of any real functionality.\n\nIn the end it seems like we could only handle alternative names by\nkeeping our own lists of them. There are probably few enough cases\nthat that wouldn't be a tremendous maintenance problem, but what\nI'm not quite seeing is how we'd decide which list to use when.\nRight now, locale identifiers are pretty much opaque to us ... do\nwe really want to get into the business of recognizing that such a\nname refers to German, or Greek?\n\nA brute-force answer, if there are few enough cases, is to recognize\nthem regardless of the specific value of LC_TIME. Do we think\nanybody would notice or care if to_date('Sonnabend', 'TMDay') works\neven when in a non-German locale?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 28 Jan 2020 12:30:42 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "\n\n> On Jan 28, 2020, at 9:30 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> \n> A brute-force answer, if there are few enough cases, is to recognize\n> them regardless of the specific value of LC_TIME. Do we think\n> anybody would notice or care if to_date('Sonnabend', 'TMDay') works\n> even when in a non-German locale?\n\nI think this only becomes a problem if there are weekday or month name collisions between languages where they have different meanings. As an absurd hypothetical, if “Sunday” in Tagalog means what “Tuesday” means in English, then you’ve got a problem.\n\nThis does happen for month abbreviations. “Mar” is short for “March” and variations in a number of languages, but short for “November” in Finnish.\n\nFor day abbreviations, “Su” collides between fi_FI and hr_HR, and “tor” collides between sl_SL and no_NO.\n\nI don’t see any collisions with full month or full weekday names, but I’m also only looking at the 53 locales installed in /usr/share/locale/.*/LC_TIME on my mac.\n\n—\nMark Dilger\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n\n\n\n", "msg_date": "Tue, 28 Jan 2020 11:05:09 -0800", "msg_from": "Mark Dilger <mark.dilger@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "Mark Dilger <mark.dilger@enterprisedb.com> writes:\n>> On Jan 28, 2020, at 9:30 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> A brute-force answer, if there are few enough cases, is to recognize\n>> them regardless of the specific value of LC_TIME. Do we think\n>> anybody would notice or care if to_date('Sonnabend', 'TMDay') works\n>> even when in a non-German locale?\n\n> I think this only becomes a problem if there are weekday or month name collisions between languages where they have different meanings. As an absurd hypothetical, if “Sunday” in Tagalog means what “Tuesday” means in English, then you’ve got a problem.\n\n> This does happen for month abbreviations. “Mar” is short for “March” and variations in a number of languages, but short for “November” in Finnish.\n\n> For day abbreviations, “Su” collides between fi_FI and hr_HR, and “tor” collides between sl_SL and no_NO.\n\nBut none of those cases are alternative names, so we wouldn't have\nentries for them in this hypothetical list. They'd only be recognized\nwhen strftime() returns them. I suspect also that the abbreviated\nnames have few if any alternatives, so we may only need this whole hack\nfor full names.\n\nA possible way of tightening things up without explicitly decoding the\nlocale name is to make the entries of the list be string pairs: \"if\nstrftime() returned this, then also consider that\". That puts a bit\nof a premium on knowing which names strftime considers primary, but\nI think we'd have had to know that anyway.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 28 Jan 2020 14:37:50 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On 2020-01-28 16:47, Juan José Santamaría Flecha wrote:\n> This patch targets to do something symmetrical to to_char(), which will \n> just return a single value.\n\nI didn't fully realize while reading this thread that to_char() already \nsupports localized output and this patch indeed just wants to do the \nopposite.\n\nSo I'm withdrawing my concerns with respect to this patch. As long as \nit can do a roundtrip conversion with to_char(), it's fine.\n\nIt's pretty clear that this interface cannot be useful for producing or \nparsing fully general localized dates. But since it exists now (and \nit's quasi SQL standard now), we might as well fill in this gap.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 28 Jan 2020 21:35:25 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Tue, Jan 28, 2020 at 5:21 PM Alvaro Herrera <alvherre@2ndquadrant.com>\nwrote:\n\n> On 2020-Jan-28, Peter Eisentraut wrote:\n>\n> > On 2020-01-28 04:05, Mark Dilger wrote:\n> > > German uses both Sonnabend and Samstag for Saturday, so don’t you have\n> to compare to a list of values anyway?\n> >\n> > Yeah, good point. If it doesn't accept both \"Sonnabend\" and \"Samstag\",\n> then\n> > it's not really usable.\n>\n> The string \"Sonnabend\" never appears in the glibc sources, so that will\n> certainly not work. I vote not to care about that, but of course my\n> language is not one that has alternate weekday/month names. I guess if\n> we're intent on recognizing alternate names, we'll have to build our own\n> list of them :-(\n>\n> I don't have the ICU sources here to check the status there.\n>\n>\n\"Sonnabend\" is neither available in ICU.\n\nWhat is available are both genitive and nominative forms for months, as\nreported up thread by Peter. See formats \"M\" and \"L\" in:\n\nhttp://userguide.icu-project.org/formatparse/datetime\n\nRegards,\n\nJuan José Santamaría Flecha\n\nOn Tue, Jan 28, 2020 at 5:21 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:On 2020-Jan-28, Peter Eisentraut wrote:\n\n> On 2020-01-28 04:05, Mark Dilger wrote:\n> > German uses both Sonnabend and Samstag for Saturday, so don’t you have to compare to a list of values anyway?\n> \n> Yeah, good point.  If it doesn't accept both \"Sonnabend\" and \"Samstag\", then\n> it's not really usable.\n\nThe string \"Sonnabend\" never appears in the glibc sources, so that will\ncertainly not work.  I vote not to care about that, but of course my\nlanguage is not one that has alternate weekday/month names.  I guess if\nwe're intent on recognizing alternate names, we'll have to build our own\nlist of them :-(\n\nI don't have the ICU sources here to check the status there.\n\n\"Sonnabend\" is neither available in ICU.What is available are both genitive and nominative forms for months, as reported up thread by Peter. See formats \"M\" and \"L\" in:http://userguide.icu-project.org/formatparse/datetimeRegards,Juan José Santamaría Flecha", "msg_date": "Tue, 28 Jan 2020 23:07:13 +0100", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Tue, Jan 28, 2020 at 9:35 PM Peter Eisentraut <\npeter.eisentraut@2ndquadrant.com> wrote:\n\n> On 2020-01-28 16:47, Juan José Santamaría Flecha wrote:\n> > This patch targets to do something symmetrical to to_char(), which will\n> > just return a single value.\n>\n> I didn't fully realize while reading this thread that to_char() already\n> supports localized output and this patch indeed just wants to do the\n> opposite.\n>\n> So I'm withdrawing my concerns with respect to this patch. As long as\n> it can do a roundtrip conversion with to_char(), it's fine.\n>\n>\nWe can avoid issues with non injective case conversion languages with a\ndouble conversion, so both strings in the comparison end up in the same\nstate.\n\nI propose an upper/lower conversion as in the attached patch.\n\nRegards,\n\nJuan José Santamaría Flecha", "msg_date": "Fri, 31 Jan 2020 14:02:51 +0100", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?= <juanjo.santamaria@gmail.com> writes:\n> On Tue, Jan 28, 2020 at 9:35 PM Peter Eisentraut <\n> peter.eisentraut@2ndquadrant.com> wrote:\n>> So I'm withdrawing my concerns with respect to this patch. As long as\n>> it can do a roundtrip conversion with to_char(), it's fine.\n\n> We can avoid issues with non injective case conversion languages with a\n> double conversion, so both strings in the comparison end up in the same\n> state.\n> I propose an upper/lower conversion as in the attached patch.\n\nThis seems pretty reasonable to me, with a couple of caveats:\n\n* I don't think it's appropriate to hard-wire DEFAULT_COLLATION_OID\nas the collation to do case-folding with. For to_date/to_timestamp,\nwe have collatable text input so we can rely on the function's input\ncollation instead, at the cost of having to pass down the collation\nOID through a few layers of subroutines :-(. For parse_datetime,\nI punted for now and let it use DEFAULT_COLLATION_OID, because that's\ncurrently only called by JSONB code that probably hasn't got a usable\ninput collation anyway (since jsonb isn't considered collatable).\n\n* I think it's likely worthwhile to do a quick check for an exact\nmatch before we go through all these case-folding pushups. If the\nexpected use-case is reversing to_char() output, that will win all\nthe time. We're probably ahead of the game even if it only matches\na few percent of the time.\n\nAttached v10 incorporates those improvements, plus a bit of\npolishing of docs and comments. Barring objections, this seems\ncommittable to me.\n\n\t\t\tregards, tom lane", "msg_date": "Sat, 29 Feb 2020 16:36:25 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "I wrote:\n> * I don't think it's appropriate to hard-wire DEFAULT_COLLATION_OID\n> as the collation to do case-folding with. For to_date/to_timestamp,\n> we have collatable text input so we can rely on the function's input\n> collation instead, at the cost of having to pass down the collation\n> OID through a few layers of subroutines :-(. For parse_datetime,\n> I punted for now and let it use DEFAULT_COLLATION_OID, because that's\n> currently only called by JSONB code that probably hasn't got a usable\n> input collation anyway (since jsonb isn't considered collatable).\n\nOn closer look, it's probably a wise idea to change the signature\nof parse_datetime() to include a collation argument, because that\nfunction is new in v13 so there's no API-break argument against it.\nIt will never be cheaper to change it than today. So v11 below\ndoes that, pushing the use of DEFAULT_COLLATION_OID into the\njson-specific code. Perhaps somebody else would like to look at\nwhether there's something brighter for that code to do, but I still\nsuspect there isn't, so I didn't chase it further.\n\n> Barring objections, this seems\n> committable to me.\n\nGoing once, going twice ...\n\n\t\t\tregards, tom lane", "msg_date": "Sun, 01 Mar 2020 17:25:30 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Sun, Mar 1, 2020 at 11:25 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n>\n> > Barring objections, this seems\n> > committable to me.\n>\n> Going once, going twice ...\n>\n\nYou have moved this to better place, so none from me, and thank you.\n\nRegards,\n\nJuan José Santamaría Flecha\n\nOn Sun, Mar 1, 2020 at 11:25 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Barring objections, this seems\n> committable to me.\n\nGoing once, going twice ...You have moved this to better place, so none from me, and thank you.Regards,Juan José Santamaría Flecha", "msg_date": "Mon, 2 Mar 2020 10:10:57 +0100", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?= <juanjo.santamaria@gmail.com> writes:\n> On Sun, Mar 1, 2020 at 11:25 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Going once, going twice ...\n\n> You have moved this to better place, so none from me, and thank you.\n\nPushed then.\n\nWhile looking over the patch one more time, I noticed some pretty poor\nEnglish in docs and error messages for the related jsonb code, so\nI took it on myself to fix that while at it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 03 Mar 2020 11:09:00 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Tue, Mar 3, 2020 at 11:09 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> =?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?= <\n> juanjo.santamaria@gmail.com> writes:\n> > On Sun, Mar 1, 2020 at 11:25 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> Going once, going twice ...\n>\n> > You have moved this to better place, so none from me, and thank you.\n>\n> Pushed then.\n>\n\nOn master with a clean build (and configure re-run) and a fresh init-db,\nI'm seeing the collate.linux.utf8 test fail with the attached diff.\n\nIs there something I need to reconfigure, install on my machine (elementary\nos, so based on Ubuntu) for this to pass?\n\nThanks,\nJames", "msg_date": "Sat, 7 Mar 2020 21:19:06 -0500", "msg_from": "James Coleman <jtc331@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "James Coleman <jtc331@gmail.com> writes:\n> On master with a clean build (and configure re-run) and a fresh init-db,\n> I'm seeing the collate.linux.utf8 test fail with the attached diff.\n\n -- to_char\n SET lc_time TO 'tr_TR';\n+ERROR: invalid value for parameter \"lc_time\": \"tr_TR\"\n SELECT to_char(date '2010-02-01', 'DD TMMON YYYY');\n\nLooks like you may not have Turkish locale installed? Try\n\nlocale -a | grep tr_TR\n\nIf you don't see \"tr_TR.utf8\" or some variant spelling of that,\nthe collate.linux.utf8 test is not gonna pass. The required\npackage is probably some sub-package of glibc.\n\nA workaround if you don't want to install more stuff is to run the\nregression tests in C locale, so that that test script gets skipped.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 07 Mar 2020 21:31:17 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Sat, Mar 7, 2020 at 9:31 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> James Coleman <jtc331@gmail.com> writes:\n> > On master with a clean build (and configure re-run) and a fresh init-db,\n> > I'm seeing the collate.linux.utf8 test fail with the attached diff.\n>\n> -- to_char\n> SET lc_time TO 'tr_TR';\n> +ERROR: invalid value for parameter \"lc_time\": \"tr_TR\"\n> SELECT to_char(date '2010-02-01', 'DD TMMON YYYY');\n>\n> Looks like you may not have Turkish locale installed? Try\n>\n> locale -a | grep tr_TR\n>\n> If you don't see \"tr_TR.utf8\" or some variant spelling of that,\n> the collate.linux.utf8 test is not gonna pass. The required\n> package is probably some sub-package of glibc.\n>\n> A workaround if you don't want to install more stuff is to run the\n> regression tests in C locale, so that that test script gets skipped.\n>\n> regards, tom lane\n>\n\nHmm, when I grep the locales I see `tr_TR.utf8` in the output. I assume the\nutf8 version is acceptable? Or is there a non-utf8 variant?\n\nThanks,\nJames\n\nOn Sat, Mar 7, 2020 at 9:31 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:James Coleman <jtc331@gmail.com> writes:\n> On master with a clean build (and configure re-run) and a fresh init-db,\n> I'm seeing the collate.linux.utf8 test fail with the attached diff.\n\n -- to_char\n SET lc_time TO 'tr_TR';\n+ERROR:  invalid value for parameter \"lc_time\": \"tr_TR\"\n SELECT to_char(date '2010-02-01', 'DD TMMON YYYY');\n\nLooks like you may not have Turkish locale installed?  Try\n\nlocale -a | grep tr_TR\n\nIf you don't see \"tr_TR.utf8\" or some variant spelling of that,\nthe collate.linux.utf8 test is not gonna pass.  The required\npackage is probably some sub-package of glibc.\n\nA workaround if you don't want to install more stuff is to run the\nregression tests in C locale, so that that test script gets skipped.\n\n                        regards, tom laneHmm, when I grep the locales I see `tr_TR.utf8` in the output. I assume the utf8 version is acceptable? Or is there a non-utf8 variant?Thanks,James", "msg_date": "Sat, 7 Mar 2020 21:33:40 -0500", "msg_from": "James Coleman <jtc331@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "James Coleman <jtc331@gmail.com> writes:\n> On Sat, Mar 7, 2020 at 9:31 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Looks like you may not have Turkish locale installed? Try\n>> locale -a | grep tr_TR\n\n> Hmm, when I grep the locales I see `tr_TR.utf8` in the output. I assume the\n> utf8 version is acceptable? Or is there a non-utf8 variant?\n\nHmm ... I'm far from an expert on the packaging of locale data, but\nthe simplest explanation I can think of is that the tr_TR locale exists\nto some extent on your machine but the LC_TIME component of that is\nmissing.\n\nDo you get different results from \"date\" depending on the locale?\nI get\n\n$ LANG=C date\nSat Mar 7 21:44:24 EST 2020\n$ LANG=tr_TR.utf8 date\nCts Mar 7 21:44:26 EST 2020\n\non my Fedora 30 box.\n\nAnother possibility perhaps is that you have partial locale settings\nin your environment that are bollixing the test. Try\n\n$ env | grep ^LANG\n$ env | grep ^LC_\n\nIf there's more than one relevant environment setting, and they\ndon't all agree, I'm not sure what would happen with our\nregression tests.\n\nBTW, what platform are you using anyway?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 07 Mar 2020 21:47:59 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Sun, Mar 8, 2020 at 3:48 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> James Coleman <jtc331@gmail.com> writes:\n> > On Sat, Mar 7, 2020 at 9:31 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> Looks like you may not have Turkish locale installed? Try\n> >> locale -a | grep tr_TR\n>\n> > Hmm, when I grep the locales I see `tr_TR.utf8` in the output. I assume\n> the\n> > utf8 version is acceptable? Or is there a non-utf8 variant?\n>\n> Hmm ... I'm far from an expert on the packaging of locale data, but\n> the simplest explanation I can think of is that the tr_TR locale exists\n> to some extent on your machine but the LC_TIME component of that is\n> missing.\n>\n\n AFAICS, the locale 'tr_TR' uses the encoding ISO-8859-9 (LATIN5), is not\nthe same as 'tr_TR.utf8'.\n\n\n> BTW, what platform are you using anyway?\n>\n\nI have just checked in a Debian Stretch\n\nRegards,\n\nJuan José Santamaría Flecha\n\nOn Sun, Mar 8, 2020 at 3:48 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:James Coleman <jtc331@gmail.com> writes:\n> On Sat, Mar 7, 2020 at 9:31 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Looks like you may not have Turkish locale installed?  Try\n>> locale -a | grep tr_TR\n\n> Hmm, when I grep the locales I see `tr_TR.utf8` in the output. I assume the\n> utf8 version is acceptable? Or is there a non-utf8 variant?\n\nHmm ... I'm far from an expert on the packaging of locale data, but\nthe simplest explanation I can think of is that the tr_TR locale exists\nto some extent on your machine but the LC_TIME component of that is\nmissing. AFAICS, the locale 'tr_TR' uses the encoding ISO-8859-9 (LATIN5), is not the same as 'tr_TR.utf8'.\nBTW, what platform are you using anyway?\n\nI have just checked in a Debian Stretch  Regards,Juan José Santamaría Flecha", "msg_date": "Sun, 8 Mar 2020 12:16:56 +0100", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Sat, Mar 7, 2020 at 9:48 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> James Coleman <jtc331@gmail.com> writes:\n> > On Sat, Mar 7, 2020 at 9:31 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> Looks like you may not have Turkish locale installed? Try\n> >> locale -a | grep tr_TR\n>\n> > Hmm, when I grep the locales I see `tr_TR.utf8` in the output. I assume\n> the\n> > utf8 version is acceptable? Or is there a non-utf8 variant?\n>\n> Hmm ... I'm far from an expert on the packaging of locale data, but\n> the simplest explanation I can think of is that the tr_TR locale exists\n> to some extent on your machine but the LC_TIME component of that is\n> missing.\n>\n> Do you get different results from \"date\" depending on the locale?\n> I get\n>\n> $ LANG=C date\n> Sat Mar 7 21:44:24 EST 2020\n> $ LANG=tr_TR.utf8 date\n> Cts Mar 7 21:44:26 EST 2020\n>\n\n$ LANG=C date\nSun Mar 8 09:27:50 EDT 2020\n$ LANG=tr_TR.utf8 date\nPaz Mar 8 09:27:54 EDT 2020\n$ LANG=tr_TR date\nSun Mar 8 09:27:57 EDT 2020\n\nI'm curious if you get something different for that last one (no utf8\nqualifier).\n\non my Fedora 30 box.\n>\n> Another possibility perhaps is that you have partial locale settings\n> in your environment that are bollixing the test. Try\n>\n> $ env | grep ^LANG\n>\n\nThis gives me:\nLANG=en_US.UTF-8\nLANGUAGE=en_US\n\n\n> $ env | grep ^LC_\n>\n\nNothing for this.\n\n\n> If there's more than one relevant environment setting, and they\n> don't all agree, I'm not sure what would happen with our\n> regression tests.\n>\n\nThere's LANG and LANGUAGE but they look like they effectively agree to me?\n\n\n> BTW, what platform are you using anyway?\n>\n\nElementaryOS 5.1 Hera, which is built on top of Ubuntu 18.04.3 LTS (and\nLinux 4.15.0-72-generic).\n\nThis suggests I have the standard Ubuntu Turkish language packages\ninstalled:\n\n$ dpkg -l | grep language-pack-tr\nii language-pack-tr 1:18.04+20180712\n all translation updates for language Turkish\nii language-pack-tr-base 1:18.04+20180712\n all translations for language Turkish\n\nJames\n\nOn Sat, Mar 7, 2020 at 9:48 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:James Coleman <jtc331@gmail.com> writes:\n> On Sat, Mar 7, 2020 at 9:31 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Looks like you may not have Turkish locale installed?  Try\n>> locale -a | grep tr_TR\n\n> Hmm, when I grep the locales I see `tr_TR.utf8` in the output. I assume the\n> utf8 version is acceptable? Or is there a non-utf8 variant?\n\nHmm ... I'm far from an expert on the packaging of locale data, but\nthe simplest explanation I can think of is that the tr_TR locale exists\nto some extent on your machine but the LC_TIME component of that is\nmissing.\n\nDo you get different results from \"date\" depending on the locale?\nI get\n\n$ LANG=C date\nSat Mar  7 21:44:24 EST 2020\n$ LANG=tr_TR.utf8 date\nCts Mar  7 21:44:26 EST 2020$ LANG=C dateSun Mar  8 09:27:50 EDT 2020$ LANG=tr_TR.utf8 datePaz Mar  8 09:27:54 EDT 2020$ LANG=tr_TR dateSun Mar  8 09:27:57 EDT 2020I'm curious if you get something different for that last one (no utf8 qualifier).\non my Fedora 30 box.\n\nAnother possibility perhaps is that you have partial locale settings\nin your environment that are bollixing the test.  Try\n\n$ env | grep ^LANGThis gives me:LANG=en_US.UTF-8LANGUAGE=en_US \n$ env | grep ^LC_Nothing for this. \nIf there's more than one relevant environment setting, and they\ndon't all agree, I'm not sure what would happen with our\nregression tests.There's LANG and LANGUAGE but they look like they effectively agree to me? \nBTW, what platform are you using anyway?ElementaryOS 5.1 Hera, which is built on top of Ubuntu 18.04.3 LTS (and Linux 4.15.0-72-generic).This suggests I have the standard Ubuntu Turkish language packages installed:$ dpkg -l | grep language-pack-trii  language-pack-tr                              1:18.04+20180712                                all          translation updates for language Turkishii  language-pack-tr-base                         1:18.04+20180712                                all          translations for language TurkishJames", "msg_date": "Sun, 8 Mar 2020 09:34:16 -0400", "msg_from": "James Coleman <jtc331@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Sun, Mar 8, 2020 at 7:17 AM Juan José Santamaría Flecha <\njuanjo.santamaria@gmail.com> wrote:\n\n>\n>\n> On Sun, Mar 8, 2020 at 3:48 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n>> James Coleman <jtc331@gmail.com> writes:\n>> > On Sat, Mar 7, 2020 at 9:31 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> >> Looks like you may not have Turkish locale installed? Try\n>> >> locale -a | grep tr_TR\n>>\n>> > Hmm, when I grep the locales I see `tr_TR.utf8` in the output. I assume\n>> the\n>> > utf8 version is acceptable? Or is there a non-utf8 variant?\n>>\n>> Hmm ... I'm far from an expert on the packaging of locale data, but\n>> the simplest explanation I can think of is that the tr_TR locale exists\n>> to some extent on your machine but the LC_TIME component of that is\n>> missing.\n>>\n>\n> AFAICS, the locale 'tr_TR' uses the encoding ISO-8859-9 (LATIN5), is not\n> the same as 'tr_TR.utf8'.\n>\n\nThe test name implies it's about utf8, though, which makes me wonder if the\ntest should be testing utf8 instead?\n\nThat being said, a bit more googling based on your node about the proper\nISO encoding turned up this page: https://unix.stackexchange.com/a/446762\n\nAnd I confirmed that the locale you mentioned is available:\n$ grep \"tr_TR\" /usr/share/i18n/SUPPORTED\ntr_TR.UTF-8 UTF-8\ntr_TR ISO-8859-9\n\nSo I tried:\necho tr_TR.ISO-8859-9 >> /var/lib/locales/supported.d/local # In a root\nsession\nsudo dpkg-reconfigure locales\n\nThat didn't seem to fix it, though `locale -a` still only lists tr_TR.utf8,\nso I'm still at a loss, and also unclear why a test names utf8 is actually\nrelying on an ISO encoding.\n\nJames\n\nOn Sun, Mar 8, 2020 at 7:17 AM Juan José Santamaría Flecha <juanjo.santamaria@gmail.com> wrote:On Sun, Mar 8, 2020 at 3:48 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:James Coleman <jtc331@gmail.com> writes:\n> On Sat, Mar 7, 2020 at 9:31 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Looks like you may not have Turkish locale installed?  Try\n>> locale -a | grep tr_TR\n\n> Hmm, when I grep the locales I see `tr_TR.utf8` in the output. I assume the\n> utf8 version is acceptable? Or is there a non-utf8 variant?\n\nHmm ... I'm far from an expert on the packaging of locale data, but\nthe simplest explanation I can think of is that the tr_TR locale exists\nto some extent on your machine but the LC_TIME component of that is\nmissing. AFAICS, the locale 'tr_TR' uses the encoding ISO-8859-9 (LATIN5), is not the same as 'tr_TR.utf8'.The test name implies it's about utf8, though, which makes me wonder if the test should be testing utf8 instead?That being said, a bit more googling based on your node about the proper ISO encoding turned up this page: https://unix.stackexchange.com/a/446762And I confirmed that the locale you mentioned is available:$ grep \"tr_TR\" /usr/share/i18n/SUPPORTEDtr_TR.UTF-8 UTF-8    tr_TR ISO-8859-9So I tried:echo tr_TR.ISO-8859-9 >> /var/lib/locales/supported.d/local # In a root sessionsudo dpkg-reconfigure localesThat didn't seem to fix it, though `locale -a` still only lists tr_TR.utf8, so I'm still at a loss, and also unclear why a test names utf8 is actually relying on an ISO encoding.James", "msg_date": "Sun, 8 Mar 2020 10:42:53 -0400", "msg_from": "James Coleman <jtc331@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Sun, Mar 8, 2020 at 10:42 AM James Coleman <jtc331@gmail.com> wrote:\n\n> On Sun, Mar 8, 2020 at 7:17 AM Juan José Santamaría Flecha <\n> juanjo.santamaria@gmail.com> wrote:\n>\n>>\n>>\n>> On Sun, Mar 8, 2020 at 3:48 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>>\n>>> James Coleman <jtc331@gmail.com> writes:\n>>> > On Sat, Mar 7, 2020 at 9:31 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>>> >> Looks like you may not have Turkish locale installed? Try\n>>> >> locale -a | grep tr_TR\n>>>\n>>> > Hmm, when I grep the locales I see `tr_TR.utf8` in the output. I\n>>> assume the\n>>> > utf8 version is acceptable? Or is there a non-utf8 variant?\n>>>\n>>> Hmm ... I'm far from an expert on the packaging of locale data, but\n>>> the simplest explanation I can think of is that the tr_TR locale exists\n>>> to some extent on your machine but the LC_TIME component of that is\n>>> missing.\n>>>\n>>\n>> AFAICS, the locale 'tr_TR' uses the encoding ISO-8859-9 (LATIN5), is not\n>> the same as 'tr_TR.utf8'.\n>>\n>\n> The test name implies it's about utf8, though, which makes me wonder if\n> the test should be testing utf8 instead?\n>\n> That being said, a bit more googling based on your node about the proper\n> ISO encoding turned up this page: https://unix.stackexchange.com/a/446762\n>\n> And I confirmed that the locale you mentioned is available:\n> $ grep \"tr_TR\" /usr/share/i18n/SUPPORTED\n> tr_TR.UTF-8 UTF-8\n> tr_TR ISO-8859-9\n>\n> So I tried:\n> echo tr_TR.ISO-8859-9 >> /var/lib/locales/supported.d/local # In a root\n> session\n> sudo dpkg-reconfigure locales\n>\n> That didn't seem to fix it, though `locale -a` still only lists\n> tr_TR.utf8, so I'm still at a loss, and also unclear why a test names utf8\n> is actually relying on an ISO encoding.\n>\n\nAnother update:\n\nSince sudo dpkg-reconfigure locales opens up an ncurses gui on my machine,\nI tried selecting the tr_TR.ISO-8859-9 option there and removed the\n/var/lib/locales/supported.d/local file. Now I get:\n\n$ locale -a | grep tr_TR\ntr_TR\ntr_TR.iso88599\ntr_TR.utf8\n\nAnd now `make check` passes.\n\nI'm still interested in understanding why we're using the ISO locale\ninstead of the utf8 one in a utf8-labeled test though.\n\nThanks,\nJames\n\nOn Sun, Mar 8, 2020 at 10:42 AM James Coleman <jtc331@gmail.com> wrote:On Sun, Mar 8, 2020 at 7:17 AM Juan José Santamaría Flecha <juanjo.santamaria@gmail.com> wrote:On Sun, Mar 8, 2020 at 3:48 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:James Coleman <jtc331@gmail.com> writes:\n> On Sat, Mar 7, 2020 at 9:31 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> Looks like you may not have Turkish locale installed?  Try\n>> locale -a | grep tr_TR\n\n> Hmm, when I grep the locales I see `tr_TR.utf8` in the output. I assume the\n> utf8 version is acceptable? Or is there a non-utf8 variant?\n\nHmm ... I'm far from an expert on the packaging of locale data, but\nthe simplest explanation I can think of is that the tr_TR locale exists\nto some extent on your machine but the LC_TIME component of that is\nmissing. AFAICS, the locale 'tr_TR' uses the encoding ISO-8859-9 (LATIN5), is not the same as 'tr_TR.utf8'.The test name implies it's about utf8, though, which makes me wonder if the test should be testing utf8 instead?That being said, a bit more googling based on your node about the proper ISO encoding turned up this page: https://unix.stackexchange.com/a/446762And I confirmed that the locale you mentioned is available:$ grep \"tr_TR\" /usr/share/i18n/SUPPORTEDtr_TR.UTF-8 UTF-8    tr_TR ISO-8859-9So I tried:echo tr_TR.ISO-8859-9 >> /var/lib/locales/supported.d/local # In a root sessionsudo dpkg-reconfigure localesThat didn't seem to fix it, though `locale -a` still only lists tr_TR.utf8, so I'm still at a loss, and also unclear why a test names utf8 is actually relying on an ISO encoding.Another update:Since sudo dpkg-reconfigure locales opens up an ncurses gui on my machine, I tried selecting the tr_TR.ISO-8859-9 option there and removed the /var/lib/locales/supported.d/local file. Now I get:$ locale -a | grep tr_TRtr_TRtr_TR.iso88599tr_TR.utf8And now `make check` passes.I'm still interested in understanding why we're using the ISO locale instead of the utf8 one in a utf8-labeled test though.Thanks,James", "msg_date": "Sun, 8 Mar 2020 12:11:42 -0400", "msg_from": "James Coleman <jtc331@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "James Coleman <jtc331@gmail.com> writes:\n> Since sudo dpkg-reconfigure locales opens up an ncurses gui on my machine,\n> I tried selecting the tr_TR.ISO-8859-9 option there and removed the\n> /var/lib/locales/supported.d/local file. Now I get:\n\n> $ locale -a | grep tr_TR\n> tr_TR\n> tr_TR.iso88599\n> tr_TR.utf8\n\n> And now `make check` passes.\n\nHm.\n\n> I'm still interested in understanding why we're using the ISO locale\n> instead of the utf8 one in a utf8-labeled test though.\n\nWe are not. My understanding of the rules about this is that the\nactive LC_CTYPE setting determines the encoding that libc uses,\nperiod. The encoding suffix on the locale name only makes a\ndifference when LC_CTYPE is being specified (or derived from LANG or\nLC_ALL), not any other LC_XXX setting --- although for consistency\nthey'll let you include it in any LC_XXX value.\n\nWe could of course choose to spell LC_TIME as 'tr_TR.utf8' in this\ntest, but that would open up the question of whether that causes\nproblems on platforms where the canonical spelling of the encoding\nsuffix is different (eg \"UTF-8\"). I'm disinclined to take that risk\nwithout positive proof that it helps on some platform.\n\nMy guess about what was actually happening on your machine is that\nthe underlying locale data only exists in iso-8859-9 form, and that\nglibc normally translates that to utf8 on-the-fly when it's demanded\n... but if the data isn't installed at all, nothing happens.\n\nOn my Red Hat platforms, this installation choice seems pretty\nall-or-nothing, but it sounds like Debian lets you chop it up\nmore finely (and maybe slice off your finger while at it :-().\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 08 Mar 2020 12:38:59 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "I wrote:\n> James Coleman <jtc331@gmail.com> writes:\n>> I'm still interested in understanding why we're using the ISO locale\n>> instead of the utf8 one in a utf8-labeled test though.\n\n> We are not. My understanding of the rules about this is that the\n> active LC_CTYPE setting determines the encoding that libc uses,\n> period. The encoding suffix on the locale name only makes a\n> difference when LC_CTYPE is being specified (or derived from LANG or\n> LC_ALL), not any other LC_XXX setting --- although for consistency\n> they'll let you include it in any LC_XXX value.\n\nOh wait --- I'm wrong about that. Looking at the code in pg_locale.c,\nwhat actually happens is that we get data in the codeset implied by\nthe LC_TIME setting and then translate it to the database encoding\n(cf commit 7ad1cd31b). So if bare \"tr_TR\" is taken as implying\niso-8859-9, which seems likely (it appears to work that way here,\nanyway) then this test is exercising the codeset translation path.\nWe could change the test to say 'tr_TR.utf8' but that would give us\nless test coverage.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 08 Mar 2020 14:19:46 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Sun, Mar 8, 2020 at 2:19 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> I wrote:\n> > James Coleman <jtc331@gmail.com> writes:\n> >> I'm still interested in understanding why we're using the ISO locale\n> >> instead of the utf8 one in a utf8-labeled test though.\n>\n> > We are not. My understanding of the rules about this is that the\n> > active LC_CTYPE setting determines the encoding that libc uses,\n> > period. The encoding suffix on the locale name only makes a\n> > difference when LC_CTYPE is being specified (or derived from LANG or\n> > LC_ALL), not any other LC_XXX setting --- although for consistency\n> > they'll let you include it in any LC_XXX value.\n>\n> Oh wait --- I'm wrong about that. Looking at the code in pg_locale.c,\n> what actually happens is that we get data in the codeset implied by\n> the LC_TIME setting and then translate it to the database encoding\n> (cf commit 7ad1cd31b). So if bare \"tr_TR\" is taken as implying\n> iso-8859-9, which seems likely (it appears to work that way here,\n> anyway) then this test is exercising the codeset translation path.\n> We could change the test to say 'tr_TR.utf8' but that would give us\n> less test coverage.\n>\n\nSo just to confirm I understand, that implies that the issue is solely that\nonly the utf8 tr_TR set is installed by default on this machine, and the\niso-8859-9 set is a hard requirement (that is, the test is explicitly\ntesting a codepath that generates utf8 results from a non-utf8 source)?\n\nIf so, I'm going to try a bare Ubuntu install on a VM and see what locales\nare installed by default for Turkish.\n\nIf in fact Ubuntu doesn't install this locale by default, then is this a\ncaveat we should add to developer docs somewhere? It seems odd to me that\nI'd be the only one encountering it, but OTOH I would have thought this a\nfairly vanilla install too...\n\nJames\n\nOn Sun, Mar 8, 2020 at 2:19 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:I wrote:\n> James Coleman <jtc331@gmail.com> writes:\n>> I'm still interested in understanding why we're using the ISO locale\n>> instead of the utf8 one in a utf8-labeled test though.\n\n> We are not.  My understanding of the rules about this is that the\n> active LC_CTYPE setting determines the encoding that libc uses,\n> period.  The encoding suffix on the locale name only makes a\n> difference when LC_CTYPE is being specified (or derived from LANG or\n> LC_ALL), not any other LC_XXX setting --- although for consistency\n> they'll let you include it in any LC_XXX value.\n\nOh wait --- I'm wrong about that.  Looking at the code in pg_locale.c,\nwhat actually happens is that we get data in the codeset implied by\nthe LC_TIME setting and then translate it to the database encoding\n(cf commit 7ad1cd31b).  So if bare \"tr_TR\" is taken as implying\niso-8859-9, which seems likely (it appears to work that way here,\nanyway) then this test is exercising the codeset translation path.\nWe could change the test to say 'tr_TR.utf8' but that would give us\nless test coverage.So just to confirm I understand, that implies that the issue is solely that only the utf8 tr_TR set is installed by default on this machine, and the iso-8859-9 set is a hard requirement (that is, the test is explicitly testing a codepath that generates utf8 results from a non-utf8 source)?If so, I'm going to try a bare Ubuntu install on a VM and see what locales are installed by default for Turkish.If in fact Ubuntu doesn't install this locale by default, then is this a caveat we should add to developer docs somewhere? It seems odd to me that I'd be the only one encountering it, but OTOH I would have thought this a fairly vanilla install too...James", "msg_date": "Sun, 8 Mar 2020 17:43:42 -0400", "msg_from": "James Coleman <jtc331@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "James Coleman <jtc331@gmail.com> writes:\n> So just to confirm I understand, that implies that the issue is solely that\n> only the utf8 tr_TR set is installed by default on this machine, and the\n> iso-8859-9 set is a hard requirement (that is, the test is explicitly\n> testing a codepath that generates utf8 results from a non-utf8 source)?\n\nIt's not \"explicitly\" testing that; the fact that \"tr_TR\" is treated\nas \"tr_TR.iso88599\" is surely an implementation artifact. (On macOS,\nsome experimentation shows that \"tr_TR\" is treated as \"tr_TR.UTF-8\".)\nBut yeah, I think it's intentional that we want the codeset translation\npath to be exercised here on at least some platforms.\n\n> If in fact Ubuntu doesn't install this locale by default, then is this a\n> caveat we should add to developer docs somewhere? It seems odd to me that\n> I'd be the only one encountering it, but OTOH I would have thought this a\n> fairly vanilla install too...\n\nNot sure. The lack of prior complaints points to this not being a\ncommon situation. It does seem weird that they'd set things up so\nthat \"tr_TR.utf8\" exists but not \"tr_TR\"; even if that's not an\noutright packaging mistake, it seems like a POLA violation from here.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 08 Mar 2020 18:03:52 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" }, { "msg_contents": "On Sun, Mar 8, 2020 at 6:03 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> James Coleman <jtc331@gmail.com> writes:\n> > So just to confirm I understand, that implies that the issue is solely\n> that\n> > only the utf8 tr_TR set is installed by default on this machine, and the\n> > iso-8859-9 set is a hard requirement (that is, the test is explicitly\n> > testing a codepath that generates utf8 results from a non-utf8 source)?\n>\n> It's not \"explicitly\" testing that; the fact that \"tr_TR\" is treated\n> as \"tr_TR.iso88599\" is surely an implementation artifact. (On macOS,\n> some experimentation shows that \"tr_TR\" is treated as \"tr_TR.UTF-8\".)\n> But yeah, I think it's intentional that we want the codeset translation\n> path to be exercised here on at least some platforms.\n>\n\nI idly wonder if there could/should be some tests for the implicit case,\nsome explicitly testing the codeset translation (if possible), and some\ntesting the explicit utf8 case...but I don't know enough about this area to\npush for anything.\n\n\n> > If in fact Ubuntu doesn't install this locale by default, then is this a\n> > caveat we should add to developer docs somewhere? It seems odd to me that\n> > I'd be the only one encountering it, but OTOH I would have thought this a\n> > fairly vanilla install too...\n>\n> Not sure. The lack of prior complaints points to this not being a\n> common situation. It does seem weird that they'd set things up so\n> that \"tr_TR.utf8\" exists but not \"tr_TR\"; even if that's not an\n> outright packaging mistake, it seems like a POLA violation from here.\n>\n> regards, tom lane\n>\n\nAll right. I downloaded an Ubuntu 18.04.3 server VM from OSBoxes, and it\nhad very few locales installed by default...so that wasn't all that helpful.\n\nI think at this point I'll just leave this as a mystery, much as I hate\nthat.\n\nJames\n\nOn Sun, Mar 8, 2020 at 6:03 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:James Coleman <jtc331@gmail.com> writes:\n> So just to confirm I understand, that implies that the issue is solely that\n> only the utf8 tr_TR set is installed by default on this machine, and the\n> iso-8859-9 set is a hard requirement (that is, the test is explicitly\n> testing a codepath that generates utf8 results from a non-utf8 source)?\n\nIt's not \"explicitly\" testing that; the fact that \"tr_TR\" is treated\nas \"tr_TR.iso88599\" is surely an implementation artifact.  (On macOS,\nsome experimentation shows that \"tr_TR\" is treated as \"tr_TR.UTF-8\".)\nBut yeah, I think it's intentional that we want the codeset translation\npath to be exercised here on at least some platforms.I idly wonder if there could/should be some tests for the implicit case, some explicitly testing the codeset translation (if possible), and some testing the explicit utf8 case...but I don't know enough about this area to push for anything. \n> If in fact Ubuntu doesn't install this locale by default, then is this a\n> caveat we should add to developer docs somewhere? It seems odd to me that\n> I'd be the only one encountering it, but OTOH I would have thought this a\n> fairly vanilla install too...\n\nNot sure.  The lack of prior complaints points to this not being a\ncommon situation.  It does seem weird that they'd set things up so\nthat \"tr_TR.utf8\" exists but not \"tr_TR\"; even if that's not an\noutright packaging mistake, it seems like a POLA violation from here.\n\n                        regards, tom laneAll right. I downloaded an Ubuntu 18.04.3 server VM from OSBoxes, and it had very few locales installed by default...so that wasn't all that helpful.I think at this point I'll just leave this as a mystery, much as I hate that.James", "msg_date": "Sun, 8 Mar 2020 18:29:41 -0400", "msg_from": "James Coleman <jtc331@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Allow to_date() and to_timestamp() to accept localized names" } ]
[ { "msg_contents": "Hi,\n\nAttached is a patch to support send/recv on ltree, lquery and ltxtquery.\nI'm a contributor to the Npgsql .NET PostgreSQL driver and we'll be\nthe first to have official support once those ltree changes have been\nreleased.\nYou can find the driver support work here, the tests verify a\nroundtrip for each of the types is succesful.\nhttps://github.com/NinoFloris/npgsql/tree/label-tree-support\n\nAny feedback would be highly appreciated.\n\nGreetings,\nNino Floris", "msg_date": "Sun, 18 Aug 2019 16:56:27 +0200", "msg_from": "Nino Floris <mail@ninofloris.com>", "msg_from_op": true, "msg_subject": "[PATCH] ltree, lquery, and ltxtquery binary protocol support" }, { "msg_contents": "Hi!\n\nOn Sun, Aug 18, 2019 at 6:53 PM Nino Floris <mail@ninofloris.com> wrote:\n> Attached is a patch to support send/recv on ltree, lquery and ltxtquery.\n> I'm a contributor to the Npgsql .NET PostgreSQL driver and we'll be\n> the first to have official support once those ltree changes have been\n> released.\n> You can find the driver support work here, the tests verify a\n> roundtrip for each of the types is succesful.\n> https://github.com/NinoFloris/npgsql/tree/label-tree-support\n\nThank you for the patch.\n\nMy notes are following:\n * Your patch doesn't follow coding convention. In particular, it\nuses spaces for indentation instead of tabs. Moreover, it changes\ntags to spaces in places it doesn't touch. As the result, patch is\n\"dirty\". Looks like your IDE isn't properly setup. Please check your\npatch doesn't contain unintended changes and follow coding convention.\nIt's also good practice to run pgindent over changed files before\nsending patch.\n * We currently don't add new extension SQL-script for new extension\nversion (i.e. ltree--1.2.sql). Instead, we provide just a migration\nscript (i.e. ltree--1.1--1.2.sql). This simplifies testing of\nextension migration – plain extension creation implies migration.\n * What is motivation for binary format for lquery and ltxtquery? One\ncould transfer large datasets of ltree's. But is it so for lquery and\nltxtquery, which are used just for querying.\n * Just send binary representation of datatype is not OK. PostgreSQL\nsupports a lot of platforms with different byte ordering, alignment\nand so on. You basically need to send each particular field using\npq_send*() function.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Tue, 10 Sep 2019 00:38:17 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: [PATCH] ltree, lquery, and ltxtquery binary protocol support" }, { "msg_contents": "Hi Alexander,\n\nThanks for the initial review!\n\n> * Your patch doesn't follow coding convention. In particular, it\n> uses spaces for indentation instead of tabs. Moreover, it changes\n> tags to spaces in places it doesn't touch. As the result, patch is\n> \"dirty\". Looks like your IDE isn't properly setup. Please check your\n> patch doesn't contain unintended changes and follow coding convention.\n> It's also good practice to run pgindent over changed files before\n> sending patch.\n\nApologies, will fix, I indeed haven't seen the requirement being tabs.\nThough not to sound pedantic I would expect an .editorconfig for such\n(industry) non standard indenting as it's broadly supported and very\nlittle effort to do so.\nI will run pgindent, thanks for the pointer, that looks super useful.\n\n > * We currently don't add new extension SQL-script for new extension\n> version (i.e. ltree--1.2.sql). Instead, we provide just a migration\n> script (i.e. ltree--1.1--1.2.sql). This simplifies testing of\n> extension migration – plain extension creation implies migration.\n\nI wasn't sure how to add new methods to the type without doing a full\nCREATE TYPE, as ALTER TYPE doesn't allow updates to functions. At that\npoint wouldn't it be better as a new version?\nI checked some other extensions like hstore to find reference material\nhow to do a new CREATE TYPE, all did a full version bump.\nShould I just do a DROP and CREATE instead in a migration?\n\n> * What is motivation for binary format for lquery and ltxtquery? One\ncould transfer large datasets of ltree's. But is it so for lquery and\nltxtquery, which are used just for querying.\n\nCompleteness, Npgsql (and other drivers like Ecto from Elixir and\nprobably many others as well) can't do any text fallback in the binary\nprotocol without manual configuration.\nThis is because these drivers don't know much (or anything) about the\nSQL they send so it wouldn't know to apply it for which columns.\nI believe there has been a proposal at some point to enhance the\nbinary protocol to additionally allow clients to specify text/binary\nper data type instead of per column.\nThat would allow all these drivers to automate this, but I think it\nnever went anywhere.\nAs it stands it's not ergonomic to ask developers to setup this\nmetadata per query they write.\n\n * Just send binary representation of datatype is not OK. PostgreSQL\nsupports a lot of platforms with different byte ordering, alignment\nand so on. You basically need to send each particular field using\npq_send*() function.\n\nOh my, I don't think I did? I copied what jsonb is doing,\nspecifically, sending the textual representation of the data type with\na version field prefixed.\n(It is why I introduced deparse_ltree/lquery, to take the respective\nstructure and create a null terminated string of its textual form)\nSo there are no other fields besides version and the string\nrepresentation of the structure.\nltree, lquery, and ltxtquery all seem to have a lossless and compact\ntextual interpretation.\nMy motivation here has been \"if it's good enough for jsonb it should\nbe good enough for a niche extension like ltree\" especially as having\nany binary support is better than not having it at all.\nI can change it to anything you'd like to see instead but I would need\nsome pointers as to what that would be.\n\nAgain, thank you for taking up this patch to review.\n\nBest regards,\nNino Floris\n\nOn Mon, Sep 9, 2019 at 11:38 PM Alexander Korotkov\n<a.korotkov@postgrespro.ru> wrote:\n>\n> Hi!\n>\n> On Sun, Aug 18, 2019 at 6:53 PM Nino Floris <mail@ninofloris.com> wrote:\n> > Attached is a patch to support send/recv on ltree, lquery and ltxtquery.\n> > I'm a contributor to the Npgsql .NET PostgreSQL driver and we'll be\n> > the first to have official support once those ltree changes have been\n> > released.\n> > You can find the driver support work here, the tests verify a\n> > roundtrip for each of the types is succesful.\n> > https://github.com/NinoFloris/npgsql/tree/label-tree-support\n>\n> Thank you for the patch.\n>\n> My notes are following:\n> * Your patch doesn't follow coding convention. In particular, it\n> uses spaces for indentation instead of tabs. Moreover, it changes\n> tags to spaces in places it doesn't touch. As the result, patch is\n> \"dirty\". Looks like your IDE isn't properly setup. Please check your\n> patch doesn't contain unintended changes and follow coding convention.\n> It's also good practice to run pgindent over changed files before\n> sending patch.\n> * We currently don't add new extension SQL-script for new extension\n> version (i.e. ltree--1.2.sql). Instead, we provide just a migration\n> script (i.e. ltree--1.1--1.2.sql). This simplifies testing of\n> extension migration – plain extension creation implies migration.\n> * What is motivation for binary format for lquery and ltxtquery? One\n> could transfer large datasets of ltree's. But is it so for lquery and\n> ltxtquery, which are used just for querying.\n> * Just send binary representation of datatype is not OK. PostgreSQL\n> supports a lot of platforms with different byte ordering, alignment\n> and so on. You basically need to send each particular field using\n> pq_send*() function.\n>\n> ------\n> Alexander Korotkov\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n\n\n\n", "msg_date": "Wed, 11 Sep 2019 20:44:39 +0200", "msg_from": "Nino Floris <mail@ninofloris.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] ltree, lquery, and ltxtquery binary protocol support" }, { "msg_contents": "On Wed, Sep 11, 2019 at 9:45 PM Nino Floris <mail@ninofloris.com> wrote:\n> > * We currently don't add new extension SQL-script for new extension\n> > version (i.e. ltree--1.2.sql). Instead, we provide just a migration\n> > script (i.e. ltree--1.1--1.2.sql). This simplifies testing of\n> > extension migration – plain extension creation implies migration.\n>\n> I wasn't sure how to add new methods to the type without doing a full\n> CREATE TYPE, as ALTER TYPE doesn't allow updates to functions. At that\n> point wouldn't it be better as a new version?\n> I checked some other extensions like hstore to find reference material\n> how to do a new CREATE TYPE, all did a full version bump.\n> Should I just do a DROP and CREATE instead in a migration?\n\nOh, I appears we didn't add send/recv to any pluggable datatype one we\nget extension system.\n\nIdeally we need to adjust ALTER TYPE command so that it could add\nsend/recv functions to an existing type.\n\nI see couple other options:\n1) Write migration script, which directly updates pg_type.\n2) Add ltree--1.2.sql and advise users to recreate extension to get\nbinary protocol support.\nBut both these options are cumbersome.\n\nWhat do you think about writing patch for ALTER TYPE?\n\n> > * What is motivation for binary format for lquery and ltxtquery? One\n> could transfer large datasets of ltree's. But is it so for lquery and\n> ltxtquery, which are used just for querying.\n>\n> Completeness, Npgsql (and other drivers like Ecto from Elixir and\n> probably many others as well) can't do any text fallback in the binary\n> protocol without manual configuration.\n> This is because these drivers don't know much (or anything) about the\n> SQL they send so it wouldn't know to apply it for which columns.\n> I believe there has been a proposal at some point to enhance the\n> binary protocol to additionally allow clients to specify text/binary\n> per data type instead of per column.\n> That would allow all these drivers to automate this, but I think it\n> never went anywhere.\n> As it stands it's not ergonomic to ask developers to setup this\n> metadata per query they write.\n>\n> * Just send binary representation of datatype is not OK. PostgreSQL\n> supports a lot of platforms with different byte ordering, alignment\n> and so on. You basically need to send each particular field using\n> pq_send*() function.\n>\n> Oh my, I don't think I did? I copied what jsonb is doing,\n> specifically, sending the textual representation of the data type with\n> a version field prefixed.\n> (It is why I introduced deparse_ltree/lquery, to take the respective\n> structure and create a null terminated string of its textual form)\n> So there are no other fields besides version and the string\n> representation of the structure.\n> ltree, lquery, and ltxtquery all seem to have a lossless and compact\n> textual interpretation.\n> My motivation here has been \"if it's good enough for jsonb it should\n> be good enough for a niche extension like ltree\" especially as having\n> any binary support is better than not having it at all.\n> I can change it to anything you'd like to see instead but I would need\n> some pointers as to what that would be.\n\nOh, sorry. I didn't notice you send textual representation for ltree,\nlquery, and ltxtquery. And the point is not performance for these\ndatatypes, but completeness. Now I got it, then it looks OK.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Thu, 12 Sep 2019 17:00:02 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: [PATCH] ltree, lquery, and ltxtquery binary protocol support" }, { "msg_contents": "Hello, can you please post an updated version of this patch? Note that\nTravis has a small complaint:\n\ngcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -g -O2 -Wall -Werror -fPIC -DLOWER_NODE -I. -I. -I../../src/include -I/usr/include/x86_64-linux-gnu -D_GNU_SOURCE -c -o crc32.o crc32.c\ncrc32.c: In function ‘ltree_crc32_sz’:\ncrc32.c:26:12: error: initialization discards ‘const’ qualifier from pointer target type [-Werror=discarded-qualifiers]\n char *p = buf;\n ^\ncc1: all warnings being treated as errors\n<builtin>: recipe for target 'crc32.o' failed\nmake[4]: *** [crc32.o] Error 1\nmake[4]: Leaving directory '/home/travis/build/postgresql-cfbot/postgresql/contrib/ltree'\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 25 Sep 2019 17:31:28 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] ltree, lquery, and ltxtquery binary protocol support" }, { "msg_contents": "Alright, as usual life got in the way. I've attached a new version of\nthe patch with pgindent changes.\n\n> What do you think about writing patch for ALTER TYPE?\nI'd rather not :$\n\n> 1) Write migration script, which directly updates pg_type.\nThis sounds like the best option right now, if we don't want people to\ndo manual migrations to ltree 1.2.\nHow would I best go at this?\n\n> Travis has a small complaint:\nShould be fixed!\n\nNino Floris\n\nOn Wed, Sep 25, 2019 at 10:31 PM Alvaro Herrera\n<alvherre@2ndquadrant.com> wrote:\n>\n> Hello, can you please post an updated version of this patch? Note that\n> Travis has a small complaint:\n>\n> gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -g -O2 -Wall -Werror -fPIC -DLOWER_NODE -I. -I. -I../../src/include -I/usr/include/x86_64-linux-gnu -D_GNU_SOURCE -c -o crc32.o crc32.c\n> crc32.c: In function ‘ltree_crc32_sz’:\n> crc32.c:26:12: error: initialization discards ‘const’ qualifier from pointer target type [-Werror=discarded-qualifiers]\n> char *p = buf;\n> ^\n> cc1: all warnings being treated as errors\n> <builtin>: recipe for target 'crc32.o' failed\n> make[4]: *** [crc32.o] Error 1\n> make[4]: Leaving directory '/home/travis/build/postgresql-cfbot/postgresql/contrib/ltree'\n>\n> --\n> Álvaro Herrera https://www.2ndQuadrant.com/\n> PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Mon, 11 Nov 2019 15:44:54 +0100", "msg_from": "Nino Floris <mail@ninofloris.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] ltree, lquery, and ltxtquery binary protocol support" }, { "msg_contents": "On Mon, Nov 11, 2019 at 03:44:54PM +0100, Nino Floris wrote:\n> Alright, as usual life got in the way. I've attached a new version of\n> the patch with pgindent changes.\n> \n> > What do you think about writing patch for ALTER TYPE?\n> I'd rather not :$\n> \n> > 1) Write migration script, which directly updates pg_type.\n> This sounds like the best option right now, if we don't want people to\n> do manual migrations to ltree 1.2.\n> How would I best go at this?\n> \n> > Travis has a small complaint:\n> Should be fixed!\n\nThe latest patch provided fails to apply for me on HEAD. Please\nprovide a rebase. For now I am bumping this patch to next CF with\n\"waiting on author\" as status.\n--\nMichael", "msg_date": "Fri, 29 Nov 2019 11:29:03 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [PATCH] ltree, lquery, and ltxtquery binary protocol support" }, { "msg_contents": "On Fri, Nov 29, 2019 at 11:29:03AM +0900, Michael Paquier wrote:\n>On Mon, Nov 11, 2019 at 03:44:54PM +0100, Nino Floris wrote:\n>> Alright, as usual life got in the way. I've attached a new version of\n>> the patch with pgindent changes.\n>>\n>> > What do you think about writing patch for ALTER TYPE?\n>> I'd rather not :$\n>>\n>> > 1) Write migration script, which directly updates pg_type.\n>> This sounds like the best option right now, if we don't want people to\n>> do manual migrations to ltree 1.2.\n>> How would I best go at this?\n>>\n>> > Travis has a small complaint:\n>> Should be fixed!\n>\n>The latest patch provided fails to apply for me on HEAD. Please\n>provide a rebase. For now I am bumping this patch to next CF with\n>\"waiting on author\" as status.\n\nNino, any plans to submit a rebased/fixed patch, so that people can\nreview it? Not sure if this needs a simple rebase or something more\ncomplex, all I know is cputube can't apply it.\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services \n\n\n", "msg_date": "Thu, 16 Jan 2020 23:00:12 +0100", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] ltree, lquery, and ltxtquery binary protocol support" }, { "msg_contents": "Attached is the new patch rebased onto master.\n\nBest regards,\nNino Floris\n\nOn Thu, Jan 16, 2020 at 11:00 PM Tomas Vondra\n<tomas.vondra@2ndquadrant.com> wrote:\n>\n> On Fri, Nov 29, 2019 at 11:29:03AM +0900, Michael Paquier wrote:\n> >On Mon, Nov 11, 2019 at 03:44:54PM +0100, Nino Floris wrote:\n> >> Alright, as usual life got in the way. I've attached a new version of\n> >> the patch with pgindent changes.\n> >>\n> >> > What do you think about writing patch for ALTER TYPE?\n> >> I'd rather not :$\n> >>\n> >> > 1) Write migration script, which directly updates pg_type.\n> >> This sounds like the best option right now, if we don't want people to\n> >> do manual migrations to ltree 1.2.\n> >> How would I best go at this?\n> >>\n> >> > Travis has a small complaint:\n> >> Should be fixed!\n> >\n> >The latest patch provided fails to apply for me on HEAD. Please\n> >provide a rebase. For now I am bumping this patch to next CF with\n> >\"waiting on author\" as status.\n>\n> Nino, any plans to submit a rebased/fixed patch, so that people can\n> review it? Not sure if this needs a simple rebase or something more\n> complex, all I know is cputube can't apply it.\n>\n> regards\n>\n> --\n> Tomas Vondra http://www.2ndQuadrant.com\n> PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Sat, 25 Jan 2020 18:43:53 +0100", "msg_from": "Nino Floris <mail@ninofloris.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] ltree, lquery, and ltxtquery binary protocol support" }, { "msg_contents": "Nino Floris <mail@ninofloris.com> writes:\n> Attached is the new patch rebased onto master.\n\nThe approach of simply providing a 1.2 installation script, with no\nupgrade path from 1.1, is surely not going to be acceptable to anyone\nwho's using ltree in production.\n\nFortunately for the odds of getting this patch accepted, we just\npushed an ALTER TYPE improvement that will solve your problem [1].\nPlease replace ltree--1.2.sql with an upgrade script that uses\nthat, and resubmit.\n\n\t\t\tregards, tom lane\n\n[1] https://git.postgresql.org/gitweb/?p=postgresql.git;a=commit;h=fe30e7ebfa3846416f1adeb7cf611006513a4ee0\n\n\n", "msg_date": "Fri, 06 Mar 2020 12:40:45 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] ltree, lquery, and ltxtquery binary protocol support" }, { "msg_contents": "I wrote:\n> Fortunately for the odds of getting this patch accepted, we just\n> pushed an ALTER TYPE improvement that will solve your problem [1].\n> Please replace ltree--1.2.sql with an upgrade script that uses\n> that, and resubmit.\n\nI decided it would be a shame for this to miss v13, seeing that\n(a) it'd provide real-world use of that ALTER TYPE code, and\n(b) we already bumped ltree's extension version for v13.\n\nSo I went ahead and rebased this, reviewed and pushed it. The\nmain non-cosmetic thing I changed, other than using ALTER TYPE,\nwas that you had the output functions looking like this:\n\n\tpq_sendtext(&buf, res, pg_mbstrlen(res));\n\nThat's just wrong; it should be plain strlen(). Did you copy\nthat coding from someplace? I could not find any similar\noccurrences in our code tree.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 01 Apr 2020 17:37:15 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] ltree, lquery, and ltxtquery binary protocol support" }, { "msg_contents": "Hi Tom,\n\nThanks a lot for pushing this through.\n\nIn complete agreement on fixing mbstrlen, it would clearly have lead to cut\noff string sends, or worse (does the binary protocol use null terminated\nstrings, or are they length prefixed?). Apologies anyways, it's been a\nwhile so I don't know how it may have ended up there, thanks for catching\nit.\n\nEven though it was a bit bumpy, and vastly different from my usual github\ncontribution flow, I've had a good time contributing my first patch!\n\nBest regards,\nNino Floris\n\n\nOn Apr 1, 2020 at 23:37, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\nI wrote:\n> Fortunately for the odds of getting this patch accepted, we just\n> pushed an ALTER TYPE improvement that will solve your problem [1].\n> Please replace ltree--1.2.sql with an upgrade script that uses\n> that, and resubmit.\n\nI decided it would be a shame for this to miss v13, seeing that\n(a) it'd provide real-world use of that ALTER TYPE code, and\n(b) we already bumped ltree's extension version for v13.\n\nSo I went ahead and rebased this, reviewed and pushed it. The\nmain non-cosmetic thing I changed, other than using ALTER TYPE,\nwas that you had the output functions looking like this:\n\n\tpq_sendtext(&buf, res, pg_mbstrlen(res));\n\nThat's just wrong; it should be plain strlen(). Did you copy\nthat coding from someplace? I could not find any similar\noccurrences in our code tree.\n\n\t\t\tregards, tom lane\n\nHi Tom,Thanks a lot for pushing this through.In complete agreement on fixing mbstrlen, it would clearly have lead to cut off string sends, or worse (does the binary protocol use null terminated strings, or are they length prefixed?). Apologies anyways, it's been a while so I don't know how it may have ended up there, thanks for catching it.Even though it was a bit bumpy, and vastly different from my usual github contribution flow, I've had a good time contributing my first patch!Best regards,Nino FlorisOn Apr 1, 2020 at 23:37, Tom Lane <tgl@sss.pgh.pa.us> wrote: I wrote:\n> Fortunately for the odds of getting this patch accepted, we just\n> pushed an ALTER TYPE improvement that will solve your problem [1].\n> Please replace ltree--1.2.sql with an upgrade script that uses\n> that, and resubmit.\n\nI decided it would be a shame for this to miss v13, seeing that\n(a) it'd provide real-world use of that ALTER TYPE code, and\n(b) we already bumped ltree's extension version for v13.\n\nSo I went ahead and rebased this, reviewed and pushed it. The\nmain non-cosmetic thing I changed, other than using ALTER TYPE,\nwas that you had the output functions looking like this:\n\n\tpq_sendtext(&buf, res, pg_mbstrlen(res));\n\nThat's just wrong; it should be plain strlen(). Did you copy\nthat coding from someplace? I could not find any similar\noccurrences in our code tree.\n\n\t\t\tregards, tom lane", "msg_date": "Wed, 1 Apr 2020 14:52:59 -0700", "msg_from": "Nino Floris <mail@ninofloris.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] ltree, lquery, and ltxtquery binary protocol support" } ]
[ { "msg_contents": "Hello hackers,\n\nPlease consider fixing the last group (for now) of typos and\ninconsistencies in the tree:\n\n11.1 peforming -> performing\n11.2 table_freeze_age -> freeze_table_age\n11.3 TableInfoData -> TableDataInfo\n11.4 TableStatus -> PgStat_TableStatus\n11.5 TAG_VALID -> BM_TAG_VALID\n11.6 TarDirectoryMethod -> WalTarMethod\n11.7 targetss -> targets\n11.8 tarReadRaw -> _tarReadRaw\n11.9 Tcl_SetVar2 -> Tcl_SetVar2Ex\n11.10 tcvn_to_utf8, utf8_to_tcvn -> windows_1258_to_utf8,\nutf8_to_windows_1258\n11.11 test_rls_hook_permissive, test_rls_hook_restrictive ->\ntest_rls_hooks_permissive, test_rls_hooks_restrictive\n11.12 test_thread_funcs.c -> thread_test.c\n11.13 threated -> treated\n11.14 TidNode -> TidScan\n11.15 tidPtr -> tss_TidPtr\n11.16 TimestampTZ -> TimestampTz\n11.17 TM_ZONE -> tm_zone\n11.18 TOAST_DEBUG -> remove (orphaned since the introduction in 57d8080a)\n11.19 TopTransactionState -> TopTransactionStateData\n11.20 tpe -> type\n11.21 tranasctions -> transactions\n11.22 TransactionOid -> TransactionId\n11.23 TupleLockUpdate -> LockTupleNoKeyExclusive\n11.24 TUPLES_OK -> PGRES_TUPLES_OK\n11.25 typstore -> tupstore\n11.26 uniquePairs -> hstoreUniquePairs\n11.27 upperIndex -> upperIndx\n11.28 USER_NAME_SIZE -> remove (not used since the introduction in\nc2e9b2f28)\n11.29 VacLimit -> xidVacLimit\n11.30 verfies -> verifies\n11.31 verifymbstr -> pg_verifymbstr\n11.32 VfdArray -> VfdCache\n11.33 visca -> vice\n11.34 v_spl_left, v_spl_right -> v-&gt;spl_left, v-&gt;spl_right\n11.35 WaitforMultipleObjects -> WaitForMultipleObjects\n11.36 walrcv_query -> walrcv_exec\n11.37 max wal_size_mb -> max_wal_size_mb\n11.38 WalWriteDelay -> WalWriterDelay\n11.39 whichChkpti -> whichChkpt\n11.40 win32_crashdump.c -> crashdump.c\n11.41 worker_i -> worker_num\n11.42 WorkingDirectorY -> WorkingDirectory\n11.43 XactLockTableWaitErrorContextCb -> XactLockTableWaitErrorCb\n11.44 xlblock -> xlblocks\n11.45 xl_multi_insert -> xl_multi_insert_tuple\n11.46 xlog_brin_update -> xl_brin_insert\n11.47 XLogFakeRelcacheEntry -> CreateFakeRelcacheEntry\n11.48 XLOGFileSlop -> XLOGfileslop\n11.49 XLogreader -> XLogReader\n11.50 XLogReadPage -> XLogRead\n11.51 xl_rem_len -> xlp_rem_len\n11.52 XMAX_EXCL_LOCK, XMAX_KEYSHR_LOCK -> HEAP_XMAX_EXCL_LOCK,\nHEAP_XMAX_KEYSHR_LOCK\n11.53 yyscanner_t -> yyscan_t\n11.54 cdir -> cidr\n11.55 examine_operator_expression -> examine_opclause_expression\n11.56 list_qsort_comparator -> list_sort_comparator (renamed in 569ed7f4)\n11.57 PASSBYVALUE -> PASSEDBYVALUE\n\nBest regards,\nAlexander", "msg_date": "Mon, 19 Aug 2019 07:04:04 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": true, "msg_subject": "Fix typos and inconsistencies for HEAD (take 11)" }, { "msg_contents": "On Mon, Aug 19, 2019 at 07:04:04AM +0300, Alexander Lakhin wrote:\n> 11.23 TupleLockUpdate -> LockTupleNoKeyExclusive\n\nNot sure about this one, so discarded for now. Alvaro?\n\n> 11.25 typstore -> tupstore\n\nThis one is cute. It actually does not cause a compilation failure as\ntuplestore_donestoring() is a no-op.\n\n> 11.33 visca -> vice\n\nThis one is interesting latin.\n\n> 11.57 PASSBYVALUE -> PASSEDBYVALUE\n\nWill fix this one separately and back-patch.\n--\nMichael", "msg_date": "Mon, 19 Aug 2019 16:22:44 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Fix typos and inconsistencies for HEAD (take 11)" }, { "msg_contents": "On Mon, Aug 19, 2019 at 04:22:44PM +0900, Michael Paquier wrote:\n> On Mon, Aug 19, 2019 at 07:04:04AM +0300, Alexander Lakhin wrote:\n>> 11.57 PASSBYVALUE -> PASSEDBYVALUE\n> \n> Will fix this one separately and back-patch.\n\nNo need to, actually, as the error comes from 7bdc655.\n--\nMichael", "msg_date": "Mon, 19 Aug 2019 16:39:54 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Fix typos and inconsistencies for HEAD (take 11)" }, { "msg_contents": "On 2019-Aug-19, Michael Paquier wrote:\n\n> On Mon, Aug 19, 2019 at 07:04:04AM +0300, Alexander Lakhin wrote:\n> > 11.23 TupleLockUpdate -> LockTupleNoKeyExclusive\n> \n> Not sure about this one, so discarded for now. Alvaro?\n\nYeah, Alexander proposed change is correct. I just pushed it.\n\n> > 11.33 visca -> vice\n> \n> This one is interesting latin.\n\nWell, it's a regular Haasism.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 20 Aug 2019 16:47:41 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Fix typos and inconsistencies for HEAD (take 11)" }, { "msg_contents": "On Tue, Aug 20, 2019 at 04:47:41PM -0400, Alvaro Herrera wrote:\n> Yeah, Alexander proposed change is correct. I just pushed it.\n\nThanks, Alvaro.\n--\nMichael", "msg_date": "Wed, 21 Aug 2019 16:37:14 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Fix typos and inconsistencies for HEAD (take 11)" } ]
[ { "msg_contents": "Hi all,\n\nI have been looking at the isolation tests, and we have in some specs\nsteps which are defined but not used in any permutations. In order to\ndetect them, I have been using the attached trick to track which\npermutations are used. This allows to find immediately any\nover-engineered spec by generating diffs about steps defined by not\nused in any permutations. On HEAD, we have six specs entering in this\ncategory.\n\nWould that be useful?\n--\nMichael", "msg_date": "Mon, 19 Aug 2019 17:08:20 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Cleanup isolation specs from unused steps" }, { "msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n> I have been looking at the isolation tests, and we have in some specs\n> steps which are defined but not used in any permutations.\n\nHmm, might any of those represent actual bugs? Or are they just\nleftovers from test development?\n\n> In order to\n> detect them, I have been using the attached trick to track which\n> permutations are used. This allows to find immediately any\n> over-engineered spec by generating diffs about steps defined by not\n> used in any permutations. On HEAD, we have six specs entering in this\n> category.\n\nSeems like a good idea; I'm surprised we've got so many cases.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 19 Aug 2019 11:02:42 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Mon, Aug 19, 2019 at 1:08 AM Michael Paquier <michael@paquier.xyz> wrote:\n\n> Hi all,\n>\n> I have been looking at the isolation tests, and we have in some specs\n> steps which are defined but not used in any permutations. In order to\n> detect them, I have been using the attached trick to track which\n> permutations are used. This allows to find immediately any\n> over-engineered spec by generating diffs about steps defined by not\n> used in any permutations. On HEAD, we have six specs entering in this\n> category.\n>\n> Would that be useful?\n>\n\nI think it is useful.\n\ncould you do the check that all steps have been used in dry_run mode\ninstead of when running the tests for real?\n\n-- \nMelanie Plageman\n\nOn Mon, Aug 19, 2019 at 1:08 AM Michael Paquier <michael@paquier.xyz> wrote:Hi all,\n\nI have been looking at the isolation tests, and we have in some specs\nsteps which are defined but not used in any permutations.  In order to\ndetect them, I have been using the attached trick to track which\npermutations are used.  This allows to find immediately any\nover-engineered spec by generating diffs about steps defined by not\nused in any permutations.  On HEAD, we have six specs entering in this\ncategory.\n\nWould that be useful?I think it is useful.could you do the check that all steps have been used in dry_run modeinstead of when running the tests for real? -- Melanie Plageman", "msg_date": "Mon, 19 Aug 2019 10:23:19 -0700", "msg_from": "Melanie Plageman <melanieplageman@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Mon, Aug 19, 2019 at 11:02:42AM -0400, Tom Lane wrote:\n> Michael Paquier <michael@paquier.xyz> writes:\n>> I have been looking at the isolation tests, and we have in some specs\n>> steps which are defined but not used in any permutations.\n> \n> Hmm, might any of those represent actual bugs? Or are they just\n> leftovers from test development?\n\nI cannot yet enter the minds of each test author back this much in\ntime, but I think that's a mix of both. When working on a new\nisolation spec, I personally tend to do a lot of copy-pasting of the\nsame queries for multiple sessions and then manipulate the\npermutations to produce a set of useful tests. It is rather easy to\nforget to remove some steps when doing that. I guess that's what\nhappened with tuplelock-upgrade, insert-conflict-do-update* and\nfreeze-the-dead.\n--\nMichael", "msg_date": "Tue, 20 Aug 2019 10:36:08 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Mon, Aug 19, 2019 at 10:23:19AM -0700, Melanie Plageman wrote:\n> Could you do the check that all steps have been used in dry_run mode\n> instead of when running the tests for real?\n\nSure, I was hesitating to do so. I have no issue in moving the check\ninto run_testspec(). So done as attached.\n\nIt is rather a pain to pass down custom options to isolationtester.\nFor example, I have tested the updated version attached after\nhijacking -n into isolation_start_test(). Ugly hack, but for testing\nthat's enough. Do you make use of this tool in a particular way in\ngreenplum? Just wondering.\n\n(Could it make sense to have long options for isolationtester by the\nway?)\n--\nMichael", "msg_date": "Tue, 20 Aug 2019 11:00:21 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On 2019-Aug-20, Michael Paquier wrote:\n\n> On Mon, Aug 19, 2019 at 10:23:19AM -0700, Melanie Plageman wrote:\n> > Could you do the check that all steps have been used in dry_run mode\n> > instead of when running the tests for real?\n> \n> Sure, I was hesitating to do so. I have no issue in moving the check\n> into run_testspec(). So done as attached.\n\nI created the dry-run mode to be able to easily generate the set of\npossible permutations for a new test, then edit the result and put it\nback in the spec file; but after the deadlock tests were added (with\nnecessary hacking of the lock-detection in isolationtester) that manner\nof operation became almost completely useless. Maybe we need to rethink\nwhat facilities isolationtester offers -- possibly making dry-run have a\ncompletely different behavior than currently, which I doubt anybody is\nusing.\n\nAll that being said, I have no objections to this patch (but I didn't\nreview it closely).\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 20 Aug 2019 00:34:45 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Tue, Aug 20, 2019 at 12:34:45AM -0400, Alvaro Herrera wrote:\n> I created the dry-run mode to be able to easily generate the set of\n> possible permutations for a new test, then edit the result and put it\n> back in the spec file; but after the deadlock tests were added (with\n> necessary hacking of the lock-detection in isolationtester) that manner\n> of operation became almost completely useless. Maybe we need to rethink\n> what facilities isolationtester offers -- possibly making dry-run have a\n> completely different behavior than currently, which I doubt anybody is\n> using.\n\nI am not sure exactly how it could be redesigned, and with n!\npermutations that easily leads to bloat of the generated output. I\nthink that --dry-run (well -n) is a bit misleading as option name\nthough as it prints only permutations. Still, keeping it around has\nno real cost, so it is not a big deal.\n\n(Looking at the gpdb code, it does not seem to be used.)\n\n> All that being said, I have no objections to this patch (but I didn't\n> review it closely).\n\nThanks.\n--\nMichael", "msg_date": "Tue, 20 Aug 2019 14:17:36 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2019-Aug-20, Michael Paquier wrote:\n>> On Mon, Aug 19, 2019 at 10:23:19AM -0700, Melanie Plageman wrote:\n>>> Could you do the check that all steps have been used in dry_run mode\n>>> instead of when running the tests for real?\n\n>> Sure, I was hesitating to do so. I have no issue in moving the check\n>> into run_testspec(). So done as attached.\n\n> I created the dry-run mode to be able to easily generate the set of\n> possible permutations for a new test, then edit the result and put it\n> back in the spec file; but after the deadlock tests were added (with\n> necessary hacking of the lock-detection in isolationtester) that manner\n> of operation became almost completely useless. Maybe we need to rethink\n> what facilities isolationtester offers -- possibly making dry-run have a\n> completely different behavior than currently, which I doubt anybody is\n> using.\n\nHm, does that mean that this version of the patch would fail to warn\nduring a normal run? Doesn't sound good, since as Alvaro says,\nhardly anyone uses dry-run.\n\nIf you can warn in both cases, that'd be OK perhaps. But Alvaro's\ndescription of the intended use of dry-run makes it sound like\nit would be expected for there to be unreferenced steps, since there'd\nbe no permutations yet in the input.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 20 Aug 2019 09:47:22 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On 2019-Aug-20, Tom Lane wrote:\n\n> If you can warn in both cases, that'd be OK perhaps. But Alvaro's\n> description of the intended use of dry-run makes it sound like\n> it would be expected for there to be unreferenced steps, since there'd\n> be no permutations yet in the input.\n\nWell, Heikki/Kevin's original intention was that if no permutations are\nspecified, then all possible permutations are generated internally and\nthe spec is run with that. The intended use of dry-run was to do just\nthat (generate all possible permutations) and print that list, so that\nit could be trimmed down by the test author. In this mode of operation,\nall steps are always used, so there'd be no warning printed. However,\nwhen a test file has a largish number of steps then the list is, um, a\nbit long. Before the deadlock-test hacking, you could run with such a\nlist anyway and any permutations that caused a blockage would be\nreported right away as an invalid permutation -- quick enough.\nCurrently it sleeps for absurdly long on those cases, so this is no\nlonger feasible.\n\nThis is why I say that the current dry-run mode could be removed with no\nloss of useful functionality.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 20 Aug 2019 09:54:56 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Tue, Aug 20, 2019 at 09:54:56AM -0400, Alvaro Herrera wrote:\n> On 2019-Aug-20, Tom Lane wrote:\n>> If you can warn in both cases, that'd be OK perhaps. But Alvaro's\n>> description of the intended use of dry-run makes it sound like\n>> it would be expected for there to be unreferenced steps, since there'd\n>> be no permutations yet in the input.\n\nv2 of the patch warns of any unused steps in dry-run mode. If no\npermutations are defined in the input spec, all steps get used\n(actually that's not a factorial as the per-session ordering is\npreserved), so I would expect no warnings to be generated and the\npatch does that. If the test includes some permutations, then I would\nexpect dry-run to complain about the steps which are defined in the\nspec but not used. The patch also does that. Do you see a problem\nwith that?\n\n> Well, Heikki/Kevin's original intention was that if no permutations are\n> specified, then all possible permutations are generated internally and\n> the spec is run with that. The intended use of dry-run was to do just\n> that (generate all possible permutations) and print that list, so that\n> it could be trimmed down by the test author. In this mode of operation,\n> all steps are always used, so there'd be no warning printed. However,\n> when a test file has a largish number of steps then the list is, um, a\n> bit long. Before the deadlock-test hacking, you could run with such a\n> list anyway and any permutations that caused a blockage would be\n> reported right away as an invalid permutation -- quick enough.\n> Currently it sleeps for absurdly long on those cases, so this is no\n> longer feasible.\n> \n> This is why I say that the current dry-run mode could be removed with no\n> loss of useful functionality.\n\nHmm. Even if one does not do something deadlock-specific, the list\nprinted could still be useful, no? This for example works now that I\nlook at it:\n./isolationtester -n < specs/my_spec.spec\n\nI am wondering if we should not actually keep dry_run, but rename it\nto something like --print-permutations to print the set of\npermutations which would be run as part of the spec, and also have an\noption which is able to print out all permutations possible, like\n--print-all-permutations. Simply ripping out the mode would be fine\nby me as it does not seem to be used, but keeping it around does not\ninduce really much extra maintenance cost.\n--\nMichael", "msg_date": "Wed, 21 Aug 2019 10:34:24 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Mon, Aug 19, 2019 at 7:01 PM Michael Paquier <michael@paquier.xyz> wrote:\n\n>\n> It is rather a pain to pass down custom options to isolationtester.\n> For example, I have tested the updated version attached after\n> hijacking -n into isolation_start_test(). Ugly hack, but for testing\n> that's enough. Do you make use of this tool in a particular way in\n> greenplum? Just wondering.\n>\n> (Could it make sense to have long options for isolationtester by the\n> way?)\n>\n\nIn Greenplum, we mainly add new tests to a separate isolation\nframework (called isolation2) which uses a completely different\nsyntax. It doesn't use isolationtester at all. So, I haven't had a use\ncase to add long options to isolationtester yet :)\n\n-- \nMelanie Plageman\n\nOn Mon, Aug 19, 2019 at 7:01 PM Michael Paquier <michael@paquier.xyz> wrote:\nIt is rather a pain to pass down custom options to isolationtester.\nFor example, I have tested the updated version attached after\nhijacking -n into isolation_start_test().  Ugly hack, but for testing\nthat's enough.  Do you make use of this tool in a particular way in\ngreenplum?  Just wondering.\n\n(Could it make sense to have long options for isolationtester by the\nway?)In Greenplum, we mainly add new tests to a separate isolationframework (called isolation2) which uses a completely differentsyntax. It doesn't use isolationtester at all. So, I haven't had a usecase to add long options to isolationtester yet :)-- Melanie Plageman", "msg_date": "Wed, 21 Aug 2019 11:04:08 -0700", "msg_from": "Melanie Plageman <melanieplageman@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Tue, Aug 20, 2019 at 6:34 PM Michael Paquier <michael@paquier.xyz> wrote:\n\n> On Tue, Aug 20, 2019 at 09:54:56AM -0400, Alvaro Herrera wrote:\n> > On 2019-Aug-20, Tom Lane wrote:\n> >> If you can warn in both cases, that'd be OK perhaps. But Alvaro's\n> >> description of the intended use of dry-run makes it sound like\n> >> it would be expected for there to be unreferenced steps, since there'd\n> >> be no permutations yet in the input.\n>\n> v2 of the patch warns of any unused steps in dry-run mode. If no\n> permutations are defined in the input spec, all steps get used\n> (actually that's not a factorial as the per-session ordering is\n> preserved), so I would expect no warnings to be generated and the\n> patch does that. If the test includes some permutations, then I would\n> expect dry-run to complain about the steps which are defined in the\n> spec but not used. The patch also does that. Do you see a problem\n> with that?\n>\n> > Well, Heikki/Kevin's original intention was that if no permutations are\n> > specified, then all possible permutations are generated internally and\n> > the spec is run with that. The intended use of dry-run was to do just\n> > that (generate all possible permutations) and print that list, so that\n> > it could be trimmed down by the test author. In this mode of operation,\n> > all steps are always used, so there'd be no warning printed. However,\n> > when a test file has a largish number of steps then the list is, um, a\n> > bit long. Before the deadlock-test hacking, you could run with such a\n> > list anyway and any permutations that caused a blockage would be\n> > reported right away as an invalid permutation -- quick enough.\n> > Currently it sleeps for absurdly long on those cases, so this is no\n> > longer feasible.\n> >\n> > This is why I say that the current dry-run mode could be removed with no\n> > loss of useful functionality.\n>\n> Hmm. Even if one does not do something deadlock-specific, the list\n> printed could still be useful, no? This for example works now that I\n> look at it:\n> ./isolationtester -n < specs/my_spec.spec\n>\n> I am wondering if we should not actually keep dry_run, but rename it\n> to something like --print-permutations to print the set of\n> permutations which would be run as part of the spec, and also have an\n> option which is able to print out all permutations possible, like\n> --print-all-permutations. Simply ripping out the mode would be fine\n> by me as it does not seem to be used, but keeping it around does not\n> induce really much extra maintenance cost.\n>\n\nSo, I think I completely misunderstood the purpose of 'dry-run'. If no\none is using it, having a check for unused steps in dry-run may not be\nuseful.\n\n+1 to renaming it to --print-permutations and, potentially,\nadding --print-all-permutations\n\n-- \nMelanie Plageman\n\nOn Tue, Aug 20, 2019 at 6:34 PM Michael Paquier <michael@paquier.xyz> wrote:On Tue, Aug 20, 2019 at 09:54:56AM -0400, Alvaro Herrera wrote:\n> On 2019-Aug-20, Tom Lane wrote:\n>> If you can warn in both cases, that'd be OK perhaps.  But Alvaro's\n>> description of the intended use of dry-run makes it sound like\n>> it would be expected for there to be unreferenced steps, since there'd\n>> be no permutations yet in the input.\n\nv2 of the patch warns of any unused steps in dry-run mode.  If no\npermutations are defined in the input spec, all steps get used\n(actually that's not a factorial as the per-session ordering is\npreserved), so I would expect no warnings to be generated and the\npatch does that.  If the test includes some permutations, then I would\nexpect dry-run to complain about the steps which are defined in the\nspec but not used.  The patch also does that.  Do you see a problem\nwith that?\n\n> Well, Heikki/Kevin's original intention was that if no permutations are\n> specified, then all possible permutations are generated internally and\n> the spec is run with that.  The intended use of dry-run was to do just\n> that (generate all possible permutations) and print that list, so that\n> it could be trimmed down by the test author.  In this mode of operation,\n> all steps are always used, so there'd be no warning printed.  However,\n> when a test file has a largish number of steps then the list is, um, a\n> bit long.  Before the deadlock-test hacking, you could run with such a\n> list anyway and any permutations that caused a blockage would be\n> reported right away as an invalid permutation -- quick enough.\n> Currently it sleeps for absurdly long on those cases, so this is no\n> longer feasible.\n> \n> This is why I say that the current dry-run mode could be removed with no\n> loss of useful functionality.\n\nHmm.  Even if one does not do something deadlock-specific, the list\nprinted could still be useful, no?  This for example works now that I\nlook at it:\n./isolationtester -n < specs/my_spec.spec\n\nI am wondering if we should not actually keep dry_run, but rename it\nto something like --print-permutations to print the set of\npermutations which would be run as part of the spec, and also have an\noption which is able to print out all permutations possible, like\n--print-all-permutations.  Simply ripping out the mode would be fine\nby me as it does not seem to be used, but keeping it around does not\ninduce really much extra maintenance cost.So, I think I completely misunderstood the purpose of 'dry-run'. If noone is using it, having a check for unused steps in dry-run may not beuseful.+1 to renaming it to --print-permutations and, potentially,adding --print-all-permutations -- Melanie Plageman", "msg_date": "Wed, 21 Aug 2019 11:07:19 -0700", "msg_from": "Melanie Plageman <melanieplageman@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On 2019-Aug-21, Melanie Plageman wrote:\n\n> In Greenplum, we mainly add new tests to a separate isolation\n> framework (called isolation2) which uses a completely different\n> syntax. It doesn't use isolationtester at all. So, I haven't had a use\n> case to add long options to isolationtester yet :)\n\nIs that other framework somehow more capable?\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 21 Aug 2019 15:16:43 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Wed, Aug 21, 2019 at 11:07:19AM -0700, Melanie Plageman wrote:\n> So, I think I completely misunderstood the purpose of 'dry-run'. If no\n> one is using it, having a check for unused steps in dry-run may not be\n> useful.\n\nOkay. After sleeping on it and seeing how this thread evolves, it\nlooks that we have more arguments in favor of just let dry-run go to\nthe void. So attached is an updated patch set:\n- 0001 removes the dry-run mode from isolationtester.\n- 0002 cleans up the specs of unused steps and adds the discussed\nsanity checks, as proposed for this thread.\n--\nMichael", "msg_date": "Thu, 22 Aug 2019 11:53:35 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Wed, Aug 21, 2019 at 12:16 PM Alvaro Herrera <alvherre@2ndquadrant.com>\nwrote:\n\n> On 2019-Aug-21, Melanie Plageman wrote:\n>\n> > In Greenplum, we mainly add new tests to a separate isolation\n> > framework (called isolation2) which uses a completely different\n> > syntax. It doesn't use isolationtester at all. So, I haven't had a use\n> > case to add long options to isolationtester yet :)\n>\n> Is that other framework somehow more capable?\n>\n\nSo, there is some historical context as to why it is a separate test suite.\nAnd some of the differences are specific to Greenplum -- e.g. needing to\nconnect\nto a specific database in \"utility mode\" to do something.\n\nHowever, the other differences are actually pretty handy and would be\napplicable\nto upstream as well.\nWe use a different syntax than the isolation framework and have some nice\nfeatures. Most notably, explicit control over blocking.\n\nThe syntax for what would be a \"step\" in isolation is like this:\n\n[<#>[flag]:] <sql> | ! <shell scripts or command>\n\nwhere # is the session number and flags include the following:\n\n&: expect blocking behavior\n>: running in background without blocking\n<: join an existing session\nq: quit the given session\n\nSee the script [1] for parsing the test cases for more details on the\nsyntax and\ncapabilities (it is in Python).\n\n[1]\nhttps://github.com/greenplum-db/gpdb/blob/master/src/test/isolation2/sql_isolation_testcase.py\n\n-- \nMelanie Plageman\n\nOn Wed, Aug 21, 2019 at 12:16 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:On 2019-Aug-21, Melanie Plageman wrote:\n\n> In Greenplum, we mainly add new tests to a separate isolation\n> framework (called isolation2) which uses a completely different\n> syntax. It doesn't use isolationtester at all. So, I haven't had a use\n> case to add long options to isolationtester yet :)\n\nIs that other framework somehow more capable?\nSo, there is some historical context as to why it is a separate test suite.And some of the differences are specific to Greenplum -- e.g. needing to connectto a specific database in \"utility mode\" to do something.However, the other differences are actually pretty handy and would be applicableto upstream as well.We use a different syntax than the isolation framework and have some nicefeatures. Most notably, explicit control over blocking.The syntax for what would be a \"step\" in isolation is like this:\t[<#>[flag]:] <sql> | ! <shell scripts or command>where # is the session number and flags include the following:\t&: expect blocking behavior\t>: running in background without blocking\t<: join an existing session\tq: quit the given sessionSee the script [1] for parsing the test cases for more details on the syntax andcapabilities (it is in Python).[1] https://github.com/greenplum-db/gpdb/blob/master/src/test/isolation2/sql_isolation_testcase.py-- Melanie Plageman", "msg_date": "Thu, 22 Aug 2019 10:20:48 -0700", "msg_from": "Melanie Plageman <melanieplageman@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Thu, Aug 22, 2019 at 1:45 PM Melanie Plageman\n<melanieplageman@gmail.com> wrote:\n>\n>\n> On Wed, Aug 21, 2019 at 12:16 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n>>\n>> On 2019-Aug-21, Melanie Plageman wrote:\n>>\n>> > In Greenplum, we mainly add new tests to a separate isolation\n>> > framework (called isolation2) which uses a completely different\n>> > syntax. It doesn't use isolationtester at all. So, I haven't had a use\n>> > case to add long options to isolationtester yet :)\n>>\n>> Is that other framework somehow more capable?\n>\n>\n> So, there is some historical context as to why it is a separate test suite.\n> And some of the differences are specific to Greenplum -- e.g. needing to connect\n> to a specific database in \"utility mode\" to do something.\n>\n> However, the other differences are actually pretty handy and would be applicable\n> to upstream as well.\n> We use a different syntax than the isolation framework and have some nice\n> features. Most notably, explicit control over blocking.\n\nAsim submitted this framework just yesterday:\nhttps://www.postgresql.org/message-id/CANXE4TdxdESX1jKw48xet-5GvBFVSq=4cgNeioTQff372KO45A@mail.gmail.com\n\n-- Rob\n\n>\n> The syntax for what would be a \"step\" in isolation is like this:\n>\n> [<#>[flag]:] <sql> | ! <shell scripts or command>\n>\n> where # is the session number and flags include the following:\n>\n> &: expect blocking behavior\n> >: running in background without blocking\n> <: join an existing session\n> q: quit the given session\n>\n> See the script [1] for parsing the test cases for more details on the syntax and\n> capabilities (it is in Python).\n>\n> [1] https://github.com/greenplum-db/gpdb/blob/master/src/test/isolation2/sql_isolation_testcase.py\n>\n> --\n> Melanie Plageman\n\n\n", "msg_date": "Thu, 22 Aug 2019 15:48:47 -0400", "msg_from": "Robert Eckhardt <reckhardt@pivotal.io>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Thu, Aug 22, 2019 at 10:20:48AM -0700, Melanie Plageman wrote:\n> So, there is some historical context as to why it is a separate test suite.\n> And some of the differences are specific to Greenplum -- e.g. needing to\n> connect to a specific database in \"utility mode\" to do something.\n\nWhat is \"utility mode\"?\n\n> The syntax for what would be a \"step\" in isolation is like this:\n> \n> [<#>[flag]:] <sql> | ! <shell scripts or command>\n> \n> where # is the session number and flags include the following:\n> \n> &: expect blocking behavior\n> >: running in background without blocking\n> <: join an existing session\n> q: quit the given session\n\nThese could be transposed as new meta commands for the existing\nspecs? Of course not as \"step\" per-se, but new dedicated commands?\n\n> See the script [1] for parsing the test cases for more details on the \n> syntax and capabilities (it is in Python).\n\nHmm. The bar to add a new hard language dependency in the test\nsuites is very high. I am not sure that we'd want something with a\npython dependency for the tests, also knowing how Python likes\nbreaking compatibility (isolation2_main() also mentions a dependency\nto Python).\n--\nMichael", "msg_date": "Fri, 23 Aug 2019 10:53:16 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Thu, Aug 22, 2019 at 6:53 PM Michael Paquier <michael@paquier.xyz> wrote:\n\n> On Thu, Aug 22, 2019 at 10:20:48AM -0700, Melanie Plageman wrote:\n> > So, there is some historical context as to why it is a separate test\n> suite.\n> > And some of the differences are specific to Greenplum -- e.g. needing to\n> > connect to a specific database in \"utility mode\" to do something.\n>\n> What is \"utility mode\"?\n>\n\nIt's a connection parameter that allows you to connect to a single Postgres\nnode\nin a Greenplum cluster. I only included it as an example of the kind of\n\"Greenplum-specific\" things that are in the test framework.\n\n\n>\n> > The syntax for what would be a \"step\" in isolation is like this:\n> >\n> > [<#>[flag]:] <sql> | ! <shell scripts or command>\n> >\n> > where # is the session number and flags include the following:\n> >\n> > &: expect blocking behavior\n> > >: running in background without blocking\n> > <: join an existing session\n> > q: quit the given session\n>\n> These could be transposed as new meta commands for the existing\n> specs? Of course not as \"step\" per-se, but new dedicated commands?\n>\n>\nYes, I think you could definitely add some of the flags as meta-commands for\nexisting steps -- the current implementation of \"blocking\" for isolation is\nreally limiting.\nHowever, features aside, I actually find the existing \"step\" syntax in\nisolation\nclunkier than the syntax used in Greenplum's \"isolation2\" framework.\n\n\n> > See the script [1] for parsing the test cases for more details on the\n> > syntax and capabilities (it is in Python).\n>\n> Hmm. The bar to add a new hard language dependency in the test\n> suites is very high. I am not sure that we'd want something with a\n> python dependency for the tests, also knowing how Python likes\n> breaking compatibility (isolation2_main() also mentions a dependency\n> to Python).\n>\n\nAgreed, I don't think it needs to be in Python.\n\nMy point was that some of our \"isolation2\" framework has to be different\nbecause\nit is enabling us to test features that are in Greenplum and not in\nPostgres.\nHowever, many of the features it has would actually be really handy to have\nfor\ntesting Postgres.\nIt wasn't initially suggested upstream because it is actually mainly ported\nfrom\na separate standalone testing framework that was written at Greenplum in\nPython.\n\nI've heard Greenplum folks talk about re-writing our \"isolation2\" framework\nin\n(probably) C and making it a better fit to contribute. It's definitely on\nmy wishlist.\n\n-- \nMelanie Plageman\n\nOn Thu, Aug 22, 2019 at 6:53 PM Michael Paquier <michael@paquier.xyz> wrote:On Thu, Aug 22, 2019 at 10:20:48AM -0700, Melanie Plageman wrote:\n> So, there is some historical context as to why it is a separate test suite.\n> And some of the differences are specific to Greenplum -- e.g. needing to\n> connect to a specific database in \"utility mode\" to do something.\n\nWhat is \"utility mode\"?It's a connection parameter that allows you to connect to a single Postgres nodein a Greenplum cluster. I only included it as an example of the kind of\"Greenplum-specific\" things that are in the test framework. \n\n> The syntax for what would be a \"step\" in isolation is like this:\n> \n> [<#>[flag]:] <sql> | ! <shell scripts or command>\n> \n> where # is the session number and flags include the following:\n> \n> &: expect blocking behavior\n> >: running in background without blocking\n> <: join an existing session\n> q: quit the given session\n\nThese could be transposed as new meta commands for the existing\nspecs?  Of course not as \"step\" per-se, but new dedicated commands?\nYes, I think you could definitely add some of the flags as meta-commands forexisting steps -- the current implementation of \"blocking\" for isolation isreally limiting.However, features aside, I actually find the existing \"step\" syntax in isolationclunkier than the syntax used in Greenplum's \"isolation2\" framework. \n> See the script [1] for parsing the test cases for more details on the \n> syntax and capabilities (it is in Python).\n\nHmm.  The bar to add a new hard language dependency in the test\nsuites is very high.  I am not sure that we'd want something with a\npython dependency for the tests, also knowing how Python likes\nbreaking compatibility (isolation2_main() also mentions a dependency\nto Python).Agreed, I don't think it needs to be in Python.My point was that some of our \"isolation2\" framework has to be different becauseit is enabling us to test features that are in Greenplum and not in Postgres.However, many of the features it has would actually be really handy to have fortesting Postgres.It wasn't initially suggested upstream because it is actually mainly ported froma separate standalone testing framework that was written at Greenplum in Python.I've heard Greenplum folks talk about re-writing our \"isolation2\" framework in(probably) C and making it a better fit to contribute. It's definitely on my wishlist. -- Melanie Plageman", "msg_date": "Thu, 22 Aug 2019 21:19:47 -0700", "msg_from": "Melanie Plageman <melanieplageman@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Thu, Aug 22, 2019 at 09:19:47PM -0700, Melanie Plageman wrote:\n> It's a connection parameter that allows you to connect to a single Postgres\n> node in a Greenplum cluster. I only included it as an example of the kind of\n> \"Greenplum-specific\" things that are in the test framework.\n\nAh, I see. I had the same stuff for XC to connect to data nodes.\n\n> I've heard Greenplum folks talk about re-writing our \"isolation2\" framework\n> in (probably) C and making it a better fit to contribute. It's definitely on\n> my wishlist.\n\nNice to hear that.\n--\nMichael", "msg_date": "Fri, 23 Aug 2019 13:40:12 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Thu, Aug 22, 2019 at 12:47 AM Alvaro Herrera <alvherre@2ndquadrant.com>\nwrote:\n>\n> On 2019-Aug-21, Melanie Plageman wrote:\n>\n> > In Greenplum, we mainly add new tests to a separate isolation\n> > framework (called isolation2) which uses a completely different\n> > syntax. It doesn't use isolationtester at all. So, I haven't had a use\n> > case to add long options to isolationtester yet :)\n>\n> Is that other framework somehow more capable?\n>\n\nThe ability to declare a step as blocking, as Melanie mentioned upthread\n(\"&\" prefix), makes it more capable. The tester, when encounters such a\nstep, makes sure that the command in that step is blocking and moves on to\nrun subsequent commands. The isolationtester, on the other hand, treats a\nstep as blocking only when the command waits on a lock. That seems\nrestrictive. E.g. what if a command waits on a latch, as part of a valid\ninterleaving of concurrent transactions? The isolation tester cannot\ndetect such a case and it will keep waiting and eventually fail the test\nwith a timeout.\n\nAs part of the fault injector patch set [1], I added a new \"blocking\"\nkeyword to isolation grammar so that a step can be declared as blocking.\nSee patch 0002-Add-syntax-to-declare-a-step-that-is-expected-to-block.\n\nAsim\n\n[1]\nhttps://www.postgresql.org/message-id/CANXE4TdxdESX1jKw48xet-5GvBFVSq%3D4cgNeioTQff372KO45A%40mail.gmail.com\n\nOn Thu, Aug 22, 2019 at 12:47 AM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:>> On 2019-Aug-21, Melanie Plageman wrote:>> > In Greenplum, we mainly add new tests to a separate isolation> > framework (called isolation2) which uses a completely different> > syntax. It doesn't use isolationtester at all. So, I haven't had a use> > case to add long options to isolationtester yet :)>> Is that other framework somehow more capable?>The ability to declare a step as blocking, as Melanie mentioned upthread (\"&\" prefix), makes it more capable.  The tester, when encounters such a step, makes sure that the command in that step is blocking and moves on to run subsequent commands.  The isolationtester, on the other hand, treats a step as blocking only when the command waits on a lock.  That seems restrictive.  E.g. what if a command waits on a latch, as part of a valid interleaving of concurrent transactions?  The isolation tester cannot detect such a case and it will keep waiting and eventually fail the test with a timeout.As part of the fault injector patch set [1], I added a new \"blocking\" keyword to isolation grammar so that a step can be declared as blocking.  See patch 0002-Add-syntax-to-declare-a-step-that-is-expected-to-block.Asim[1] https://www.postgresql.org/message-id/CANXE4TdxdESX1jKw48xet-5GvBFVSq%3D4cgNeioTQff372KO45A%40mail.gmail.com", "msg_date": "Fri, 23 Aug 2019 17:39:35 +0530", "msg_from": "Asim R P <apraveen@pivotal.io>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On 2019-Aug-23, Asim R P wrote:\n\n> As part of the fault injector patch set [1], I added a new \"blocking\"\n> keyword to isolation grammar so that a step can be declared as blocking.\n> See patch 0002-Add-syntax-to-declare-a-step-that-is-expected-to-block.\n\nOne point to that implementation is that in that design a step is\nglobally declared to be blocking, but in reality that's the wrong way to\nsee things: a step might block in some permutations and not others. So\nI think we should do as Michael suggested: it's the permutation that has\nto have a way to mark a given step as blocking, not the step itself.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 23 Aug 2019 11:38:25 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "(Re-adding pgsql-hackers)\n\nOn Fri, Aug 23, 2019 at 05:28:35PM +0530, Asim R P wrote:\n> Both the patches look good to me, thank you. +1 to removing dry-run and\n> tracking unused steps.\n\nThanks, both have been committed. There have been issues with the\nisolation tests of logical decoding I have taken care of.\n--\nMichael", "msg_date": "Sat, 24 Aug 2019 14:45:34 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Fri, Aug 23, 2019 at 9:08 PM Alvaro Herrera <alvherre@2ndquadrant.com>\nwrote:\n>\n> On 2019-Aug-23, Asim R P wrote:\n>\n> > As part of the fault injector patch set [1], I added a new \"blocking\"\n> > keyword to isolation grammar so that a step can be declared as blocking.\n> > See patch 0002-Add-syntax-to-declare-a-step-that-is-expected-to-block.\n>\n> One point to that implementation is that in that design a step is\n> globally declared to be blocking, but in reality that's the wrong way to\n> see things: a step might block in some permutations and not others. So\n> I think we should do as Michael suggested: it's the permutation that has\n> to have a way to mark a given step as blocking, not the step itself.\n\nThank you for the feedback. I've changed patch 0002 accordingly, please\ntake another look:\nhttps://www.postgresql.org/message-id/CANXE4TdvSi7Yia_5sV82%2BMHf0WcUSN9u6_X8VEUBv-YStphd%3DQ%40mail.gmail.com\n\nAsim\n\nOn Fri, Aug 23, 2019 at 9:08 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:>> On 2019-Aug-23, Asim R P wrote:>> > As part of the fault injector patch set [1], I added a new \"blocking\"> > keyword to isolation grammar so that a step can be declared as blocking.> > See patch 0002-Add-syntax-to-declare-a-step-that-is-expected-to-block.>> One point to that implementation is that in that design a step is> globally declared to be blocking, but in reality that's the wrong way to> see things: a step might block in some permutations and not others.  So> I think we should do as Michael suggested: it's the permutation that has> to have a way to mark a given step as blocking, not the step itself.Thank you for the feedback.  I've changed patch 0002 accordingly, please take another look: https://www.postgresql.org/message-id/CANXE4TdvSi7Yia_5sV82%2BMHf0WcUSN9u6_X8VEUBv-YStphd%3DQ%40mail.gmail.comAsim", "msg_date": "Tue, 27 Aug 2019 19:05:50 +0530", "msg_from": "Asim R P <apraveen@pivotal.io>", "msg_from_op": false, "msg_subject": "Re: Cleanup isolation specs from unused steps" }, { "msg_contents": "On Tue, Aug 27, 2019 at 07:05:50PM +0530, Asim R P wrote:\n> Thank you for the feedback. I've changed patch 0002 accordingly, please\n> take another look:\n> https://www.postgresql.org/message-id/CANXE4TdvSi7Yia_5sV82%2BMHf0WcUSN9u6_X8VEUBv-YStphd%3DQ%40mail.gmail.com\n\nThanks! Let's move the discussion on the other thread then.\n--\nMichael", "msg_date": "Wed, 28 Aug 2019 11:52:10 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Cleanup isolation specs from unused steps" } ]
[ { "msg_contents": "Hello\n\nIs psql command \\r actually works? I expected \\r and then \\e command should start editor without text of last query.\n\nLANG=C EDITOR=cat psql \npsql (11.5 (Debian 11.5-1.pgdg100+1))\nType \"help\" for help.\n\nmelkij=> select 1;\n ?column? \n----------\n 1\n(1 row)\n\nmelkij=> \\r\nQuery buffer reset (cleared).\nmelkij=> \\e\nselect 1;\n ?column? \n----------\n 1\n(1 row)\n\nBuffer is still here, in normal external editors too.\nSame test on REL9_6_STABLE:\n\npostgres=# select 1;\n ?column? \n----------\n 1\n(1 row)\n\npostgres=# \\r\nQuery buffer reset (cleared).\npostgres=# \\e\n\nBuffer was actually cleared.\n\nI see this behavior change on >= 10 versions\n\nregards, Sergei\n\n\n", "msg_date": "Mon, 19 Aug 2019 17:17:44 +0300", "msg_from": "Sergei Kornilov <sk@zsrv.org>", "msg_from_op": true, "msg_subject": "psql \\r command is working?" }, { "msg_contents": "Sergei Kornilov <sk@zsrv.org> writes:\n> Is psql command \\r actually works? I expected \\r and then \\e command should start editor without text of last query.\n\n\\r clears the current query buffer. \\e without an argument is\ndefined to edit the current query buffer, or if that is empty,\nthe last query. I don't see anything particularly wrong here.\n\n> I see this behavior change on >= 10 versions\n\nPossibly fixed as a side effect of e984ef586.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 19 Aug 2019 10:28:29 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: psql \\r command is working?" }, { "msg_contents": "so this is expected behavior, ok, thank you!\n\nregards, Sergei\n\n\n", "msg_date": "Mon, 19 Aug 2019 17:34:24 +0300", "msg_from": "Sergei Kornilov <sk@zsrv.org>", "msg_from_op": true, "msg_subject": "Re: psql \\r command is working?" } ]
[ { "msg_contents": "Hi,\n\nin the README, top level, there is this:\n\nPostgreSQL has many language interfaces, many of which are listed here:\nhttps://www.postgresql.org/download\n\nI don't think the download page lists any language interfaces or do I miss something?\n\nRegards\nDaniel\n\n\n\n\n\n\n\n\nHi,\n\n\n\n\nin the README, top level, there is this:\n\n\n\n\n\nPostgreSQL has many language interfaces, many of which are listed here:\nhttps://www.postgresql.org/download\n\n\n\n\nI don't think the download page lists any language interfaces or do I miss something?\n\n\n\n\nRegards\n\nDaniel", "msg_date": "Mon, 19 Aug 2019 14:45:51 +0000", "msg_from": "\"Daniel Westermann (DWE)\" <daniel.westermann@dbi-services.com>", "msg_from_op": true, "msg_subject": "Wrong sentence in the README?" }, { "msg_contents": "\"Daniel Westermann (DWE)\" <daniel.westermann@dbi-services.com> writes:\n> in the README, top level, there is this:\n\n> PostgreSQL has many language interfaces, many of which are listed here:\n> https://www.postgresql.org/download\n\n> I don't think the download page lists any language interfaces or do I miss something?\n\nNot directly on that page, though if you drill down into the \"software\ncatalogue\" you can find them.\n\nSince there's already a link to that same page a bit further down in\nthe file, I'm inclined to just remove the quoted sentence. Maybe\nadd something about \"and related software\" to the later link. Certainly\n\"language interfaces\" is just one small part of that.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 22 Sep 2019 12:28:02 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Wrong sentence in the README?" }, { "msg_contents": "\"Daniel Westermann (DWE)\" <daniel.westermann@dbi-services.com> writes:\n>> in the README, top level, there is this:\n\n>> PostgreSQL has many language interfaces, many of which are listed here:\n>> https://www.postgresql.org/download\n\n>> I don't think the download page lists any language interfaces or do I miss something?\n\n>Not directly on that page, though if you drill down into the \"software\n>catalogue\" you can find them.\n\n>Since there's already a link to that same page a bit further down in\n>the file, I'm inclined to just remove the quoted sentence. Maybe\n>add something about \"and related software\" to the later link. Certainly\n>\"language interfaces\" is just one small part of that.\n\nThank you, Tom. I'll try to come up with a patch for that in the next days.\n\nRegards\nDaniel\n\n\n\n\n\n\n\n\"Daniel Westermann (DWE)\" <daniel.westermann@dbi-services.com> writes:\n\n\n\n>> in the README, top level, there is this:\n\n>> PostgreSQL has many language interfaces, many of which are listed here:\n>> https://www.postgresql.org/download\n\n>> I don't think the download page lists any language interfaces or do I miss something?\n\n>Not directly on that page, though if you drill down into the \"software\n>catalogue\" you can find them.\n\n>Since there's already a link to that same page a bit further down in\n>the file, I'm inclined to just remove the quoted sentence.  Maybe\n>add something about \"and related software\" to the later link.  Certainly\n>\"language interfaces\" is just one small part of that.\n\n\n\nThank you, Tom. I'll try to come up with a patch for that in the next days.\n\n\nRegards\nDaniel", "msg_date": "Mon, 23 Sep 2019 15:18:55 +0000", "msg_from": "\"Daniel Westermann (DWE)\" <daniel.westermann@dbi-services.com>", "msg_from_op": true, "msg_subject": "Re: Wrong sentence in the README?" }, { "msg_contents": "On Sun, Sep 22, 2019 at 12:28:02PM -0400, Tom Lane wrote:\n> \"Daniel Westermann (DWE)\" <daniel.westermann@dbi-services.com> writes:\n> > in the README, top level, there is this:\n> \n> > PostgreSQL has many language interfaces, many of which are listed here:\n> > https://www.postgresql.org/download\n> \n> > I don't think the download page lists any language interfaces or do I miss something?\n> \n> Not directly on that page, though if you drill down into the \"software\n> catalogue\" you can find them.\n> \n> Since there's already a link to that same page a bit further down in\n> the file, I'm inclined to just remove the quoted sentence. Maybe\n> add something about \"and related software\" to the later link. Certainly\n> \"language interfaces\" is just one small part of that.\n\nFour years later, attached patch applied to master to implement these\nchanges.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n Only you can decide what is important to you.", "msg_date": "Wed, 8 Nov 2023 16:34:57 -0500", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Wrong sentence in the README?" } ]
[ { "msg_contents": "Hi,\n\nFor already some time I'm following the new linux IO interface \"io_uring\", that\nwas introduced relatively recently [1]. Short description says:\n\n Shared application/kernel submission and completion ring pairs, for\n supporting fast/efficient IO.\n\nFor us the important part is probably that it's an asynchronious IO, that can\nwork not only with O_DIRECT, but with also with buffered access. Plus there are\nclaims that it's pretty efficient (efficiency was one of the design goals [2]).\nThe interface consists of submit/complete queues and data structures, shared\nbetween an application and the kernel. To facilitate application development\nthere is also a nice library to utilize io_uring from the user space [3].\n\nSince I haven't found that many discussions in the hackers archives about async\nIO, and out of curiosity decided to prepare an experimental patch to see how\nthis would looks like to use io_uring in PostgreSQL. I've tested this patch so\nfar only inside a qemu vm on the latest io_uring branch from linux-block tree.\nThe result is relatively simple, and introduces new interface smgrqueueread,\nsmgrsubmitread and smgrwaitread to queue any read we want, then submit a queue\nto a kernel and then wait for a result. The simplest example of how this\ninterface could be used I found in pg_prewarm for buffers prefetching.\n\nAs a result of this experiment I have few questions, open points and requests\nfor the community experience:\n\n* I guess the proper implementation to use async IO is a big deal, but could\n bring also significant performance advantages. Is there any (nearest) future\n for such kind of async IO in PostgreSQL? Buffer prefetching is a simplest\n example, but taking into account that io_uring supports ordering, barriers\n and linked events, there are probably more use cases when it could be useful.\n\n* Assuming that the answer for previous question is positive, there could be\n different strategies how to use io_uring. So far I see different\n opportunities for waiting. Let's say we have prepared a batch of async IO\n operations and submitted it. Then we can e.g.\n\n -> just wait for a batch to be finished\n -> wait (in the same syscall as submitting) for previously submitted batches,\n then start submitting again, and at the end wait for the leftovers\n -> peek if there are any events completed, and get only those without waiting\n for the whole batch (in this case it's necessary to make sure submission\n queue is not overflowed)\n\n So it's open what and when to use.\n\n* Does it makes sense to use io_uring for smgrprefetch? Originally I've added\n io_uring parts into FilePrefetch also (in the form of preparing and submiting\n just one buffer), but not sure if this API is suitable.\n\n* How may look like a data structure, that can describe IO from PostgreSQL\n perspective? With io_uring we need to somehow identify IO operations that\n were completed. For now I'm just using a buffer number. Btw, this\n experimental patch has many limitations, e.g. only one ring is used for\n everything, which is of course far from ideal and makes identification even\n more important.\n\n* There are few more freedom dimensions, that io_uring introduces - how many\n rings to use, how many events per ring (which is going to be n for sqe and\n 2*n for cqe), how many IO operations per event to do (similar to\n preadv/pwritev we can provide a vector), what would be the balance between\n submit and complete queues. I guess it will require a lot of benchmarking to\n find a good values for these.\n\n\n[1]: https://github.com/torvalds/linux/commit/38e7571c07be01f9f19b355a9306a4e3d5cb0f5b\n[2]: http://kernel.dk/io_uring.pdf\n[3]: http://git.kernel.dk/cgit/liburing/", "msg_date": "Mon, 19 Aug 2019 20:20:46 +0200", "msg_from": "Dmitry Dolgov <9erthalion6@gmail.com>", "msg_from_op": true, "msg_subject": "io_uring support" }, { "msg_contents": "Hi,\n\nOn 2019-08-19 20:20:46 +0200, Dmitry Dolgov wrote:\n> For already some time I'm following the new linux IO interface \"io_uring\", that\n> was introduced relatively recently [1]. Short description says:\n> \n> Shared application/kernel submission and completion ring pairs, for\n> supporting fast/efficient IO.\n\nYes, it's quite promising. I also played around some with it. One\nthing I particularly like is that it seems somewhat realistic to have an\nabstraction that both supports io_uring and window's iocp - personally I\ndon't think we need support for more than those.\n\n\n> For us the important part is probably that it's an asynchronious IO, that can\n> work not only with O_DIRECT, but with also with buffered access.\n\nNote that while the buffered access does allow for some acceleration, it\ncurrently does have quite noticable CPU overhead.\n\n\n> Since I haven't found that many discussions in the hackers archives about async\n> IO, and out of curiosity decided to prepare an experimental patch to see how\n> this would looks like to use io_uring in PostgreSQL.\n\nCool!\n\n\n> I've tested this patch so far only inside a qemu vm on the latest\n> io_uring branch from linux-block tree. The result is relatively\n> simple, and introduces new interface smgrqueueread, smgrsubmitread and\n> smgrwaitread to queue any read we want, then submit a queue to a\n> kernel and then wait for a result. The simplest example of how this\n> interface could be used I found in pg_prewarm for buffers prefetching.\n\nHm. I'm bit doubtful that that's going in the direction of being the\nright interface. I think we'd basically have to insist that all AIO\ncapable smgr's use one common AIO layer (note that the UNDO patches add\nanother smgr implementation). Otherwise I think we'll have a very hard\ntime to make them cooperate. An interface like this would also lead to\na lot of duplicated interfaces, because we'd basically need most of the\nsmgr interface functions duplicated.\n\nI suspect we'd rather have to build something where the existing\nfunctions grow a parameter controlling synchronizity. If AIO is allowed\nand supported, the smgr implementation would initiate the IO, together\nwith a completion function for it, and return some value allowing the\ncaller to wait for the result if desirable.\n\n\n\n> As a result of this experiment I have few questions, open points and requests\n> for the community experience:\n> \n> * I guess the proper implementation to use async IO is a big deal, but could\n> bring also significant performance advantages. Is there any (nearest) future\n> for such kind of async IO in PostgreSQL? Buffer prefetching is a simplest\n> example, but taking into account that io_uring supports ordering, barriers\n> and linked events, there are probably more use cases when it could be useful.\n\nThe lowest hanging fruit that I can see - and which I played with - is\nmaking the writeback flushing use async IO. That's particularly\ninteresting for bgwriter. As it commonly only performs random IO, and\nas we need to keep the number of dirty buffers in the kernel small to\navoid huge latency spikes, being able to submit IOs asynchronously can\nyield significant benefits.\n\n\n\n> * Assuming that the answer for previous question is positive, there could be\n> different strategies how to use io_uring. So far I see different\n> opportunities for waiting. Let's say we have prepared a batch of async IO\n> operations and submitted it. Then we can e.g.\n> \n> -> just wait for a batch to be finished\n> -> wait (in the same syscall as submitting) for previously submitted batches,\n> then start submitting again, and at the end wait for the leftovers\n> -> peek if there are any events completed, and get only those without waiting\n> for the whole batch (in this case it's necessary to make sure submission\n> queue is not overflowed)\n> \n> So it's open what and when to use.\n\nI don't think there's much point in working only with complete\nbatches. I think we'd loose too much of the benefit by introducing\nunnecessary synchronous operations. I think we'd need to design the\ninterface in a way that there constantly can be in-progress IOs, block\nwhen the queue is full, and handle finished IOs using a callback\nmechanism or such.\n\n\n> * Does it makes sense to use io_uring for smgrprefetch? Originally I've added\n> io_uring parts into FilePrefetch also (in the form of preparing and submiting\n> just one buffer), but not sure if this API is suitable.\n\nI have a hard time seeing that being worthwhile, unless we change the\nway it's used significantly. I think to benefit really, we'd have to be\nable to lock multiple buffers, and have io_uring prefetch directly into\nbuffers.\n\n\n> * How may look like a data structure, that can describe IO from PostgreSQL\n> perspective? With io_uring we need to somehow identify IO operations that\n> were completed. For now I'm just using a buffer number.\n\nIn my hacks I've used the sqe's user_data to point to a struct with\ninformation about the IO.\n\n\n> Btw, this\n> experimental patch has many limitations, e.g. only one ring is used for\n> everything, which is of course far from ideal and makes identification even\n> more important.\n\nI think we don't want to use more than one ring. Makes it too\ncomplicated to have interdependencies between operations (e.g. waiting\nfor fsyncs before submitting further writes). I also don't really see\nwhy we would benefit from more?\n\n\n> * There are few more freedom dimensions, that io_uring introduces - how many\n> rings to use, how many events per ring (which is going to be n for sqe and\n> 2*n for cqe), how many IO operations per event to do (similar to\n> preadv/pwritev we can provide a vector), what would be the balance between\n> submit and complete queues. I guess it will require a lot of benchmarking to\n> find a good values for these.\n\n\nOne thing you didn't mention: A lot of this also requires that we\noverhaul the way buffer locking for IOs works. Currently we really can\nonly have one proper IO in progress at a time, which clearly isn't\nsufficient for anything that wants to use AIO.\n\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 19 Aug 2019 13:21:21 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: io_uring support" }, { "msg_contents": "> On Mon, Aug 19, 2019 at 10:21 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> > For us the important part is probably that it's an asynchronious IO, that can\n> > work not only with O_DIRECT, but with also with buffered access.\n>\n> Note that while the buffered access does allow for some acceleration, it\n> currently does have quite noticable CPU overhead.\n\nI haven't looked deep at benchmarks yet, is there any public results that show\nthis? So far I've seen only [1], but it doesn't say too much about CPU\noverhead. Probably it could be also interesting to check io_uring-bench.\n\n> > I've tested this patch so far only inside a qemu vm on the latest\n> > io_uring branch from linux-block tree. The result is relatively\n> > simple, and introduces new interface smgrqueueread, smgrsubmitread and\n> > smgrwaitread to queue any read we want, then submit a queue to a\n> > kernel and then wait for a result. The simplest example of how this\n> > interface could be used I found in pg_prewarm for buffers prefetching.\n>\n> Hm. I'm bit doubtful that that's going in the direction of being the\n> right interface. I think we'd basically have to insist that all AIO\n> capable smgr's use one common AIO layer (note that the UNDO patches add\n> another smgr implementation). Otherwise I think we'll have a very hard\n> time to make them cooperate. An interface like this would also lead to\n> a lot of duplicated interfaces, because we'd basically need most of the\n> smgr interface functions duplicated.\n>\n> I suspect we'd rather have to build something where the existing\n> functions grow a parameter controlling synchronizity. If AIO is allowed\n> and supported, the smgr implementation would initiate the IO, together\n> with a completion function for it, and return some value allowing the\n> caller to wait for the result if desirable.\n\nAgree, all AIO capable smgr's need to use some common layer. But it seems hard\nto implement some async operations only via adding more parameters, e.g.\naccumulating AIO operations before submitting to a kernel.\n\n> > As a result of this experiment I have few questions, open points and requests\n> > for the community experience:\n> >\n> > * I guess the proper implementation to use async IO is a big deal, but could\n> > bring also significant performance advantages. Is there any (nearest) future\n> > for such kind of async IO in PostgreSQL? Buffer prefetching is a simplest\n> > example, but taking into account that io_uring supports ordering, barriers\n> > and linked events, there are probably more use cases when it could be useful.\n>\n> The lowest hanging fruit that I can see - and which I played with - is\n> making the writeback flushing use async IO. That's particularly\n> interesting for bgwriter. As it commonly only performs random IO, and\n> as we need to keep the number of dirty buffers in the kernel small to\n> avoid huge latency spikes, being able to submit IOs asynchronously can\n> yield significant benefits.\n\nYeah, sounds interesting. Are there any results you already can share? Maybe\nit's possible to collaborate on this topic?\n\n> > * Assuming that the answer for previous question is positive, there could be\n> > different strategies how to use io_uring. So far I see different\n> > opportunities for waiting. Let's say we have prepared a batch of async IO\n> > operations and submitted it. Then we can e.g.\n> >\n> > -> just wait for a batch to be finished\n> > -> wait (in the same syscall as submitting) for previously submitted batches,\n> > then start submitting again, and at the end wait for the leftovers\n> > -> peek if there are any events completed, and get only those without waiting\n> > for the whole batch (in this case it's necessary to make sure submission\n> > queue is not overflowed)\n> >\n> > So it's open what and when to use.\n>\n> I don't think there's much point in working only with complete\n> batches. I think we'd loose too much of the benefit by introducing\n> unnecessary synchronous operations. I think we'd need to design the\n> interface in a way that there constantly can be in-progress IOs, block\n> when the queue is full, and handle finished IOs using a callback\n> mechanism or such.\n\nWhat would happen if we suddenly don't have enough IO at this particular\nmoment to fill a queue? Probably there should be more triggers for blocking.\n\n> > * How may look like a data structure, that can describe IO from PostgreSQL\n> > perspective? With io_uring we need to somehow identify IO operations that\n> > were completed. For now I'm just using a buffer number.\n>\n> In my hacks I've used the sqe's user_data to point to a struct with\n> information about the IO.\n\nYes, that's the same approach I'm using too. I'm just not sure what exactly\nshould be this \"struct with information about the IO\", what should it contain\nideally?\n\n> > experimental patch has many limitations, e.g. only one ring is used for\n> > everything, which is of course far from ideal and makes identification even\n> > more important.\n>\n> I think we don't want to use more than one ring. Makes it too\n> complicated to have interdependencies between operations (e.g. waiting\n> for fsyncs before submitting further writes). I also don't really see\n> why we would benefit from more?\n\nSince the balance between SQE and CQE can be important and there could be\ndifferent \"sources of AIO\" with different submission frequency, I thought I\ncould be handy to separate \"heavy loaded\" rings from common purpose rings\n(especially in the case of ordered AIO).\n\n> > * There are few more freedom dimensions, that io_uring introduces - how many\n> > rings to use, how many events per ring (which is going to be n for sqe and\n> > 2*n for cqe), how many IO operations per event to do (similar to\n> > preadv/pwritev we can provide a vector), what would be the balance between\n> > submit and complete queues. I guess it will require a lot of benchmarking to\n> > find a good values for these.\n>\n>\n> One thing you didn't mention: A lot of this also requires that we\n> overhaul the way buffer locking for IOs works. Currently we really can\n> only have one proper IO in progress at a time, which clearly isn't\n> sufficient for anything that wants to use AIO.\n\nYeah, that's correct. My hopes are that this could be done in small steps, e.g.\nintroduce AIO only for some particular cases to see how would it work.\n\n[1]: https://lore.kernel.org/linux-block/20190116175003.17880-1-axboe@kernel.dk/\n\n\n", "msg_date": "Fri, 23 Aug 2019 12:14:05 +0200", "msg_from": "Dmitry Dolgov <9erthalion6@gmail.com>", "msg_from_op": true, "msg_subject": "Re: io_uring support" } ]
[ { "msg_contents": "Hello hackers,\n\nNow that the unicums checking is finished, I would like to share the\nscript I used to find them.\nMaybe it can be useful to recheck the source tree from time to time...\nI don't think that the check could be fully automated, but with some\neyeballing it allows to maintain a more consistent state.\n\nBest regards,\nAlexander", "msg_date": "Mon, 19 Aug 2019 22:19:19 +0300", "msg_from": "Alexander Lakhin <exclusion@gmail.com>", "msg_from_op": true, "msg_subject": "Fixing typos and inconsistencies" }, { "msg_contents": "On Tue, Aug 20, 2019 at 3:05 PM Alexander Lakhin <exclusion@gmail.com> wrote:\n> Now that the unicums checking is finished, I would like to share the\n> script I used to find them.\n> Maybe it can be useful to recheck the source tree from time to time...\n> I don't think that the check could be fully automated, but with some\n> eyeballing it allows to maintain a more consistent state.\n\nVery clever! Thanks for doing that, and sorry for all my typos.\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Tue, 20 Aug 2019 17:23:03 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Fixing typos and inconsistencies" }, { "msg_contents": "On Mon, Aug 19, 2019 at 10:19:19PM +0300, Alexander Lakhin wrote:\n> Now that the unicums checking is finished, I would like to share the\n> script I used to find them.\n> Maybe it can be useful to recheck the source tree from time to time...\n> I don't think that the check could be fully automated, but with some\n> eyeballing it allows to maintain a more consistent state.\n\nCool, thanks for sharing.\n\nWe still have a couple of things left though, one which stood out\nrecently was a reference to TupleLockUpdate in heapam.c. This relates\nto multixact, so I am not actually sure to which lock level this was\nreferring to.\n--\nMichael", "msg_date": "Tue, 20 Aug 2019 19:15:45 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Fixing typos and inconsistencies" } ]
[ { "msg_contents": "Hi all,\n\nWhile refactoring some code, I have bumped into $subject, which causes\nboth tools to have incorrect error message formats and progname being\nused all through the code, sometimes incorrectly or just missing.\n\nAt the same time, we are missing a call to set_pglocale_pgservice()\nfor both binaries.\n\nAny objections to the cleanup attached?\n--\nMichael", "msg_date": "Tue, 20 Aug 2019 10:28:19 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Plug-in common/logging.h with vacuumlo and oid2name" }, { "msg_contents": "On 2019-08-20 03:28, Michael Paquier wrote:\n> +\t\t\t\t\tpg_log_error(\"\\nfailed to remove lo %u: %s\", lo,\n> +\t\t\t\t\t\t\t\t PQerrorMessage(conn));\n\nThis newline should be removed.\n\nprogname can probably be made into a local variable now.\n\nThe rest looks good to me.\n\nDo we need set_pglocale_pgservice() calls here if we're not doing NLS?\nDoes the logging stuff require it? I'm not sure.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 4 Sep 2019 10:17:57 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Plug-in common/logging.h with vacuumlo and oid2name" }, { "msg_contents": "On Wed, Sep 04, 2019 at 10:17:57AM +0200, Peter Eisentraut wrote:\n> On 2019-08-20 03:28, Michael Paquier wrote:\n> > +\t\t\t\t\tpg_log_error(\"\\nfailed to remove lo %u: %s\", lo,\n> > +\t\t\t\t\t\t\t\t PQerrorMessage(conn));\n> \n> This newline should be removed.\n\nThanks, missed that.\n\n> progname can probably be made into a local variable now.\n\nCan it? vacuumlo() still uses the progname from _param for the\nconnection string.\n\n> Do we need set_pglocale_pgservice() calls here if we're not doing NLS?\n> Does the logging stuff require it? I'm not sure.\n\nThe logging part does not require it, but this can be used for\nPGSYSCONFDIR, no?\n--\nMichael", "msg_date": "Wed, 4 Sep 2019 21:17:46 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Plug-in common/logging.h with vacuumlo and oid2name" }, { "msg_contents": "On 2019-09-04 14:17, Michael Paquier wrote:\n>> progname can probably be made into a local variable now.\n> \n> Can it? vacuumlo() still uses the progname from _param for the\n> connection string.\n\nYeah, probably best to leave it as is for now.\n\n>> Do we need set_pglocale_pgservice() calls here if we're not doing NLS?\n>> Does the logging stuff require it? I'm not sure.\n> \n> The logging part does not require it, but this can be used for\n> PGSYSCONFDIR, no?\n\nHow does PGSYSCONFDIR come into play here?\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 4 Sep 2019 14:37:12 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Plug-in common/logging.h with vacuumlo and oid2name" }, { "msg_contents": "On Wed, Sep 04, 2019 at 02:37:12PM +0200, Peter Eisentraut wrote:\n>>> Do we need set_pglocale_pgservice() calls here if we're not doing NLS?\n>>> Does the logging stuff require it? I'm not sure.\n>> \n>> The logging part does not require it, but this can be used for\n>> PGSYSCONFDIR, no?\n> \n> How does PGSYSCONFDIR come into play here?\n\nThere is an argument to allow libpq to find out a service file for\na connection from the executable path. Note that oid2name can use a\nconnection string for connection, but not vacuumlo, so I somewhat\nmissed that.\n--\nMichael", "msg_date": "Thu, 5 Sep 2019 08:59:41 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Plug-in common/logging.h with vacuumlo and oid2name" }, { "msg_contents": "On Thu, Sep 05, 2019 at 08:59:41AM +0900, Michael Paquier wrote:\n> There is an argument to allow libpq to find out a service file for\n> a connection from the executable path. Note that oid2name can use a\n> connection string for connection, but not vacuumlo, so I somewhat\n> missed that.\n\nIf you think that's not worth considering for now, I am fine to drop\nthat part. What do you think about the updated patch attached then?\n--\nMichael", "msg_date": "Thu, 5 Sep 2019 16:40:46 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Plug-in common/logging.h with vacuumlo and oid2name" }, { "msg_contents": "On 2019-09-05 01:59, Michael Paquier wrote:\n> On Wed, Sep 04, 2019 at 02:37:12PM +0200, Peter Eisentraut wrote:\n>>>> Do we need set_pglocale_pgservice() calls here if we're not doing NLS?\n>>>> Does the logging stuff require it? I'm not sure.\n>>>\n>>> The logging part does not require it, but this can be used for\n>>> PGSYSCONFDIR, no?\n>>\n>> How does PGSYSCONFDIR come into play here?\n> \n> There is an argument to allow libpq to find out a service file for\n> a connection from the executable path. Note that oid2name can use a\n> connection string for connection, but not vacuumlo, so I somewhat\n> missed that.\n\nOh I see what's going on. PGSYSCONFDIR is used by libpq, and\nset_pglocale_pgservice() does some path mangling on PGSYSCONFDIR if set\nfor Windows. Shouldn't libpq do that itself? Worth looking into but\nprobably unrelated to your patch.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 5 Sep 2019 14:21:34 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Plug-in common/logging.h with vacuumlo and oid2name" }, { "msg_contents": "Patch looks good to me, please push.\n\nGenerally speaking I find the 'progname' handling a bit silly (since we\nhave it both as a variable in each program and also in logging.c\nseparately), but that's not the fault of this patch, and this patch\ndoesn't make it worse. That said, I think some other messages in\nvacuumlo can be made pg_log_somelevel(), based on occurrences of\n'progname'.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 5 Sep 2019 09:59:51 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Plug-in common/logging.h with vacuumlo and oid2name" }, { "msg_contents": "On Thu, Sep 05, 2019 at 09:59:51AM -0400, Alvaro Herrera wrote:\n> Patch looks good to me, please push.\n\nThanks, applied without the calls to set_pglocale_pgservice().\n\n> Generally speaking I find the 'progname' handling a bit silly (since we\n> have it both as a variable in each program and also in logging.c\n> separately), but that's not the fault of this patch, and this patch\n> doesn't make it worse. That said, I think some other messages in\n> vacuumlo can be made pg_log_somelevel(), based on occurrences of\n> 'progname'.\n\nThat would mean moving some of the messages from stdout to stderr. We\ncould do that.\n--\nMichael", "msg_date": "Fri, 6 Sep 2019 14:01:42 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Plug-in common/logging.h with vacuumlo and oid2name" } ]
[ { "msg_contents": "I have troubles to understand the pg lock in the following simple\nsituation.\n\n\nSession 1:\n\n\nbegin; update t set a = 1 where a = 10;\n\n\nSession 2:\n\n\nbegin; update t set a = 2 where a = 10;\n\n\nThey update the same row and session 2 is blocked by session 1 without\nsurprise.\n\n\nThe pretty straight implementation is:\n\nSession 1 lock the the *tuple (ExclusiveLock)* mode.\n\nwhen session 2 lock it in exclusive mode, it is blocked.\n\n\nBut when I check the pg_locks: session 1. I can see *no tuple lock*\nthere, when I check the session 2, I can see a *tuple(ExclusiveLock) is\ngranted*, but it is waiting for a transactionid.\n\n\nsince every tuple has txn information, so it is not hard to implement it\nthis way. but is there any benefits over the the straight way? with the\ncurrent implementation, what is the point of tuple(ExclusiveLock) for\nsession 2?\n\nI have troubles to understand the pg lock in the following simple situation. Session 1:begin; update t set a = 1 where a = 10;Session 2:begin; update t set a = 2 where a = 10;They update the same row and session 2 is blocked by session 1 without surprise. The pretty straight implementation is: Session 1 lock the the tuple (ExclusiveLock) mode. when session 2 lock it in exclusive mode,  it is blocked. But when I check the pg_locks: session 1.  I can see no tuple lock there,  when I check the session 2,   I can see a tuple(ExclusiveLock) is granted,  but it is waiting for a transactionid. since every tuple has txn information,  so it is not hard to implement it this way.  but is there any benefits over the the straight way?   with the current implementation, what is the point of tuple(ExclusiveLock) for session 2?", "msg_date": "Tue, 20 Aug 2019 15:23:43 +0800", "msg_from": "Alex <zhihui.fan1213@gmail.com>", "msg_from_op": true, "msg_subject": "understand the pg locks in in an simple case" }, { "msg_contents": "Alex wrote:\n> But when I check the pg_locks: session 1. I can see no tuple lock\n> there, when I check the session 2, I can see a\n> tuple(ExclusiveLock) is granted, but it is waiting for a\n> transactionid. \n> \n> since every tuple has txn information, so it is not hard to\n> implement it this way. but is there any benefits over the the\n> straight way? with the current implementation, what is the point\n> of tuple(ExclusiveLock) for session 2?\n\n From what I can tell the reason is that pg_locks reports the\ninformation from the shared memory locking table, and tuple locks\nare *not* maintained there, but in the \"xmax\" of the row itself.\n\nTo see all tuple locks in pg_locks would require a sequential\nscan of all tables which have certain locks on them, which is not\ngoing to happen.\n\nYours,\nLaurenz Albe\n\n\n\n", "msg_date": "Tue, 20 Aug 2019 10:34:30 +0200", "msg_from": "Laurenz Albe <laurenz.albe@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: understand the pg locks in in an simple case" }, { "msg_contents": "On 20/08/2019 10:23, Alex wrote:\n> I have troubles to understand the pg lock in the following simple \n> situation.\n> \n> \n> Session 1:\n> \n> \n> begin; update tset a= 1 where a= 10;\n> \n> \n> Session 2:\n> \n> \n> begin; update tset a= 2 where a= 10;\n> \n> \n> They update the same row and session 2 is blocked by session 1 without \n> surprise.\n> \n> \n> The pretty straight implementation is:\n> \n> Session 1 lock the the *tuple (ExclusiveLock)* mode.\n> \n> when session 2 lock it in exclusive mode,  it is blocked.\n> \n> \n> But when I check the pg_locks: session 1.  I can see *no tuple \n> lock*there,  when I check the session 2,   I can see a \n> *tuple(ExclusiveLock) is granted*,  but it is waiting for a transactionid.\n> \n> \n> since every tuple has txn information,  so it is not hard to implement \n> it this way.  but is there any benefits over the the straight way? \n>  with the current implementation, what is the point \n> of tuple(ExclusiveLock) for session 2?\n\nThe reason that tuple locking works with XIDs, rather than directly \nacquiring a lock on the tuple, is that the memory allocated for the lock \nmanager is limited. One transaction can lock millions of tuples, and if \nit had to hold a normal lock on every tuple, you would run out of memory \nvery quickly.\n\nSo it may seem that we don't need heavy-weight locks on individual \ntuples at all. But we still them to establish the order that backends \nare waiting. The locking protocol is:\n\n1. Check if a tuple's xmax is set.\n2. If it's set, obtain a lock on the tuple's TID.\n3. Wait on the transaction to finish, by trying to acquire lock on the XID.\n4. Update the tuple, release the lock on the XID, and on the TID.\n\nIt gets more complicated if there are multixids, or you update a row you \nhave earlier locked in a weaker mode, but that's the gist of it.\n\nWe could skip the lock on the tuple's TID, but then if you have multiple \nbackends trying to update or lock a row, it would be not be \ndeterministic, who gets the lock first. For example:\n\nSession A: BEGIN; UPDATE foo SET col='a' WHERE id = 123;\nSession B: UPDATE foo SET col='b' WHERE id = 123; <blocks>\nSession C: UPDATE foo SET col='c' WHERE id = 123; <blocks>\nSession A: ROLLBACK;\n\nWithout the lock on the TID, it would be indeterministic, whether \nsession B or C gets to update the tuple, when A rolls back. With the \nabove locking protocol, B will go first. B will acquire the lock on the \nTID, and block on the XID lock, while C will block on the TID lock held \nby B. If there were more backends trying to do the same, they would \nqueue for the TID lock, too.\n\n- Heikki\n\n\n", "msg_date": "Tue, 20 Aug 2019 11:59:55 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: understand the pg locks in in an simple case" }, { "msg_contents": "On Tue, Aug 20, 2019 at 4:59 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n\n> On 20/08/2019 10:23, Alex wrote:\n> > I have troubles to understand the pg lock in the following simple\n> > situation.\n> >\n> >\n> > Session 1:\n> >\n> >\n> > begin; update tset a= 1 where a= 10;\n> >\n> >\n> > Session 2:\n> >\n> >\n> > begin; update tset a= 2 where a= 10;\n> >\n> >\n> > They update the same row and session 2 is blocked by session 1 without\n> > surprise.\n> >\n> >\n> > The pretty straight implementation is:\n> >\n> > Session 1 lock the the *tuple (ExclusiveLock)* mode.\n> >\n> > when session 2 lock it in exclusive mode, it is blocked.\n> >\n> >\n> > But when I check the pg_locks: session 1. I can see *no tuple\n> > lock*there, when I check the session 2, I can see a\n> > *tuple(ExclusiveLock) is granted*, but it is waiting for a\n> transactionid.\n> >\n> >\n> > since every tuple has txn information, so it is not hard to implement\n> > it this way. but is there any benefits over the the straight way?\n> > with the current implementation, what is the point\n> > of tuple(ExclusiveLock) for session 2?\n>\n> The reason that tuple locking works with XIDs, rather than directly\n> acquiring a lock on the tuple, is that the memory allocated for the lock\n> manager is limited. One transaction can lock millions of tuples, and if\n> it had to hold a normal lock on every tuple, you would run out of memory\n> very quickly.\n>\n\nThank you!\n\nso can I understand that we don't need a lock on every tuple we updated\nsince\n1). the number of lock may be huge, if we do so, it will consume a lot\nof memory\n2). the tuple header which includes xid info are unavoidable due to MVCC\nrequirement, and it can be used here, so we saved the individual lock\n\nand in my above example, when session 2 waiting for a xid lock, it is\n*granted* with a tuple lock with ExclusiveLock mode, what is the purpose\nof this lock?\n\n\n> So it may seem that we don't need heavy-weight locks on individual\n> tuples at all. But we still them to establish the order that backends\n> are waiting. The locking protocol is:\n>\n> 1. Check if a tuple's xmax is set.\n> 2. If it's set, obtain a lock on the tuple's TID.\n> 3. Wait on the transaction to finish, by trying to acquire lock on the XID.\n> 4. Update the tuple, release the lock on the XID, and on the TID.\n>\n> It gets more complicated if there are multixids, or you update a row you\n> have earlier locked in a weaker mode, but that's the gist of it.\n>\n> We could skip the lock on the tuple's TID, but then if you have multiple\n> backends trying to update or lock a row, it would be not be\n> deterministic, who gets the lock first. For example:\n>\n> Session A: BEGIN; UPDATE foo SET col='a' WHERE id = 123;\n> Session B: UPDATE foo SET col='b' WHERE id = 123; <blocks>\n> Session C: UPDATE foo SET col='c' WHERE id = 123; <blocks>\n> Session A: ROLLBACK;\n>\n> Without the lock on the TID, it would be indeterministic, whether\n> session B or C gets to update the tuple, when A rolls back. With the\n> above locking protocol, B will go first. B will acquire the lock on the\n> TID, and block on the XID lock, while C will block on the TID lock held\n> by B. If there were more backends trying to do the same, they would\n> queue for the TID lock, too.\n>\n> - Heikki\n>\n\nOn Tue, Aug 20, 2019 at 4:59 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:On 20/08/2019 10:23, Alex wrote:\n> I have troubles to understand the pg lock in the following simple \n> situation.\n> \n> \n> Session 1:\n> \n> \n> begin;   update  tset  a=  1  where  a=  10;\n> \n> \n> Session 2:\n> \n> \n> begin;  update  tset  a=  2  where  a=  10;\n> \n> \n> They update the same row and session 2 is blocked by session 1 without \n> surprise.\n> \n> \n> The pretty straight implementation is:\n> \n> Session 1 lock the the *tuple (ExclusiveLock)* mode.\n> \n> when session 2 lock it in exclusive mode,  it is blocked.\n> \n> \n> But when I check the pg_locks: session 1.  I can see *no tuple \n> lock*there,  when I check the session 2,   I can see a \n> *tuple(ExclusiveLock) is granted*,  but it is waiting for a transactionid.\n> \n> \n> since every tuple has txn information,  so it is not hard to implement \n> it this way.  but is there any benefits over the the straight way?  \n>   with the current implementation, what is the point \n> of tuple(ExclusiveLock) for session 2?\n\nThe reason that tuple locking works with XIDs, rather than directly \nacquiring a lock on the tuple, is that the memory allocated for the lock \nmanager is limited. One transaction can lock millions of tuples, and if \nit had to hold a normal lock on every tuple, you would run out of memory \nvery quickly.Thank you!so can I understand that we don't need a lock on every tuple we updated since 1).  the number of lock may be  huge,  if we do so,  it will consume a lot of memory2).  the tuple header which includes xid info are unavoidable due to MVCC requirement, and it can be used here, so we saved the individual lockand in my above example,  when session 2 waiting for a xid lock,  it is granted with a tuple lock with ExclusiveLock mode,  what is the purpose of this lock? \nSo it may seem that we don't need heavy-weight locks on individual \ntuples at all. But we still them to establish the order that backends \nare waiting. The locking protocol is:\n\n1. Check if a tuple's xmax is set.\n2. If it's set, obtain a lock on the tuple's TID.\n3. Wait on the transaction to finish, by trying to acquire lock on the XID.\n4. Update the tuple, release the lock on the XID, and on the TID.\n\nIt gets more complicated if there are multixids, or you update a row you \nhave earlier locked in a weaker mode, but that's the gist of it.\n\nWe could skip the lock on the tuple's TID, but then if you have multiple \nbackends trying to update or lock a row, it would be not be \ndeterministic, who gets the lock first. For example:\n\nSession A: BEGIN; UPDATE foo SET col='a' WHERE id = 123;\nSession B: UPDATE foo SET col='b' WHERE id = 123; <blocks>\nSession C: UPDATE foo SET col='c' WHERE id = 123; <blocks>\nSession A: ROLLBACK;\n\nWithout the lock on the TID, it would be indeterministic, whether \nsession B or C gets to update the tuple, when A rolls back. With the \nabove locking protocol, B will go first. B will acquire the lock on the \nTID, and block on the XID lock, while C will block on the TID lock held \nby B. If there were more backends trying to do the same, they would \nqueue for the TID lock, too.\n\n- Heikki", "msg_date": "Tue, 20 Aug 2019 22:52:03 +0800", "msg_from": "Alex <zhihui.fan1213@gmail.com>", "msg_from_op": true, "msg_subject": "Re: understand the pg locks in in an simple case" }, { "msg_contents": "On Tue, Aug 20, 2019 at 10:52 PM Alex <zhihui.fan1213@gmail.com> wrote:\n\n>\n>\n> On Tue, Aug 20, 2019 at 4:59 PM Heikki Linnakangas <hlinnaka@iki.fi>\n> wrote:\n>\n>> On 20/08/2019 10:23, Alex wrote:\n>> > I have troubles to understand the pg lock in the following simple\n>> > situation.\n>> >\n>> >\n>> > Session 1:\n>> >\n>> >\n>> > begin; update tset a= 1 where a= 10;\n>> >\n>> >\n>> > Session 2:\n>> >\n>> >\n>> > begin; update tset a= 2 where a= 10;\n>> >\n>> >\n>> > They update the same row and session 2 is blocked by session 1 without\n>> > surprise.\n>> >\n>> >\n>> > The pretty straight implementation is:\n>> >\n>> > Session 1 lock the the *tuple (ExclusiveLock)* mode.\n>> >\n>> > when session 2 lock it in exclusive mode, it is blocked.\n>> >\n>> >\n>> > But when I check the pg_locks: session 1. I can see *no tuple\n>> > lock*there, when I check the session 2, I can see a\n>> > *tuple(ExclusiveLock) is granted*, but it is waiting for a\n>> transactionid.\n>> >\n>> >\n>> > since every tuple has txn information, so it is not hard to implement\n>> > it this way. but is there any benefits over the the straight way?\n>> > with the current implementation, what is the point\n>> > of tuple(ExclusiveLock) for session 2?\n>>\n>> The reason that tuple locking works with XIDs, rather than directly\n>> acquiring a lock on the tuple, is that the memory allocated for the lock\n>> manager is limited. One transaction can lock millions of tuples, and if\n>> it had to hold a normal lock on every tuple, you would run out of memory\n>> very quickly.\n>>\n>\n> Thank you!\n>\n> so can I understand that we don't need a lock on every tuple we updated\n> since\n> 1). the number of lock may be huge, if we do so, it will consume a lot\n> of memory\n> 2). the tuple header which includes xid info are unavoidable due to MVCC\n> requirement, and it can be used here, so we saved the individual lock\n>\n> and in my above example, when session 2 waiting for a xid lock, it is\n> *granted* with a tuple lock with ExclusiveLock mode, what is the purpose\n> of this lock?\n>\n\nI will try to answer this question myself. the purpose of the tuple lock\n(with ExclusiveLock mode) is to protect there is no more than 1 client to\nadd the transaction lock on the same tuple at the same time. once the txn\nlock is added, the tuple lock can be released.\n\n\nSo it may seem that we don't need heavy-weight locks on individual\n>> tuples at all. But we still them to establish the order that backends\n>> are waiting. The locking protocol is:\n>>\n>> 1. Check if a tuple's xmax is set.\n>> 2. If it's set, obtain a lock on the tuple's TID.\n>> 3. Wait on the transaction to finish, by trying to acquire lock on the\n>> XID.\n>> 4. Update the tuple, release the lock on the XID, and on the TID.\n>>\n>> It gets more complicated if there are multixids, or you update a row you\n>> have earlier locked in a weaker mode, but that's the gist of it.\n>>\n>> We could skip the lock on the tuple's TID, but then if you have multiple\n>> backends trying to update or lock a row, it would be not be\n>> deterministic, who gets the lock first. For example:\n>>\n>> Session A: BEGIN; UPDATE foo SET col='a' WHERE id = 123;\n>> Session B: UPDATE foo SET col='b' WHERE id = 123; <blocks>\n>> Session C: UPDATE foo SET col='c' WHERE id = 123; <blocks>\n>> Session A: ROLLBACK;\n>>\n>> Without the lock on the TID, it would be indeterministic, whether\n>> session B or C gets to update the tuple, when A rolls back. With the\n>> above locking protocol, B will go first. B will acquire the lock on the\n>> TID, and block on the XID lock, while C will block on the TID lock held\n>> by B. If there were more backends trying to do the same, they would\n>> queue for the TID lock, too.\n>>\n>> - Heikki\n>>\n>\n\nOn Tue, Aug 20, 2019 at 10:52 PM Alex <zhihui.fan1213@gmail.com> wrote:On Tue, Aug 20, 2019 at 4:59 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:On 20/08/2019 10:23, Alex wrote:\n> I have troubles to understand the pg lock in the following simple \n> situation.\n> \n> \n> Session 1:\n> \n> \n> begin;   update  tset  a=  1  where  a=  10;\n> \n> \n> Session 2:\n> \n> \n> begin;  update  tset  a=  2  where  a=  10;\n> \n> \n> They update the same row and session 2 is blocked by session 1 without \n> surprise.\n> \n> \n> The pretty straight implementation is:\n> \n> Session 1 lock the the *tuple (ExclusiveLock)* mode.\n> \n> when session 2 lock it in exclusive mode,  it is blocked.\n> \n> \n> But when I check the pg_locks: session 1.  I can see *no tuple \n> lock*there,  when I check the session 2,   I can see a \n> *tuple(ExclusiveLock) is granted*,  but it is waiting for a transactionid.\n> \n> \n> since every tuple has txn information,  so it is not hard to implement \n> it this way.  but is there any benefits over the the straight way?  \n>   with the current implementation, what is the point \n> of tuple(ExclusiveLock) for session 2?\n\nThe reason that tuple locking works with XIDs, rather than directly \nacquiring a lock on the tuple, is that the memory allocated for the lock \nmanager is limited. One transaction can lock millions of tuples, and if \nit had to hold a normal lock on every tuple, you would run out of memory \nvery quickly.Thank you!so can I understand that we don't need a lock on every tuple we updated since 1).  the number of lock may be  huge,  if we do so,  it will consume a lot of memory2).  the tuple header which includes xid info are unavoidable due to MVCC requirement, and it can be used here, so we saved the individual lockand in my above example,  when session 2 waiting for a xid lock,  it is granted with a tuple lock with ExclusiveLock mode,  what is the purpose of this lock?I will try to answer this question myself.  the purpose of the tuple lock (with ExclusiveLock mode) is to protect there is no more than 1 client to add the transaction lock on the same tuple at the same time.  once the txn lock is added,  the tuple lock can be released. \nSo it may seem that we don't need heavy-weight locks on individual \ntuples at all. But we still them to establish the order that backends \nare waiting. The locking protocol is:\n\n1. Check if a tuple's xmax is set.\n2. If it's set, obtain a lock on the tuple's TID.\n3. Wait on the transaction to finish, by trying to acquire lock on the XID.\n4. Update the tuple, release the lock on the XID, and on the TID.\n\nIt gets more complicated if there are multixids, or you update a row you \nhave earlier locked in a weaker mode, but that's the gist of it.\n\nWe could skip the lock on the tuple's TID, but then if you have multiple \nbackends trying to update or lock a row, it would be not be \ndeterministic, who gets the lock first. For example:\n\nSession A: BEGIN; UPDATE foo SET col='a' WHERE id = 123;\nSession B: UPDATE foo SET col='b' WHERE id = 123; <blocks>\nSession C: UPDATE foo SET col='c' WHERE id = 123; <blocks>\nSession A: ROLLBACK;\n\nWithout the lock on the TID, it would be indeterministic, whether \nsession B or C gets to update the tuple, when A rolls back. With the \nabove locking protocol, B will go first. B will acquire the lock on the \nTID, and block on the XID lock, while C will block on the TID lock held \nby B. If there were more backends trying to do the same, they would \nqueue for the TID lock, too.\n\n- Heikki", "msg_date": "Tue, 27 Aug 2019 10:59:44 +0800", "msg_from": "Alex <zhihui.fan1213@gmail.com>", "msg_from_op": true, "msg_subject": "Re: understand the pg locks in in an simple case" } ]
[ { "msg_contents": "Before understanding how postgres implements the serializable isolation\nlevel (I have see many paper related to it), I have question about how it\nshould be.\n\n\nI mainly read the ideas from\nhttps://www.postgresql.org/docs/11/transaction-iso.html.\n\n\nIn fact, this isolation level works exactly the same as Repeatable Read\nexcept that it monitors for conditions which could make execution of a\nconcurrent set of serializable transactions behave in a manner inconsistent\nwith all possible serial (one at a time) executions of those transactions.\n\n\nin repeatable read, every statement will use the transaction start\ntimestamp, so is it in serializable isolation level?\n\n\nWhen relying on Serializable transactions to prevent anomalies, it is\nimportant that any data read from a permanent user table not be considered\nvalid until the transaction which read it has successfully committed. This\nis true even for read-only transactions ...\n\n\nWhat does the \"not be considered valid\" mean? and if it is a read-only\ntransaction (assume T1), I think it is ok to let other transaction do\nanything with the read set of T1, since it is invisible to T1(use the\ntransaction start time as statement timestamp).\n\n\nThanks\n\nBefore understanding how postgres implements the serializable isolation level (I have see many paper related to it), I have question about how it should be. I mainly read the ideas from https://www.postgresql.org/docs/11/transaction-iso.html. In fact, this isolation level works exactly the same as Repeatable Read except that it monitors for conditions which could make execution of a concurrent set of serializable transactions behave in a manner inconsistent with all possible serial (one at a time) executions of those transactions.  in repeatable read,  every statement will use the transaction start timestamp,  so is it in serializable isolation level? When relying on Serializable transactions to prevent anomalies, it is important that any data read from a permanent user table not be considered valid until the transaction which read it has successfully committed. This is true even for read-only transactions ...What does the \"not be considered valid\" mean?  and if it is a read-only transaction (assume T1),  I think it is ok to let other transaction do anything with the read set of T1, since it is invisible to T1(use the transaction start time as statement timestamp). Thanks", "msg_date": "Tue, 20 Aug 2019 16:47:37 +0800", "msg_from": "Alex <zhihui.fan1213@gmail.com>", "msg_from_op": true, "msg_subject": "Serialization questions" }, { "msg_contents": "On Tue, Aug 20, 2019 at 4:47 PM Alex <zhihui.fan1213@gmail.com> wrote:\n\n> Before understanding how postgres implements the serializable isolation\n> level (I have see many paper related to it), I have question about how it\n> should be.\n>\n>\n> I mainly read the ideas from\n> https://www.postgresql.org/docs/11/transaction-iso.html.\n>\n>\n> In fact, this isolation level works exactly the same as Repeatable Read\n> except that it monitors for conditions which could make execution of a\n> concurrent set of serializable transactions behave in a manner inconsistent\n> with all possible serial (one at a time) executions of those transactions.\n>\n>\n>\n> in repeatable read, every statement will use the transaction start\n> timestamp, so is it in serializable isolation level?\n>\n>\n> When relying on Serializable transactions to prevent anomalies, it is\n> important that any data read from a permanent user table not be considered\n> valid until the transaction which read it has successfully committed. This\n> is true even for read-only transactions ...\n>\n>\n> What does the \"not be considered valid\" mean? and if it is a read-only\n> transaction (assume T1), I think it is ok to let other transaction do\n> anything with the read set of T1, since it is invisible to T1(use the\n> transaction start time as statement timestamp).\n>\n\nfirst issue \"set default_transaction_isolation to 'serializable';\" on the\nboth sessions, then run:\n\nSession 1: begin; select * from t; (2 rows selected);\nSession 2: delete from t; (committed automatically)\nSession 1: commit; (commit successfully).\n\nlooks the reads in session 1 has no impact on the session 2 at all which is\nconflicted with the document\n\n\n> Thanks\n>\n\nOn Tue, Aug 20, 2019 at 4:47 PM Alex <zhihui.fan1213@gmail.com> wrote:Before understanding how postgres implements the serializable isolation level (I have see many paper related to it), I have question about how it should be. I mainly read the ideas from https://www.postgresql.org/docs/11/transaction-iso.html. In fact, this isolation level works exactly the same as Repeatable Read except that it monitors for conditions which could make execution of a concurrent set of serializable transactions behave in a manner inconsistent with all possible serial (one at a time) executions of those transactions.  in repeatable read,  every statement will use the transaction start timestamp,  so is it in serializable isolation level? When relying on Serializable transactions to prevent anomalies, it is important that any data read from a permanent user table not be considered valid until the transaction which read it has successfully committed. This is true even for read-only transactions ...What does the \"not be considered valid\" mean?  and if it is a read-only transaction (assume T1),  I think it is ok to let other transaction do anything with the read set of T1, since it is invisible to T1(use the transaction start time as statement timestamp). first issue \"set default_transaction_isolation to 'serializable';\" on the both sessions,  then run:Session 1:   begin;  select * from t;  (2 rows selected);Session 2:   delete from t;   (committed automatically)Session 1:  commit;  (commit successfully). looks the reads in session 1 has no impact on the session 2 at all which is conflicted with the document   Thanks", "msg_date": "Wed, 21 Aug 2019 09:21:48 +0800", "msg_from": "Alex <zhihui.fan1213@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Serialization questions" }, { "msg_contents": "> Before understanding how postgres implements the serializable isolation\n> level (I have see many paper related to it), I have question about how it\n> should be.\n> \n> \n> I mainly read the ideas from\n> https://www.postgresql.org/docs/11/transaction-iso.html.\n> \n> \n> In fact, this isolation level works exactly the same as Repeatable Read\n> except that it monitors for conditions which could make execution of a\n> concurrent set of serializable transactions behave in a manner inconsistent\n> with all possible serial (one at a time) executions of those transactions.\n> \n> \n> in repeatable read, every statement will use the transaction start\n> timestamp, so is it in serializable isolation level?\n> \n> \n> When relying on Serializable transactions to prevent anomalies, it is\n> important that any data read from a permanent user table not be considered\n> valid until the transaction which read it has successfully committed. This\n> is true even for read-only transactions ...\n> \n> \n> What does the \"not be considered valid\" mean? and if it is a read-only\n> transaction (assume T1), I think it is ok to let other transaction do\n> anything with the read set of T1, since it is invisible to T1(use the\n> transaction start time as statement timestamp).\n\nThere are some test cases and link to the paper explaining read-only\ntransaction anomaly in the source tree.\n\nsrc/test/isolation/specs/read-only-anomaly-2.spec\n\nBest regards,\n--\nTatsuo Ishii\nSRA OSS, Inc. Japan\nEnglish: http://www.sraoss.co.jp/index_en.php\nJapanese:http://www.sraoss.co.jp\n\n\n", "msg_date": "Wed, 21 Aug 2019 10:44:28 +0900 (JST)", "msg_from": "Tatsuo Ishii <ishii@sraoss.co.jp>", "msg_from_op": false, "msg_subject": "Re: Serialization questions" }, { "msg_contents": "On Wed, Aug 21, 2019 at 9:30 AM Alex <zhihui.fan1213@gmail.com> wrote:\n\n>\n> first issue \"set default_transaction_isolation to 'serializable';\" on the\n> both sessions, then run:\n>\n> Session 1: begin; select * from t; (2 rows selected);\n> Session 2: delete from t; (committed automatically)\n> Session 1: commit; (commit successfully).\n>\n> looks the reads in session 1 has no impact on the session 2 at all which\n> is conflicted with the document\n>\n\n\nThis behavior makes sense to me. The effect can be considered as we\n execute the two sessions in a serial order of first session 1 and then\n session 2.\n\nThanks\nRichard\n\nOn Wed, Aug 21, 2019 at 9:30 AM Alex <zhihui.fan1213@gmail.com> wrote:first issue \"set default_transaction_isolation to 'serializable';\" on the both sessions,  then run:Session 1:   begin;  select * from t;  (2 rows selected);Session 2:   delete from t;   (committed automatically)Session 1:  commit;  (commit successfully). looks the reads in session 1 has no impact on the session 2 at all which is conflicted with the document  This behavior makes sense to me. The effect can be considered as we execute the two sessions in a serial order of first session 1 and then session 2.ThanksRichard", "msg_date": "Wed, 21 Aug 2019 10:41:01 +0800", "msg_from": "Richard Guo <riguo@pivotal.io>", "msg_from_op": false, "msg_subject": "Re: Serialization questions" } ]
[ { "msg_contents": "I propose the attached patch to make the new SQL/JSON error code names\nmatch the SQL standard. The existing minor differences don't seem\nnecessary.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Tue, 20 Aug 2019 10:48:47 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Make SQL/JSON error code names match SQL standard" }, { "msg_contents": "út 20. 8. 2019 v 10:49 odesílatel Peter Eisentraut <\npeter.eisentraut@2ndquadrant.com> napsal:\n\n> I propose the attached patch to make the new SQL/JSON error code names\n> match the SQL standard. The existing minor differences don't seem\n> necessary.\n>\n\n+1\n\nPavel\n\n>\n> --\n> Peter Eisentraut http://www.2ndQuadrant.com/\n> PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n>\n\nút 20. 8. 2019 v 10:49 odesílatel Peter Eisentraut <peter.eisentraut@2ndquadrant.com> napsal:I propose the attached patch to make the new SQL/JSON error code names\nmatch the SQL standard.  The existing minor differences don't seem\nnecessary.+1Pavel\n\n-- \nPeter Eisentraut              http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Tue, 20 Aug 2019 12:34:13 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Make SQL/JSON error code names match SQL standard" }, { "msg_contents": "On Tue, Aug 20, 2019 at 11:49 AM Peter Eisentraut\n<peter.eisentraut@2ndquadrant.com> wrote:\n> I propose the attached patch to make the new SQL/JSON error code names\n> match the SQL standard. The existing minor differences don't seem\n> necessary.\n\nThank you for noticing!\n+1 for pushing this\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Tue, 20 Aug 2019 14:48:37 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Make SQL/JSON error code names match SQL standard" }, { "msg_contents": "On 2019-08-20 13:48, Alexander Korotkov wrote:\n> On Tue, Aug 20, 2019 at 11:49 AM Peter Eisentraut\n> <peter.eisentraut@2ndquadrant.com> wrote:\n>> I propose the attached patch to make the new SQL/JSON error code names\n>> match the SQL standard. The existing minor differences don't seem\n>> necessary.\n> \n> Thank you for noticing!\n> +1 for pushing this\n\ndone\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 22 Aug 2019 10:56:19 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: Make SQL/JSON error code names match SQL standard" } ]
[ { "msg_contents": "I noticed that configure is still looking for crypt() and crypt.h.\nIsn't that long obsolete?\n\nIf so, I suggest to remove it with the attached patch.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Tue, 20 Aug 2019 14:29:00 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "configure still looking for crypt()?" }, { "msg_contents": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> I noticed that configure is still looking for crypt() and crypt.h.\n> Isn't that long obsolete?\n> If so, I suggest to remove it with the attached patch.\n\n+1\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 20 Aug 2019 10:07:02 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: configure still looking for crypt()?" }, { "msg_contents": "On 2019-08-20 16:07, Tom Lane wrote:\n> Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n>> I noticed that configure is still looking for crypt() and crypt.h.\n>> Isn't that long obsolete?\n>> If so, I suggest to remove it with the attached patch.\n> \n> +1\n\ndone\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 21 Aug 2019 22:15:47 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: configure still looking for crypt()?" } ]
[ { "msg_contents": "Running the regression tests on mingw32, I get the following diff in\ncircle.out:\n\n@@ -111,8 +111,8 @@\n WHERE (c1.f1 < c2.f1) AND ((c1.f1 <-> c2.f1) > 0)\n ORDER BY distance, area(c1.f1), area(c2.f1);\n five | one | two | distance\n-------+----------------+----------------+------------------\n- | <(3,5),0> | <(1,2),3> | 0.60555127546399\n+------+----------------+----------------+-------------------\n+ | <(3,5),0> | <(1,2),3> | 0.605551275463989\n | <(3,5),0> | <(5,1),3> | 1.47213595499958\n | <(100,200),10> | <(100,1),115> | 74\n | <(100,200),10> | <(1,2),100> | 111.370729772479\n\u001b\nI only get this on master/PG12, but not on PG11, so I suspect that the\nnew floating-point output routines could be the root of the issue.\n\nThis happens only with the 32-bit build (mingw32), but not with a 64-bit\nbuild (mingw64).\n\nAny suggestions on how to analyze this further?\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 20 Aug 2019 14:59:52 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "mingw32 floating point diff" }, { "msg_contents": "On 2019-08-20 14:59, Peter Eisentraut wrote:\n> Running the regression tests on mingw32, I get the following diff in\n> circle.out:\n> \n> @@ -111,8 +111,8 @@\n> WHERE (c1.f1 < c2.f1) AND ((c1.f1 <-> c2.f1) > 0)\n> ORDER BY distance, area(c1.f1), area(c2.f1);\n> five | one | two | distance\n> -------+----------------+----------------+------------------\n> - | <(3,5),0> | <(1,2),3> | 0.60555127546399\n> +------+----------------+----------------+-------------------\n> + | <(3,5),0> | <(1,2),3> | 0.605551275463989\n> | <(3,5),0> | <(5,1),3> | 1.47213595499958\n> | <(100,200),10> | <(100,1),115> | 74\n> | <(100,200),10> | <(1,2),100> | 111.370729772479\n> \u001b\n> I only get this on master/PG12, but not on PG11, so I suspect that the\n> new floating-point output routines could be the root of the issue.\n> \n> This happens only with the 32-bit build (mingw32), but not with a 64-bit\n> build (mingw64).\n\nOK, the problem isn't the new output routines. The result of the\ncomputations is actually different. The test itself is new in PG12.\n\nThe difference in output is due to the mingw32 target using -mfpmath=387\nby default. If you build with -mfpmath=sse -msee, the tests pass again.\n\nDo we care to do anything about this? Pick slightly different test data\nperhaps?\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n\n", "msg_date": "Thu, 22 Aug 2019 14:49:33 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "mingw32 floating point diff" }, { "msg_contents": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> On 2019-08-20 14:59, Peter Eisentraut wrote:\n>> Running the regression tests on mingw32, I get the following diff in\n>> circle.out:\n...\n> OK, the problem isn't the new output routines. The result of the\n> computations is actually different. The test itself is new in PG12.\n> The difference in output is due to the mingw32 target using -mfpmath=387\n> by default. If you build with -mfpmath=sse -msee, the tests pass again.\n\nHm, so presumably we could replicate this on other Intel-oid platforms\nby changing compiler switches? (I haven't tried.)\n\n> Do we care to do anything about this? Pick slightly different test data\n> perhaps?\n\nPicking different test data might be a good \"fix\". Alternatively, we\ncould try to figure out where the discrepancy is arising and adjust\nthe code --- but that might be a lot more work than it's worth.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 22 Aug 2019 09:55:03 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: mingw32 floating point diff" }, { "msg_contents": "I wrote:\n> Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n>> Do we care to do anything about this? Pick slightly different test data\n>> perhaps?\n\n> Picking different test data might be a good \"fix\". Alternatively, we\n> could try to figure out where the discrepancy is arising and adjust\n> the code --- but that might be a lot more work than it's worth.\n\nI poked at this a bit more. I can reproduce the problem by using \n-mfpmath=387 on dromedary's host (fairly old 32-bit macOS); although\nI also get half a dozen *other* failures in the core regression tests,\nmostly around detection of float overflow. So I'm not quite sure that\nthis is comparable. But at any rate, I tracked the core of the problem\nto pg_hypot:\n\n\t/* Determine the hypotenuse */\n\tyx = y / x;\n\tresult = x * sqrt(1.0 + (yx * yx));\n\nWith -mfpmath=387, these calculations are done to more-than-64-bit\nprecision, yielding a different end result --- note in particular\nthat sqrt() is a hardware instruction on this platform, so it's\nnot rounding either.\n\nI experimented with preventing that by using volatile intermediate\nvariables (cf comments in float.c); but it seemed like a mess,\nand it would likely pessimize the code more than we want for other\nplatforms, and it's kind of hard to argue that deliberately sabotaging\nthe more-accurate computation is an improvement.\n\nWhat I suggest doing is reducing extra_float_digits to -1 for this\nspecific test. Changing the contents of circle_tbl seems like it'd have\nmore consequences than we want, in particular there's no guarantee that\nwe'd not hit similar issues in other tests if they're given different\ninputs.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 22 Aug 2019 12:19:06 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: mingw32 floating point diff" }, { "msg_contents": "On 2019-08-22 18:19, Tom Lane wrote:\n> What I suggest doing is reducing extra_float_digits to -1 for this\n> specific test. Changing the contents of circle_tbl seems like it'd have\n> more consequences than we want, in particular there's no guarantee that\n> we'd not hit similar issues in other tests if they're given different\n> inputs.\n\nI agree that reducing the output precision is better than adjusting the\ncode.\n\nThe circle.sql file already has SET extra_float_digits TO 0, and a few\nother files have other settings with different values. Are we content\nto use various numbers until it works in each case, or should we try to\nuse some consistency?\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 23 Aug 2019 08:14:06 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: mingw32 floating point diff" }, { "msg_contents": "\nOn 8/20/19 8:59 AM, Peter Eisentraut wrote:\n> Running the regression tests on mingw32, I get the following diff in\n> circle.out:\n>\n> @@ -111,8 +111,8 @@\n> WHERE (c1.f1 < c2.f1) AND ((c1.f1 <-> c2.f1) > 0)\n> ORDER BY distance, area(c1.f1), area(c2.f1);\n> five | one | two | distance\n> -------+----------------+----------------+------------------\n> - | <(3,5),0> | <(1,2),3> | 0.60555127546399\n> +------+----------------+----------------+-------------------\n> + | <(3,5),0> | <(1,2),3> | 0.605551275463989\n> | <(3,5),0> | <(5,1),3> | 1.47213595499958\n> | <(100,200),10> | <(100,1),115> | 74\n> | <(100,200),10> | <(1,2),100> | 111.370729772479\n> \u001b\n> I only get this on master/PG12, but not on PG11, so I suspect that the\n> new floating-point output routines could be the root of the issue.\n>\n> This happens only with the 32-bit build (mingw32), but not with a 64-bit\n> build (mingw64).\n>\n> Any suggestions on how to analyze this further?\n>\n\n\nI complained about this a year ago:\n<https://postgr.es/m/9f4f22be-f9f1-b350-bc06-521226b87f7a@dunslane.net>\n\n\n+1 for fixing it by any reasonable means.\n\n\ncheers\n\n\nandrew\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Fri, 23 Aug 2019 08:25:01 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: mingw32 floating point diff" }, { "msg_contents": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> The circle.sql file already has SET extra_float_digits TO 0, and a few\n> other files have other settings with different values. Are we content\n> to use various numbers until it works in each case, or should we try to\n> use some consistency?\n\nThe one in rules.sql doesn't count here. Everyplace else seems to be\nusing 0, except for the one in geometry.sql, which seems to be perhaps\nunreasonably conservative. Might be worth researching why it's -3.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 23 Aug 2019 09:50:54 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: mingw32 floating point diff" }, { "msg_contents": "> I poked at this a bit more. I can reproduce the problem by using\n> -mfpmath=387 on dromedary's host (fairly old 32-bit macOS); although\n> I also get half a dozen *other* failures in the core regression tests,\n> mostly around detection of float overflow. So I'm not quite sure that\n> this is comparable. But at any rate, I tracked the core of the problem\n> to pg_hypot:\n\nI couldn't test if it helps, but another solution may be is to rip out\npg_hypot() in favour of the libc implementation. This was discussed\nin detail as part of \"Improve geometric types\" thread.\n\nLast comment about it:\n\nhttps://www.postgresql.org/message-id/9223.1507039405%40sss.pgh.pa.us\n\n\n", "msg_date": "Sat, 24 Aug 2019 14:23:11 +0200", "msg_from": "Emre Hasegeli <emre@hasegeli.com>", "msg_from_op": false, "msg_subject": "Re: mingw32 floating point diff" }, { "msg_contents": "Emre Hasegeli <emre@hasegeli.com> writes:\n> I couldn't test if it helps, but another solution may be is to rip out\n> pg_hypot() in favour of the libc implementation. This was discussed\n> in detail as part of \"Improve geometric types\" thread.\n\nHm ... the problem we're trying to fix here is platform-varying results.\nSurely switching to the libc implementation would make that worse not\nbetter?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 24 Aug 2019 11:18:37 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: mingw32 floating point diff" }, { "msg_contents": "On 2019-08-23 15:50, Tom Lane wrote:\n> Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n>> The circle.sql file already has SET extra_float_digits TO 0, and a few\n>> other files have other settings with different values. Are we content\n>> to use various numbers until it works in each case, or should we try to\n>> use some consistency?\n> \n> The one in rules.sql doesn't count here. Everyplace else seems to be\n> using 0, except for the one in geometry.sql, which seems to be perhaps\n> unreasonably conservative. Might be worth researching why it's -3.\n\nI can confirm that SET extra_float_digits TO -1 in circle.sql fixes the\noriginal complaint.\n\nI don't understand this stuff enough to be able to provide a good source\ncode comment or commit message, so I'd appreciate some help or someone\nelse to proceed with this change.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Sun, 25 Aug 2019 09:02:23 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: mingw32 floating point diff" }, { "msg_contents": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> I can confirm that SET extra_float_digits TO -1 in circle.sql fixes the\n> original complaint.\n\nCool. It did on dromedary, but that doesn't necessarily prove much\nabout other compilers :-(\n\n> I don't understand this stuff enough to be able to provide a good source\n> code comment or commit message, so I'd appreciate some help or someone\n> else to proceed with this change.\n\nSure, I'll take it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 25 Aug 2019 11:22:49 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: mingw32 floating point diff" }, { "msg_contents": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com> writes:\n> On 8/20/19 8:59 AM, Peter Eisentraut wrote:\n>> Running the regression tests on mingw32, I get the following diff in\n>> circle.out:\n>> - | <(3,5),0> | <(1,2),3> | 0.60555127546399\n>> + | <(3,5),0> | <(1,2),3> | 0.605551275463989\n\n> I complained about this a year ago:\n> <https://postgr.es/m/9f4f22be-f9f1-b350-bc06-521226b87f7a@dunslane.net>\n> +1 for fixing it by any reasonable means.\n\nNow that that fix is in, could we get a buildfarm member running on\nsuch a platform? It seems to behave differently from anything else.\n\nI tracked down the residual regression failures on dromedary with\n-mfpmath=387, and found that they occur because check_float8_val\ngets inlined and then its tests for \"isinf(val)\" and \"val == 0.0\"\nare applied to the 80-bit intermediate results not the 64-bit form.\nI find it odd that we apparently don't have the same issues on\nmingw32.\n\nI'm very hesitant to apply a volatile-qualification approach to\neliminate those issues, for fear of pessimizing performance-critical\ncode on more modern platforms. I wonder whether there is a reasonable\nway to tell at compile time if we have a platform with 80-bit math.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 25 Aug 2019 16:23:34 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: mingw32 floating point diff" }, { "msg_contents": "I wrote:\n> I'm very hesitant to apply a volatile-qualification approach to\n> eliminate those issues, for fear of pessimizing performance-critical\n> code on more modern platforms. I wonder whether there is a reasonable\n> way to tell at compile time if we have a platform with 80-bit math.\n\nHmmm ... I find that dromedary's compiler predefines __FLT_EVAL_METHOD__\nas 2 not 0 when -mfpmath=387 is given. This seems to be something\nthat was standardized in C99 (without the double underscores), so\nmaybe we could do something like\n\n#if __FLT_EVAL_METHOD__ > 0 || FLT_EVAL_METHOD > 0\n\nto conditionalize whether we try to force the evaluation width in\ncheck_float8_val and check_float4_val.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 25 Aug 2019 16:49:38 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: mingw32 floating point diff" }, { "msg_contents": "\nOn 8/25/19 4:23 PM, Tom Lane wrote:\n> Andrew Dunstan <andrew.dunstan@2ndquadrant.com> writes:\n>> On 8/20/19 8:59 AM, Peter Eisentraut wrote:\n>>> Running the regression tests on mingw32, I get the following diff in\n>>> circle.out:\n>>> - | <(3,5),0> | <(1,2),3> | 0.60555127546399\n>>> + | <(3,5),0> | <(1,2),3> | 0.605551275463989\n>> I complained about this a year ago:\n>> <https://postgr.es/m/9f4f22be-f9f1-b350-bc06-521226b87f7a@dunslane.net>\n>> +1 for fixing it by any reasonable means.\n> Now that that fix is in, could we get a buildfarm member running on\n> such a platform? It seems to behave differently from anything else.\n>\n\n\nI'm pretty much tapped out for Windows resources, I have one physical\nand one virtual machine which do nothing but run my 6 Windows based animals.\n\n\nI don't know if the community has spare resources available from those\nthat Amazon donate to us. There is already one animal I manage running\nthere, so maybe another would be feasible.\n\n\ncheers\n\n\nandrew\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Mon, 26 Aug 2019 11:13:30 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: mingw32 floating point diff" }, { "msg_contents": "I wrote:\n>> I'm very hesitant to apply a volatile-qualification approach to\n>> eliminate those issues, for fear of pessimizing performance-critical\n>> code on more modern platforms. I wonder whether there is a reasonable\n>> way to tell at compile time if we have a platform with 80-bit math.\n\n> Hmmm ... I find that dromedary's compiler predefines __FLT_EVAL_METHOD__\n> as 2 not 0 when -mfpmath=387 is given. This seems to be something\n> that was standardized in C99 (without the double underscores), so\n> maybe we could do something like\n> #if __FLT_EVAL_METHOD__ > 0 || FLT_EVAL_METHOD > 0\n\nAfter further poking around, it seems that testing FLT_EVAL_METHOD\nshould be sufficient --- <float.h> appears to define that correctly\neven in very old C99 installations.\n\nHowever, I'm losing interest in the problem after finding that I can't\nreproduce it anywhere except on dromedary (with \"-mfpmath=387\" added).\n\nFor instance, I have a 32-bit FreeBSD system with what claims to be\nthe same compiler (gcc 4.2.1), but it passes regression just fine,\nwith or without -mfpmath=387. Earlier and later gcc versions also\ndon't show a problem. I suspect that Apple bollixed something with\nlocal mods to their version of 4.2.1, or possibly they are allowing\ninlining of isinf() in a way that nobody else does.\n\nAlso, using that compiler with \"-mfpmath=387\", I see that every\nsupported PG version back to 9.4 fails regression due to not\ndetecting float8 multiply overflow. So this isn't a problem that\nwe introduced with v12's changes, as I'd first suspected; and it's\nnot a problem that anyone is hitting in the field, or we'd have\nheard complaints.\n\nSo, barring somebody showing that we have an issue on some platform\nthat people actually care about currently, I'm inclined not to do\nanything more here.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 26 Aug 2019 14:11:09 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: mingw32 floating point diff" } ]
[ { "msg_contents": "Here is an initial patch to add the option to use ICU as the global\ncollation provider, a long-requested feature.\n\nTo activate, use something like\n\n initdb --collation-provider=icu --locale=...\n\nA trick here is that since we need to also still set the normal POSIX\nlocales, the --locale value needs to be valid as both a POSIX locale and\na ICU locale. If that doesn't work out, there is also a way to specify\nit separately, e.g.,\n\n initdb --collation-provider=icu --locale=en_US.utf8 --icu-locale=en\n\nThis complexity is unfortunate, but I don't see a way around it right now.\n\nThere are also options for createdb and CREATE DATABASE to do this for a\nparticular database only.\n\nBesides this, the implementation is quite small: When starting up a\ndatabase, we create an ICU collator object, store it in a global\nvariable, and then use it when appropriate. All the ICU code for\ncreating and invoking those collators already exists of course.\n\nFor the version tracking, I use the pg_collation row for the \"default\"\ncollation. Again, this mostly reuses existing code and concepts.\n\nNondeterministic collations are not supported for the global collation,\nbecause then LIKE and regular expressions don't work and that breaks\nsome system views. This needs some separate research.\n\nTo test, run the existing regression tests against a database\ninitialized with ICU. Perhaps some options for pg_regress could\nfacilitate that.\n\nI fear that the Localization chapter in the documentation will need a\nbit of a rewrite after this, because the hitherto separately treated\nconcepts of locale and collation are fusing together. I haven't done\nthat here yet, but that would be the plan for later.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Tue, 20 Aug 2019 16:21:21 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "ICU for global collation" }, { "msg_contents": "Hi!\n\n\n> 20 авг. 2019 г., в 19:21, Peter Eisentraut <peter.eisentraut@2ndquadrant.com> написал(а):\n> \n> Here is an initial patch to add the option to use ICU as the global\n> collation provider, a long-requested feature.\n> \n> To activate, use something like\n> \n> initdb --collation-provider=icu --locale=...\n> \n> A trick here is that since we need to also still set the normal POSIX\n> locales, the --locale value needs to be valid as both a POSIX locale and\n> a ICU locale. If that doesn't work out, there is also a way to specify\n> it separately, e.g.,\n> \n> initdb --collation-provider=icu --locale=en_US.utf8 --icu-locale=en\n\nThanks! This is very awaited feature.\n\nSeems like user cannot change locale for database if icu is already chosen?\n\npostgres=# \\l\n List of databases\n Name | Owner | Encoding | Collate | Ctype | Provider | Access privileges \n-----------+-------+----------+---------+-------+----------+-------------------\n postgres | x4mmm | UTF8 | ru_RU | ru_RU | icu | \n template0 | x4mmm | UTF8 | ru_RU | ru_RU | icu | =c/x4mmm +\n | | | | | | x4mmm=CTc/x4mmm\n template1 | x4mmm | UTF8 | ru_RU | ru_RU | icu | =c/x4mmm +\n | | | | | | x4mmm=CTc/x4mmm\n(3 rows)\n\npostgres=# create database a template template0 collation_provider icu lc_collate 'en_US.utf8';\nCREATE DATABASE\npostgres=# \\c a\n2019-08-21 11:43:40.379 +05 [41509] FATAL: collations with different collate and ctype values are not supported by ICU\nFATAL: collations with different collate and ctype values are not supported by ICU\nPrevious connection kept\n\nAm I missing something?\n\nBTW, psql does not know about collation_provider.\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Wed, 21 Aug 2019 11:56:03 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2019-08-21 08:56, Andrey Borodin wrote:\n> postgres=# create database a template template0 collation_provider icu lc_collate 'en_US.utf8';\n> CREATE DATABASE\n> postgres=# \\c a\n> 2019-08-21 11:43:40.379 +05 [41509] FATAL: collations with different collate and ctype values are not supported by ICU\n> FATAL: collations with different collate and ctype values are not supported by ICU\n\nTry\n\ncreate database a template template0 collation_provider icu locale\n'en_US.utf8';\n\nwhich sets both lc_collate and lc_ctype. But 'en_US.utf8' is not a\nvalid ICU locale name. Perhaps use 'en' or 'en-US'.\n\nI'm making a note that we should prevent creating a database with a\nfaulty locale configuration in the first place instead of failing when\nwe're connecting.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 21 Aug 2019 09:23:50 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "\n\n> 21 авг. 2019 г., в 12:23, Peter Eisentraut <peter.eisentraut@2ndquadrant.com> написал(а):\n> \n> On 2019-08-21 08:56, Andrey Borodin wrote:\n>> postgres=# create database a template template0 collation_provider icu lc_collate 'en_US.utf8';\n>> CREATE DATABASE\n>> postgres=# \\c a\n>> 2019-08-21 11:43:40.379 +05 [41509] FATAL: collations with different collate and ctype values are not supported by ICU\n>> FATAL: collations with different collate and ctype values are not supported by ICU\n> \n> Try\n> \n> create database a template template0 collation_provider icu locale\n> 'en_US.utf8';\n> \n> which sets both lc_collate and lc_ctype. But 'en_US.utf8' is not a\n> valid ICU locale name. Perhaps use 'en' or 'en-US'.\n> \n> I'm making a note that we should prevent creating a database with a\n> faulty locale configuration in the first place instead of failing when\n> we're connecting.\n\nYes, the problem is input with lc_collate is accepted\npostgres=# create database a template template0 collation_provider icu lc_collate 'en_US.utf8';\nCREATE DATABASE\npostgres=# \\c a\n2019-09-11 10:01:00.373 +05 [56878] FATAL: collations with different collate and ctype values are not supported by ICU\nFATAL: collations with different collate and ctype values are not supported by ICU\nPrevious connection kept\npostgres=# create database b template template0 collation_provider icu locale 'en_US.utf8';\nCREATE DATABASE\npostgres=# \\c b\nYou are now connected to database \"b\" as user \"x4mmm\".\n\nI get same output with 'en' or 'en-US'.\n\n\nAlso, cluster initialized --with-icu started on binaries without icu just fine.\nAnd only after some time, I've got that messages \"ERROR: ICU is not supported in this build\".\nIs it expected behavior? Maybe we should refuse to start without icu?\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Wed, 11 Sep 2019 10:24:37 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": " Hi,\n\nWhen trying databases defined with ICU locales, I see that backends\nthat serve such databases seem to have their LC_CTYPE inherited from\nthe environment (as opposed to a per-database fixed value).\n\nThat's a problem for the backend code that depends on libc functions\nthat themselves depend on LC_CTYPE, such as the full text search parser\nand dictionaries.\n\nFor instance, if you start the instance with a C locale\n(LC_ALL=C pg_ctl...) , and tries to use FTS in an ICU UTF-8 database,\nit doesn't work:\n\ntemplate1=# create database \"fr-utf8\" \n template 'template0' encoding UTF8\n locale 'fr'\n collation_provider 'icu';\n\ntemplate1=# \\c fr-utf8\nYou are now connected to database \"fr-utf8\" as user \"daniel\".\n\nfr-utf8=# show lc_ctype;\n lc_ctype \n----------\n fr\n(1 row)\n\nfr-utf8=# select to_tsvector('été');\nERROR:\tinvalid multibyte character for locale\nHINT: The server's LC_CTYPE locale is probably incompatible with the\ndatabase encoding.\n\nIf I peek into the \"real\" LC_CTYPE when connected to this database,\nI can see it's \"C\":\n\nfr-utf8=# create extension plperl;\nCREATE EXTENSION\n\nfr-utf8=# create function lc_ctype() returns text as '$ENV{LC_CTYPE};'\n language plperl;\nCREATE FUNCTION\n\nfr-utf8=# select lc_ctype();\n lc_ctype \n----------\n C\n\n\nBest regards,\n-- \nDaniel Vérité\nPostgreSQL-powered mailer: http://www.manitou-mail.org\nTwitter: @DanielVerite\n\n\n", "msg_date": "Tue, 17 Sep 2019 15:08:36 +0200", "msg_from": "\"Daniel Verite\" <daniel@manitou-mail.org>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hi everyone,\n\nlike the others before me we (the university of Münster) are happy to\nsee this feature as well. Thank you this.\n\nWhen I applied the patch two weeks ago I run into the issue that initdb\ndid not recognize the new parameters (collation-provider and icu-locale)\nbut I guess it was caused by my own stupidity.\n\n> When trying databases defined with ICU locales, I see that backends\n> that serve such databases seem to have their LC_CTYPE inherited from\n> the environment (as opposed to a per-database fixed value).\nI am able to recreate the issue described by Daniel on my machine.\n\nNow it works as expected. I just had to update the patch since commit\n3f6b3be3 had modified two lines which resulted in conflicts. You find\nthe updated patch as attachement to this mail.\n\n\nBest regards,\n\nMarius Timmer\n\n\n\n\n-- \nWestfälische Wilhelms-Universität Münster (WWU)\nZentrum für Informationsverarbeitung (ZIV)\nRöntgenstraße 7-13\nBesucheradresse: Einsteinstraße 60 - Raum 107\n48149 Münster\n+49 251 83 31158\nmarius.timmer@uni-muenster.de\nhttps://www.uni-muenster.de/ZIV", "msg_date": "Tue, 8 Oct 2019 13:15:57 +0200", "msg_from": "Marius Timmer <marius.timmer@uni-muenster.de>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Wed, Oct 9, 2019 at 12:16 AM Marius Timmer\n<marius.timmer@uni-muenster.de> wrote:\n> like the others before me we (the university of Münster) are happy to\n> see this feature as well. Thank you this.\n>\n> When I applied the patch two weeks ago I run into the issue that initdb\n> did not recognize the new parameters (collation-provider and icu-locale)\n> but I guess it was caused by my own stupidity.\n>\n> > When trying databases defined with ICU locales, I see that backends\n> > that serve such databases seem to have their LC_CTYPE inherited from\n> > the environment (as opposed to a per-database fixed value).\n> I am able to recreate the issue described by Daniel on my machine.\n>\n> Now it works as expected. I just had to update the patch since commit\n> 3f6b3be3 had modified two lines which resulted in conflicts. You find\n> the updated patch as attachement to this mail.\n\nI rebased this patch, and tweaked get_collation_action_version() very\nslightly so that you get collation version change detection (of the\nersatz kind provided by commit d5ac14f9) for the default collation\neven when not using ICU. Please see attached.\n\n+struct pg_locale_struct global_locale;\n\nWhy not \"default_locale\"? Where is the terminology \"global\" coming from?\n\n+ Specifies the collation provider for the database.\n\n\"for the database's default collation\"?", "msg_date": "Thu, 17 Oct 2019 15:52:00 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Thu, Oct 17, 2019 at 3:52 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> I rebased this patch, and tweaked get_collation_action_version() very\n> slightly so that you get collation version change detection (of the\n> ersatz kind provided by commit d5ac14f9) for the default collation\n> even when not using ICU. Please see attached.\n\nIt should also remove the sentence I recently added to\nalter_collation.sgml to say that the default collation doesn't have\nversion tracking. Rereading that section, it's also clear that the\nquery introduced with:\n\n \"The following query can be used to identify all collations in the current\n database that need to be refreshed and the objects that depend on them:\"\n\n… is wrong with this patch applied. The right query is quite hard to\ncome up with, since we don't explicitly track dependencies on the\ndefault collation. That is, there is no pg_depend entry pointing from\nthe index to the collation when you write CREATE INDEX ON t(x) for a\ntext column using the default collation, but there is one when you\nwrite CREATE INDEX ON t(x COLLATE \"fr_FR\"), or when you write CREATE\nINDEX ON t(x) for a text column that was explicitly defined to use\nCOLLATE \"fr_FR\". One solution is that we could start tracking those\ndependencies explicitly too.\n\nA preexisting problem with that query is that it doesn't report\ntransitive dependencies. An index on t(x) of a user defined type\ndefined with CREATE TYPE my_type AS (x text COLLATE \"fr_FR\") doesn't\nresult in a pg_depend row from index to collation, so the query fails\nto report that as an index needing to be rebuilt. You could fix that\nwith a sprinkle of recursive magic, but you'd need a different kind of\nmagic to deal with transitive dependencies on the default collation\nunless we start listing such dependencies explicitly. In that\nexample, my_type would need to depend on collation \"default\". You\ncan't just do some kind of search for transitive dependencies on type\n\"text\", because they aren't tracked either.\n\nIn my longer term proposal to track per-dependency versions, either by\nadding refobjversion to pg_depend or by creating another\npg_depend-like catalog, you'd almost certainly need to add an explicit\nrecord for dependencies on the default collation.\n\n\n", "msg_date": "Fri, 18 Oct 2019 10:43:06 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2019-09-17 15:08, Daniel Verite wrote:\n> When trying databases defined with ICU locales, I see that backends\n> that serve such databases seem to have their LC_CTYPE inherited from\n> the environment (as opposed to a per-database fixed value).\n\n> fr-utf8=# select to_tsvector('ᅵtᅵ');\n> ERROR:\tinvalid multibyte character for locale\n> HINT: The server's LC_CTYPE locale is probably incompatible with the\n> database encoding.\n\nI looked into this problem. The way to address this would be adding \nproper collation support to the text search subsystem. See the TODO \nmarkers in src/backend/tsearch/ts_locale.c for starting points. These \nAPIs spread out to a lot of places, so it will take some time to finish. \n In the meantime, I'm pausing this thread and will set the CF entry as RwF.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 31 Oct 2019 08:22:44 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "\tPeter Eisentraut wrote:\n\n> I looked into this problem. The way to address this would be adding \n> proper collation support to the text search subsystem. See the TODO \n> markers in src/backend/tsearch/ts_locale.c for starting points. These \n> APIs spread out to a lot of places, so it will take some time to finish. \n> In the meantime, I'm pausing this thread and will set the CF entry as RwF.\n\nEven if the FTS code is improved in that matter, any extension code\nwith libc functions depending on LC_CTYPE is still going to be\npotentially problematic. In particular when it happens to be set\nto a different encoding than the database.\n\nCouldn't we simply invent per-database GUC options, as in\nALTER DATABASE myicudb SET libc_lc_ctype TO 'value';\nALTER DATABASE myicudb SET libc_lc_collate TO 'value';\n\nwhere libc_lc_ctype/libc_lc_collate would specifically set\nthe values in the LC_CTYPE and LC_COLLATE environment vars\nof any backend serving the corresponding database\"?\n\n\nBest regards,\n-- \nDaniel Vérité\nPostgreSQL-powered mailer: http://www.manitou-mail.org\nTwitter: @DanielVerite\n\n\n", "msg_date": "Fri, 01 Nov 2019 19:18:13 +0100", "msg_from": "\"Daniel Verite\" <daniel@manitou-mail.org>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2019-11-01 19:18, Daniel Verite wrote:\n> Even if the FTS code is improved in that matter, any extension code\n> with libc functions depending on LC_CTYPE is still going to be\n> potentially problematic. In particular when it happens to be set\n> to a different encoding than the database.\n\nI think the answer here is that extension code must not do that, at \nleast in ways that potentially interact with other parts of the \n(collation-aware) database system. For example, libc and ICU might have \ndifferent opinions about what is a letter, because of different versions \nof Unicode data in use. That would then affect tokenization etc. in \ntext search and elsewhere. That's why things like isalpha have to go \nthough ICU instead, if that is the collation provider in a particular \ncontext.\n\n> Couldn't we simply invent per-database GUC options, as in\n> ALTER DATABASE myicudb SET libc_lc_ctype TO 'value';\n> ALTER DATABASE myicudb SET libc_lc_collate TO 'value';\n> \n> where libc_lc_ctype/libc_lc_collate would specifically set\n> the values in the LC_CTYPE and LC_COLLATE environment vars\n> of any backend serving the corresponding database\"?\n\nWe could do that as a transition measure to support extensions like you \nmention above. But our own internal code should not have to rely on that.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 6 Nov 2019 11:09:57 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "There were a few inquiries about this topic recently, so I dug up the \nold thread and patch. What we got stuck on last time was that we can't \njust swap out all locale support in a database for ICU. We still need \nto set the usual locale environment, otherwise some things that are not \nICU aware will break or degrade. I had initially anticipated fixing \nthat by converting everything that uses libc locales to ICU. But that \nturned out to be tedious and ultimately not very useful as far as the \nuser-facing result is concerned, so I gave up.\n\nSo this is a different approach: If you choose ICU as the default locale \nfor a database, you still need to specify lc_ctype and lc_collate \nsettings, as before. Unlike in the previous patch, where the ICU \ncollation name was written in datcollate, there is now a third column \n(daticucoll), so we can store all three values. This fixes the \ndescribed problem. Other than that, once you get all the initial \nsettings right, it basically just works: The places that have ICU \nsupport now will use a database-wide ICU collation if appropriate, the \nplaces that don't have ICU support continue to use the global libc \nlocale settings.\n\nI changed the datcollate, datctype, and the new daticucoll fields to \ntype text (from name). That way, the daticucoll field can be set to \nnull if it's not applicable. Also, the limit of 63 characters can \nactually be a problem if you want to use some combination of the options \nthat ICU locales offer. And for less extreme uses, having \nvariable-length fields will save some storage, since typical locale \nnames are much shorter.\n\nFor the same reasons and to keep things consistent, I also changed the \nanalogous pg_collation fields like that. This also removes some weird \ncode that has to check that colcollate and colctype have to be the same \nfor ICU, so it's overall cleaner.", "msg_date": "Thu, 30 Dec 2021 13:07:21 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hi,\n\nOn Thu, Dec 30, 2021 at 01:07:21PM +0100, Peter Eisentraut wrote:\n> \n> So this is a different approach: If you choose ICU as the default locale for\n> a database, you still need to specify lc_ctype and lc_collate settings, as\n> before. Unlike in the previous patch, where the ICU collation name was\n> written in datcollate, there is now a third column (daticucoll), so we can\n> store all three values. This fixes the described problem. Other than that,\n> once you get all the initial settings right, it basically just works: The\n> places that have ICU support now will use a database-wide ICU collation if\n> appropriate, the places that don't have ICU support continue to use the\n> global libc locale settings.\n\nThat looks sensible to me.\n\n> @@ -2774,6 +2776,7 @@ dumpDatabase(Archive *fout)\n> \t\tappendPQExpBuffer(dbQry, \"SELECT tableoid, oid, datname, \"\n> \t\t\t\t\t\t \"(%s datdba) AS dba, \"\n> \t\t\t\t\t\t \"pg_encoding_to_char(encoding) AS encoding, \"\n> +\t\t\t\t\t\t \"datcollprovider, \"\n\nThis needs to be in a new pg 15+ branch, not in the pg 9.3+.\n\n> -\tif (!lc_collate_is_c(collid) && collid != DEFAULT_COLLATION_OID)\n> -\t\tmylocale = pg_newlocale_from_collation(collid);\n> +\tif (!lc_collate_is_c(collid))\n> +\t{\n> +\t\tif (collid != DEFAULT_COLLATION_OID)\n> +\t\t\tmylocale = pg_newlocale_from_collation(collid);\n> +\t\telse if (default_locale.provider == COLLPROVIDER_ICU)\n> +\t\t\tmylocale = &default_locale;\n> +\t}\n\nThere are really a lot of places with this new code. Maybe it could be some\nnew function/macro to wrap that for the normal case (e.g. not formatting.c)?\n\n\n", "msg_date": "Tue, 4 Jan 2022 10:21:04 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 04.01.22 03:21, Julien Rouhaud wrote:\n>> @@ -2774,6 +2776,7 @@ dumpDatabase(Archive *fout)\n>> \t\tappendPQExpBuffer(dbQry, \"SELECT tableoid, oid, datname, \"\n>> \t\t\t\t\t\t \"(%s datdba) AS dba, \"\n>> \t\t\t\t\t\t \"pg_encoding_to_char(encoding) AS encoding, \"\n>> +\t\t\t\t\t\t \"datcollprovider, \"\n> \n> This needs to be in a new pg 15+ branch, not in the pg 9.3+.\n\nok\n\n>> -\tif (!lc_collate_is_c(collid) && collid != DEFAULT_COLLATION_OID)\n>> -\t\tmylocale = pg_newlocale_from_collation(collid);\n>> +\tif (!lc_collate_is_c(collid))\n>> +\t{\n>> +\t\tif (collid != DEFAULT_COLLATION_OID)\n>> +\t\t\tmylocale = pg_newlocale_from_collation(collid);\n>> +\t\telse if (default_locale.provider == COLLPROVIDER_ICU)\n>> +\t\t\tmylocale = &default_locale;\n>> +\t}\n> \n> There are really a lot of places with this new code. Maybe it could be some\n> new function/macro to wrap that for the normal case (e.g. not formatting.c)?\n\nRight, we could just put this into pg_newlocale_from_collation(), but \nthe comment there says\n\n * In fact, they shouldn't call this function at all when they are dealing\n * with the default locale. That can save quite a bit in hotspots.\n\nI don't know how to assess that.\n\nWe could pack this into a macro or inline function if we are concerned \nabout this.\n\n\n", "msg_date": "Tue, 4 Jan 2022 17:03:10 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Tue, Jan 04, 2022 at 05:03:10PM +0100, Peter Eisentraut wrote:\n> On 04.01.22 03:21, Julien Rouhaud wrote:\n> \n> > > -\tif (!lc_collate_is_c(collid) && collid != DEFAULT_COLLATION_OID)\n> > > -\t\tmylocale = pg_newlocale_from_collation(collid);\n> > > +\tif (!lc_collate_is_c(collid))\n> > > +\t{\n> > > +\t\tif (collid != DEFAULT_COLLATION_OID)\n> > > +\t\t\tmylocale = pg_newlocale_from_collation(collid);\n> > > +\t\telse if (default_locale.provider == COLLPROVIDER_ICU)\n> > > +\t\t\tmylocale = &default_locale;\n> > > +\t}\n> > \n> > There are really a lot of places with this new code. Maybe it could be some\n> > new function/macro to wrap that for the normal case (e.g. not formatting.c)?\n> \n> Right, we could just put this into pg_newlocale_from_collation(), but the\n> comment there says\n> \n> * In fact, they shouldn't call this function at all when they are dealing\n> * with the default locale. That can save quite a bit in hotspots.\n> \n> I don't know how to assess that.\n> \n> We could pack this into a macro or inline function if we are concerned about\n> this.\n\nYes that was my idea, just have a new function (inline function or a macro\nthen since pg_newlocale_from_collation() clearly warns about performance\nconcerns) that have the whole\nis-not-c-collation-and-is-default-collation-or-icu-collation logic and calls\npg_newlocale_from_collation() only when needed.\n\n\n", "msg_date": "Thu, 6 Jan 2022 11:35:14 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "\r\nI didn't notice anything version-specific about the patch. Would any modifications be needed to backport it to pg13 and pg14?\r\n\r\nAfter this patch goes in, the big next thing would be to support nondeterministic collations for LIKE, ILIKE and pattern matching operators in general. Is anyone interested in working on that?\r\n\r\nOn 1/5/22, 10:36 PM, \"Julien Rouhaud\" <rjuju123@gmail.com> wrote:\r\n\r\n CAUTION: This email originated from outside of the organization. Do not click links or open attachments unless you can confirm the sender and know the content is safe.\r\n\r\n\r\n\r\n On Tue, Jan 04, 2022 at 05:03:10PM +0100, Peter Eisentraut wrote:\r\n > On 04.01.22 03:21, Julien Rouhaud wrote:\r\n >\r\n > > > - if (!lc_collate_is_c(collid) && collid != DEFAULT_COLLATION_OID)\r\n > > > - mylocale = pg_newlocale_from_collation(collid);\r\n > > > + if (!lc_collate_is_c(collid))\r\n > > > + {\r\n > > > + if (collid != DEFAULT_COLLATION_OID)\r\n > > > + mylocale = pg_newlocale_from_collation(collid);\r\n > > > + else if (default_locale.provider == COLLPROVIDER_ICU)\r\n > > > + mylocale = &default_locale;\r\n > > > + }\r\n > >\r\n > > There are really a lot of places with this new code. Maybe it could be some\r\n > > new function/macro to wrap that for the normal case (e.g. not formatting.c)?\r\n >\r\n > Right, we could just put this into pg_newlocale_from_collation(), but the\r\n > comment there says\r\n >\r\n > * In fact, they shouldn't call this function at all when they are dealing\r\n > * with the default locale. That can save quite a bit in hotspots.\r\n >\r\n > I don't know how to assess that.\r\n >\r\n > We could pack this into a macro or inline function if we are concerned about\r\n > this.\r\n\r\n Yes that was my idea, just have a new function (inline function or a macro\r\n then since pg_newlocale_from_collation() clearly warns about performance\r\n concerns) that have the whole\r\n is-not-c-collation-and-is-default-collation-or-icu-collation logic and calls\r\n pg_newlocale_from_collation() only when needed.\r\n\r\n\r\n\r\n", "msg_date": "Thu, 6 Jan 2022 13:55:55 +0000", "msg_from": "\"Finnerty, Jim\" <jfinnert@amazon.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Thu, Jan 06, 2022 at 01:55:55PM +0000, Finnerty, Jim wrote:\n> \n> I didn't notice anything version-specific about the patch. Would any\n> modifications be needed to backport it to pg13 and pg14?\n\nThis is a new feature so it can't be backported. The changes aren't big and\nmostly touches places that didn't change in a long time so I don't think that\nit would take much effort if you wanted to backport it on your own forks.\n\n> After this patch goes in, the big next thing would be to support\n> nondeterministic collations for LIKE, ILIKE and pattern matching operators in\n> general. Is anyone interested in working on that?\n\nAs far as I know you're the last person that seemed to be working on that topic\nback in March :)\n\n\n", "msg_date": "Thu, 6 Jan 2022 22:45:43 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hi,\n\nI looked a bit more in this patch and I have some additional remarks.\n\nOn Thu, Dec 30, 2021 at 01:07:21PM +0100, Peter Eisentraut wrote:\n> \n> So this is a different approach: If you choose ICU as the default locale for\n> a database, you still need to specify lc_ctype and lc_collate settings, as\n> before. Unlike in the previous patch, where the ICU collation name was\n> written in datcollate, there is now a third column (daticucoll), so we can\n> store all three values. This fixes the described problem. Other than that,\n> once you get all the initial settings right, it basically just works: The\n> places that have ICU support now will use a database-wide ICU collation if\n> appropriate, the places that don't have ICU support continue to use the\n> global libc locale settings.\n\nSo just to confirm a database can now have 2 different *default* collations: a\nlibc-based one for everything that doesn't work with ICU and a ICU-based (if\nspecified) for everything else, and the ICU-based is optional, so if not\nprovided everything works as before, using the libc based default collation.\n\nAs I mentioned I think this approach is sensible. However, should we document\nwhat are the things that are not ICU-aware?\n\n> I changed the datcollate, datctype, and the new daticucoll fields to type\n> text (from name). That way, the daticucoll field can be set to null if it's\n> not applicable. Also, the limit of 63 characters can actually be a problem\n> if you want to use some combination of the options that ICU locales offer.\n> And for less extreme uses, having variable-length fields will save some\n> storage, since typical locale names are much shorter.\n\nI understand the need to have daticucoll as text, however it's not clear to me\nwhy this has to be changed for datcollate and datctype? IIUC those will only\never contain libc-based collation and are still mandatory?\n> \n> For the same reasons and to keep things consistent, I also changed the\n> analogous pg_collation fields like that.\n\nThe respective fields in pg_collation are now nullable, so the changes there\nsounds ok.\n\nDigging a bit more in the patch here are some things that looks problematic.\n\n- pg_upgrade\n\nIt checks (in check_locale_and_encoding()) the compatibility for each database,\nand it looks like the daticucoll field should also be verified. Other than\nthat I don't think there is anything else needed for the pg_upgrade part as\neverything else should be handled by pg_dump (I didn't look at the changes yet\ngiven the below problems).\n\n- CREATE DATABASE\n\nThere's a new COLLATION_PROVIDER option, but the overall behavior seems quite\nunintuitive. As far as I can see the idea is to use LOCALE for the ICU default\ncollation, but as it's providing a default for the other values it's quite\nannoying. For instance:\n\n=# CREATE DATABASE db COLLATION_PROVIDER icu LOCALE 'fr-x-icu' LC_COLLATE 'en_GB.UTF-8';;\nERROR: 42809: invalid locale name: \"fr-x-icu\"\nLOCATION: createdb, dbcommands.c:397\n\nLooking at the code it's actually complaining about LC_CTYPE. If you want a\ndatabase with an ICU default collation the lc_collate and lc_ctype should\ninherit what's in the template database and not what was provided in the\nLOCALE I think. You could still probably overload them in some scenario, but\nwithout a list of what isn't ICU-aware I can't really be sure of how often one\nmight have to do it.\n\nNow, if I specify everything as needed it looks like it's missing some checks\non the ICU default collation when not using template0:\n\n=# CREATE DATABASE db COLLATION_PROVIDER icu LOCALE 'en-x-icu' LC_COLLATE 'en_GB.UTF-8' LC_CTYPE 'en_GB.UTF-8';;\nCREATE DATABASE\n\n=# SELECT datname, datcollate, datctype, daticucoll FROM pg_database ;\n datname | datcollate | datctype | daticucoll\n-----------+-------------+-------------+------------\n postgres | en_GB.UTF-8 | en_GB.UTF-8 | fr-x-icu\n db | en_GB.UTF-8 | en_GB.UTF-8 | en-x-icu\n template1 | en_GB.UTF-8 | en_GB.UTF-8 | fr-x-icu\n template0 | en_GB.UTF-8 | en_GB.UTF-8 | fr-x-icu\n(4 rows)\n\nUnless I'm missing something the same concerns about collation incompatibility\nwith objects in the source database should also apply for the ICU collation?\n\nWhile at it, I'm not exactly sure of what the COLLATION_PROVIDER is supposed to\nmean, as the same commands but with a libc provider is accepted and has\nthe exact same result:\n\n=# CREATE DATABASE db2 COLLATION_PROVIDER libc LOCALE 'en-x-icu' LC_COLLATE 'en_GB.UTF-8' LC_CTYPE 'en_GB.UTF-8';;\nCREATE DATABASE\n\n=# SELECT datname, datcollate, datctype, daticucoll FROM pg_database ;\n datname | datcollate | datctype | daticucoll\n-----------+-------------+-------------+------------\n postgres | en_GB.UTF-8 | en_GB.UTF-8 | fr-x-icu\n db | en_GB.UTF-8 | en_GB.UTF-8 | en-x-icu\n template1 | en_GB.UTF-8 | en_GB.UTF-8 | fr-x-icu\n template0 | en_GB.UTF-8 | en_GB.UTF-8 | fr-x-icu\n db2 | en_GB.UTF-8 | en_GB.UTF-8 | en-x-icu\n(5 rows)\n\nShouldn't db2 have a NULL daticucoll, and if so also complain about\nincompatibility for it?\n\n- initdb\n\nI don't think that initdb --collation-provider icu should be allowed without\n--icu-locale, same for --collation-provider libc *with* --icu-locale.\n\nWhen trying that, I can also see that the NULL handling for daticucoll is\nbroken in the BKI:\n\n$ initdb -k --collation-provider icu\n[...]\nSuccess. You can now start the database server using:\n\n=# select datname, datcollate, datctype, daticucoll from pg_database ;\n datname | datcollate | datctype | daticucoll\n-----------+-------------+-------------+------------\n postgres | en_GB.UTF-8 | en_GB.UTF-8 | en_GB\n template1 | en_GB.UTF-8 | en_GB.UTF-8 | en_GB\n template0 | en_GB.UTF-8 | en_GB.UTF-8 | en_GB\n(3 rows)\n\n\nThere's a fallback on my LANG/LC_* env settings, but I don't think it can ever\nbe correct given the different naming convention in ICU (at least the s/_/-/).\n\nAnd\n\n$ initdb -k --collation-provider libc --icu-locale test\n[...]\nSuccess. You can now start the database server using:\n\n=# select datname, datcollate, datctype, daticucoll from pg_database ;\n datname | datcollate | datctype | daticucoll\n-----------+-------------+-------------+------------\n postgres | en_GB.UTF-8 | en_GB.UTF-8 | _null_\n template1 | en_GB.UTF-8 | en_GB.UTF-8 | _null_\n template0 | en_GB.UTF-8 | en_GB.UTF-8 | _null_\n(3 rows)\n\n\n", "msg_date": "Fri, 7 Jan 2022 17:03:29 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 04.01.22 17:03, Peter Eisentraut wrote:\n>> There are really a lot of places with this new code.  Maybe it could \n>> be some\n>> new function/macro to wrap that for the normal case (e.g. not \n>> formatting.c)?\n> \n> Right, we could just put this into pg_newlocale_from_collation(), but \n> the comment there says\n> \n>  * In fact, they shouldn't call this function at all when they are dealing\n>  * with the default locale.  That can save quite a bit in hotspots.\n> \n> I don't know how to assess that.\n\nI tested this a bit. I used the following setup:\n\ncreate table t1 (a text);\ninsert into t1 select md5(generate_series(1, 10000000)::text);\nselect count(*) from t1 where a > '';\n\nAnd then I changed in varstr_cmp():\n\n if (collid != DEFAULT_COLLATION_OID)\n mylocale = pg_newlocale_from_collation(collid);\n\nto just\n\n mylocale = pg_newlocale_from_collation(collid);\n\nI find that the \\timing results are indistinguishable. (I used locale \n\"en_US.UTF-8\" and made sure that that code path is actually hit.)\n\nDoes anyone have other insights?\n\n\n", "msg_date": "Fri, 7 Jan 2022 15:25:28 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "\tJulien Rouhaud wrote:\n\n> If you want a database with an ICU default collation the lc_collate\n> and lc_ctype should inherit what's in the template database and not\n> what was provided in the LOCALE I think. You could still probably\n> overload them in some scenario, but without a list of what isn't\n> ICU-aware I can't really be sure of how often one might have to do\n> it.\n\nI guess we'd need that when creating a database with a different\nencoding than the template databases, at least.\n\nAbout what's not ICU-aware, I believe the most significant part in\ncore is the Full Text Search parser.\nIt doesn't care about sorting strings, but it relies on the functions\nfrom POSIX <ctype.h>, which depend on LC_CTYPE\n(it looks however that this could be improved by following\nwhat has been done in backend/regex/regc_pg_locale.c, which has\ncomparable needs and calls ICU functions when applicable).\n\nAlso, any extension is potentially concerned. Surely many\nextensions call functions from ctype.h assuming that\nthe current value of LC_CTYPE works with the data they handle.\n\n\nBest regards,\n-- \nDaniel Vérité\nPostgreSQL-powered mailer: https://www.manitou-mail.org\nTwitter: @DanielVerite\n\n\n", "msg_date": "Fri, 07 Jan 2022 18:19:09 +0100", "msg_from": "\"Daniel Verite\" <daniel@manitou-mail.org>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Fri, Jan 07, 2022 at 03:25:28PM +0100, Peter Eisentraut wrote:\n> \n> I tested this a bit. I used the following setup:\n> \n> create table t1 (a text);\n> insert into t1 select md5(generate_series(1, 10000000)::text);\n> select count(*) from t1 where a > '';\n> \n> And then I changed in varstr_cmp():\n> \n> if (collid != DEFAULT_COLLATION_OID)\n> mylocale = pg_newlocale_from_collation(collid);\n> \n> to just\n> \n> mylocale = pg_newlocale_from_collation(collid);\n> \n> I find that the \\timing results are indistinguishable. (I used locale\n> \"en_US.UTF-8\" and made sure that that code path is actually hit.)\n> \n> Does anyone have other insights?\n\nLooking at the git history, you added this comment in 414c5a2ea65.\n\nAfter a bit a digging in the lists, I found that you introduced it to fix a\nreported 13% slowdown in varstr_cmp():\nhttps://www.postgresql.org/message-id/20110129075253.GA18784%40tornado.leadboat.com\nhttps://www.postgresql.org/message-id/1296748408.6442.1.camel%40vanquo.pezone.net\n\n\n", "msg_date": "Mon, 10 Jan 2022 11:25:08 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Mon, Jan 10, 2022 at 11:25:08AM +0800, Julien Rouhaud wrote:\n> On Fri, Jan 07, 2022 at 03:25:28PM +0100, Peter Eisentraut wrote:\n> > \n> > I tested this a bit. I used the following setup:\n> > \n> > create table t1 (a text);\n> > insert into t1 select md5(generate_series(1, 10000000)::text);\n> > select count(*) from t1 where a > '';\n> > \n> > And then I changed in varstr_cmp():\n> > \n> > if (collid != DEFAULT_COLLATION_OID)\n> > mylocale = pg_newlocale_from_collation(collid);\n> > \n> > to just\n> > \n> > mylocale = pg_newlocale_from_collation(collid);\n> > \n> > I find that the \\timing results are indistinguishable. (I used locale\n> > \"en_US.UTF-8\" and made sure that that code path is actually hit.)\n> > \n> > Does anyone have other insights?\n> \n> Looking at the git history, you added this comment in 414c5a2ea65.\n> \n> After a bit a digging in the lists, I found that you introduced it to fix a\n> reported 13% slowdown in varstr_cmp():\n> https://www.postgresql.org/message-id/20110129075253.GA18784%40tornado.leadboat.com\n> https://www.postgresql.org/message-id/1296748408.6442.1.camel%40vanquo.pezone.net\n\nSo I tried to run Noah's benchmark to see if I could reproduce the slowdown.\nUnfortunately the results I'm getting don't really make sense as removing the\noptimisation brings a 15% speedup, and with a few more runs I can see that I\nhave about 25% noise, so there isn't much I can do to help.\n\n\n", "msg_date": "Mon, 10 Jan 2022 14:00:27 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "\tPeter Eisentraut wrote:\n\n> Unlike in the previous patch, where the ICU \n> collation name was written in datcollate, there is now a third column \n> (daticucoll), so we can store all three values.\n\nI think some users would want their db-wide ICU collation to be\ncase/accent-insensitive. Postgres users are trained to expect\ncase-sensitive comparisons, but some apps initially made for\ne.g. MySQL or MS-SQL that use such collations natively would be easier\nto port to Postgres.\nIIRC, that was the context for some questions where people were\nenquiring about db-wide ICU collations.\n\nWith the current patch, it's not possible, AFAICS, because the user\ncan't tell that the collation is non-deterministic. Presumably this\nwould require another option to CREATE DATABASE and another\ncolumn to store that bit of information.\n\nThe \"daticucol\" column also suggests that we don't expect to add\nother collation providers in the future. Maybe a pair of columns like\n(datcollprovider, datcolllocale) would be more future-proof,\nor a (datcollprovider, datcolllocale, datcollisdeterministic)\ntriplet if non-deterministic collations are allowed.\n\nAlso, pg_collation has \"collversion\" to detect a mismatch between\nthe ICU runtime and existing indexes. I don't see that field\nfor the db-wide ICU collation, so maybe we currently miss the capability\nto detect the mismatch for the db-wide collation?\n\nThe lack of these fields overall suggest the idea that when CREATE\nDATABASE is called with a global ICU collation, what if it somehow\ninserted the collation into pg_collation in the new database?\nThen pg_database would just store the collation oid and no other\ncollation-related field would need to be added into it, now\nor in the future.\n\n\nBest regards,\n-- \nDaniel Vérité\nPostgreSQL-powered mailer: https://www.manitou-mail.org\nTwitter: @DanielVerite\n\n\n", "msg_date": "Mon, 10 Jan 2022 12:49:07 +0100", "msg_from": "\"Daniel Verite\" <daniel@manitou-mail.org>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Mon, Jan 10, 2022 at 12:49:07PM +0100, Daniel Verite wrote:\n> \n> The \"daticucol\" column also suggests that we don't expect to add\n> other collation providers in the future. Maybe a pair of columns like\n> (datcollprovider, datcolllocale) would be more future-proof,\n> or a (datcollprovider, datcolllocale, datcollisdeterministic)\n> triplet if non-deterministic collations are allowed.\n\nI'm not sure about the non-deterministic default collation given the current\nrestrictions with it, but the extra column seems like a good idea. It would\nrequire a bit more thinking, as we would need a second collation column in\npg_database for any default provider that's not libc.\n\n> Also, pg_collation has \"collversion\" to detect a mismatch between\n> the ICU runtime and existing indexes. I don't see that field\n> for the db-wide ICU collation, so maybe we currently miss the capability\n> to detect the mismatch for the db-wide collation?\n\nI don't think that storing a version there will really help. There's no\nguarantee that any object has been created with the version of the collation\nthat was installed when the database was created. And we would still need\nto store a version with each underlying object anyway, as rebuilding all broken\ndependencies can last for a long time, including a server restart.\n\n> The lack of these fields overall suggest the idea that when CREATE\n> DATABASE is called with a global ICU collation, what if it somehow\n> inserted the collation into pg_collation in the new database?\n> Then pg_database would just store the collation oid and no other\n> collation-related field would need to be added into it, now\n> or in the future.\n\nI don't think it would be doable given the single-database-per-backend\nrestriction.\n\n\n", "msg_date": "Mon, 10 Jan 2022 20:56:56 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "\tJulien Rouhaud wrote:\n\n> > The lack of these fields overall suggest the idea that when CREATE\n> > DATABASE is called with a global ICU collation, what if it somehow\n> > inserted the collation into pg_collation in the new database?\n> > Then pg_database would just store the collation oid and no other\n> > collation-related field would need to be added into it, now\n> > or in the future.\n> \n> I don't think it would be doable given the single-database-per-backend\n> restriction.\n\nBy that I understand that CREATE DATABASE is limited to copying a template\ndatabase and then not write anything into it beyond that, as it's\nnot even connected to it.\nI guess there's still the possibility of requiring that the ICU db-wide\ncollation of the new database does exist in the template database,\nand then the CREATE DATABASE would refer to that collation instead of\nan independent locale string.\n\n\nBest regards,\n-- \nDaniel Vérité\nPostgreSQL-powered mailer: https://www.manitou-mail.org\nTwitter: @DanielVerite\n\n\n", "msg_date": "Mon, 10 Jan 2022 15:45:47 +0100", "msg_from": "\"Daniel Verite\" <daniel@manitou-mail.org>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Mon, Jan 10, 2022 at 03:45:47PM +0100, Daniel Verite wrote:\n> \n> By that I understand that CREATE DATABASE is limited to copying a template\n> database and then not write anything into it beyond that, as it's\n> not even connected to it.\n\nYes.\n\n> I guess there's still the possibility of requiring that the ICU db-wide\n> collation of the new database does exist in the template database,\n> and then the CREATE DATABASE would refer to that collation instead of\n> an independent locale string.\n\nThat could work. However if having the collation in the template database a\nstrict requirement the something should also be done for initdb, and it will\nprobably be a bigger problem.\n\n\n", "msg_date": "Mon, 10 Jan 2022 23:14:31 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "\nOn 10.01.22 07:00, Julien Rouhaud wrote:\n>>> And then I changed in varstr_cmp():\n>>>\n>>> if (collid != DEFAULT_COLLATION_OID)\n>>> mylocale = pg_newlocale_from_collation(collid);\n>>>\n>>> to just\n>>>\n>>> mylocale = pg_newlocale_from_collation(collid);\n>>>\n>>> I find that the \\timing results are indistinguishable. (I used locale\n>>> \"en_US.UTF-8\" and made sure that that code path is actually hit.)\n>>>\n>>> Does anyone have other insights?\n>>\n>> Looking at the git history, you added this comment in 414c5a2ea65.\n>>\n>> After a bit a digging in the lists, I found that you introduced it to fix a\n>> reported 13% slowdown in varstr_cmp():\n>> https://www.postgresql.org/message-id/20110129075253.GA18784%40tornado.leadboat.com\n>> https://www.postgresql.org/message-id/1296748408.6442.1.camel%40vanquo.pezone.net\n> \n> So I tried to run Noah's benchmark to see if I could reproduce the slowdown.\n> Unfortunately the results I'm getting don't really make sense as removing the\n> optimisation brings a 15% speedup, and with a few more runs I can see that I\n> have about 25% noise, so there isn't much I can do to help.\n\nHeh, I had that same experience, it actually got faster without the \noptimization, but then got lost in the noise on further testing.\n\nLooking back at those discussions, I don't think those old test results \nare relevant anymore. In the patch that was being tested there, \npg_newlocale_from_collation(), did not contain\n\n if (collid == DEFAULT_COLLATION_OID)\n return (pg_locale_t) 0;\n\nso the default collation actually went through most or all of the \nfunction and did a lot of work. That would understandably be quite \nslow. But just calling a function and returning immediately should not \nbe a problem. Otherwise, the call to check_collation_set() in \nvarstr_cmp() and elsewhere would be just as bad.\n\nSo, unless there are concerns, I'm going to see about making a patch to \ncall pg_newlocale_from_collation() even with the default collation. \nThat would make the actual feature patch quite a bit smaller, since we \nwon't have to patch every call site of pg_newlocale_from_collation().\n\n\n", "msg_date": "Tue, 11 Jan 2022 10:10:25 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Tue, Jan 11, 2022 at 10:10:25AM +0100, Peter Eisentraut wrote:\n> \n> On 10.01.22 07:00, Julien Rouhaud wrote:\n> > \n> > So I tried to run Noah's benchmark to see if I could reproduce the slowdown.\n> > Unfortunately the results I'm getting don't really make sense as removing the\n> > optimisation brings a 15% speedup, and with a few more runs I can see that I\n> > have about 25% noise, so there isn't much I can do to help.\n> \n> Heh, I had that same experience, it actually got faster without the\n> optimization, but then got lost in the noise on further testing.\n\nAh, so it's not just my machine :)\n\n> Looking back at those discussions, I don't think those old test results are\n> relevant anymore. In the patch that was being tested there,\n> pg_newlocale_from_collation(), did not contain\n> \n> if (collid == DEFAULT_COLLATION_OID)\n> return (pg_locale_t) 0;\n> \n> so the default collation actually went through most or all of the function\n> and did a lot of work. That would understandably be quite slow. But just\n> calling a function and returning immediately should not be a problem.\n> Otherwise, the call to check_collation_set() in varstr_cmp() and elsewhere\n> would be just as bad.\n\nI didn't noticed that. That definitely explain why the performance concern\nisn't valid anymore.\n\n> So, unless there are concerns, I'm going to see about making a patch to call\n> pg_newlocale_from_collation() even with the default collation. That would\n> make the actual feature patch quite a bit smaller, since we won't have to\n> patch every call site of pg_newlocale_from_collation().\n\n+1 for me!\n\n\n", "msg_date": "Tue, 11 Jan 2022 19:08:52 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "\nOn 07.01.22 10:03, Julien Rouhaud wrote:\n>> I changed the datcollate, datctype, and the new daticucoll fields to type\n>> text (from name). That way, the daticucoll field can be set to null if it's\n>> not applicable. Also, the limit of 63 characters can actually be a problem\n>> if you want to use some combination of the options that ICU locales offer.\n>> And for less extreme uses, having variable-length fields will save some\n>> storage, since typical locale names are much shorter.\n> \n> I understand the need to have daticucoll as text, however it's not clear to me\n> why this has to be changed for datcollate and datctype? IIUC those will only\n> ever contain libc-based collation and are still mandatory?\n\nRight. I just did this for consistency. It would be strange otherwise \nto have some fields as name and some as text. Arguably, using \"name\" \nhere was wrong to begin with, since they are not really object names. \nMaybe there used to be a reason to avoid variable-length fields in \npg_database, but there isn't one now AFAICT.\n\n> - pg_upgrade\n> \n> It checks (in check_locale_and_encoding()) the compatibility for each database,\n> and it looks like the daticucoll field should also be verified. Other than\n> that I don't think there is anything else needed for the pg_upgrade part as\n> everything else should be handled by pg_dump (I didn't look at the changes yet\n> given the below problems).\n\nOk, I have added this and will include it in my next patch submission.\n\n> - CREATE DATABASE\n\n> - initdb\n\nOk, some work is needed to make these interfaces behave sensibly in \nvarious combinations. I will look into that.\n\n\n", "msg_date": "Tue, 11 Jan 2022 12:10:14 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 10.01.22 12:49, Daniel Verite wrote:\n> With the current patch, it's not possible, AFAICS, because the user\n> can't tell that the collation is non-deterministic. Presumably this\n> would require another option to CREATE DATABASE and another\n> column to store that bit of information.\n\nAdding this would be easy, but since pattern matching currently does not \nsupport nondeterministic collations, if you make a global collation \nnondeterministic, a lot of system views, psql, pg_dump queries etc. \nwould break, so it's not practical. I view this is an orthogonal \nproject. Once we can support this without breaking system views etc., \nthen it's easy to enable with a new column in pg_database.\n\n> The \"daticucol\" column also suggests that we don't expect to add\n> other collation providers in the future. Maybe a pair of columns like\n> (datcollprovider, datcolllocale) would be more future-proof,\n> or a (datcollprovider, datcolllocale, datcollisdeterministic)\n> triplet if non-deterministic collations are allowed.\n\nI don't expect many new collation providers. So I don't think an \nEAV-like storage would be helpful. The other problem is that we don't \nknow what we need. For example, the libc provider needs both a collate \nand a ctype value, so that wouldn't fit into that scheme nicely.\n\n> Also, pg_collation has \"collversion\" to detect a mismatch between\n> the ICU runtime and existing indexes. I don't see that field\n> for the db-wide ICU collation, so maybe we currently miss the capability\n> to detect the mismatch for the db-wide collation?\n\nYeah, I think I need to add a datcollversion field and the associated \nchecks.\n\n\n", "msg_date": "Tue, 11 Jan 2022 12:18:58 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "\tJulien Rouhaud wrote:\n\n> > I guess there's still the possibility of requiring that the ICU db-wide\n> > collation of the new database does exist in the template database,\n> > and then the CREATE DATABASE would refer to that collation instead of\n> > an independent locale string.\n> \n> That could work. However if having the collation in the template database a\n> strict requirement the something should also be done for initdb, and it will\n> probably be a bigger problem.\n\nIf CREATE DATABASE referred to a collation in the template db,\neither that collation already exists, or the user would have to add it\nto the template db with CREATE COLLATION.\ninitdb already populates the template databases with a full set of\nICU collations through pg_import_system_collations().\nI don't quite see what change you're seeing that would be needed in\ninitdb.\n\n\nBest regards,\n-- \nDaniel Vérité\nPostgreSQL-powered mailer: https://www.manitou-mail.org\nTwitter: @DanielVerite\n\n\n", "msg_date": "Tue, 11 Jan 2022 12:36:46 +0100", "msg_from": "\"Daniel Verite\" <daniel@manitou-mail.org>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Tue, Jan 11, 2022 at 12:36:46PM +0100, Daniel Verite wrote:\n> \n> If CREATE DATABASE referred to a collation in the template db,\n> either that collation already exists, or the user would have to add it\n> to the template db with CREATE COLLATION.\n> initdb already populates the template databases with a full set of\n> ICU collations through pg_import_system_collations().\n> I don't quite see what change you're seeing that would be needed in\n> initdb.\n\nYes, there are already the system collation imported. But you still need to\nmake sure that that collation does exist in the template database, and it's\nstill impossible to connect to that database to check when processing the\nCREATE DATABASE. Also, if the wanted collation wasn't imported by\npg_import_system_collations() and isn't the server's default collation, then\nthe user would have to allow connection on the template0 database and create\nthe wanted collation there. It doesn't seem like something that should be\nrecommended for a reasonably standard use case.\n\n\n", "msg_date": "Tue, 11 Jan 2022 19:47:00 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 11.01.22 12:08, Julien Rouhaud wrote:\n>> So, unless there are concerns, I'm going to see about making a patch to call\n>> pg_newlocale_from_collation() even with the default collation. That would\n>> make the actual feature patch quite a bit smaller, since we won't have to\n>> patch every call site of pg_newlocale_from_collation().\n> +1 for me!\n\nHere is that patch.\n\nIf this is applied, then in my estimation all these hunks will \ncompletely disappear from the global ICU patch. So this would be a \nsignificant win.", "msg_date": "Thu, 13 Jan 2022 09:39:42 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Re: \r\n>> After this patch goes in, the big next thing would be to support\r\n>> nondeterministic collations for LIKE, ILIKE and pattern matching operators in\r\n>> general. Is anyone interested in working on that?\r\n\r\n> As far as I know you're the last person that seemed to be working on that topic\r\n> back in March :)\r\n\r\nI have a solution for LIKE and ILIKE for case-insensitive, accent-sensitive ICU collations and the UTF8 server encoding, but didn't attempt to address the general case until ICU collations were supported at the database and cluster levels. I may have another look at that after this patch goes in.\r\n\r\n\r\n", "msg_date": "Mon, 17 Jan 2022 17:30:45 +0000", "msg_from": "\"Finnerty, Jim\" <jfinnert@amazon.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": " On 10.01.22 12:49, Daniel Verite wrote:\r\n\r\n> I think some users would want their db-wide ICU collation to be\r\n> case/accent-insensitive. \r\n...\r\n> IIRC, that was the context for some questions where people were\r\n> enquiring about db-wide ICU collations.\r\n\r\n+1. There is the DEFAULT_COLLATION_OID, which is the cluster-level default collation, a.k.a. the \"global collation\", as distinct from the \"db-wide\" database-level default collation, which controls the default type of the collatable types within that database.\r\n\r\n> With the current patch, it's not possible, AFAICS, because the user\r\n> can't tell that the collation is non-deterministic. Presumably this\r\n> would require another option to CREATE DATABASE and another\r\n> column to store that bit of information.\r\n\r\nOn 1/11/22, 6:24 AM, \"Peter Eisentraut\" <peter.eisentraut@enterprisedb.com> wrote:\r\n \r\n> Adding this would be easy, but since pattern matching currently does not\r\n> support nondeterministic collations, if you make a global collation\r\n> nondeterministic, a lot of system views, psql, pg_dump queries etc.\r\n> would break, so it's not practical. I view this is an orthogonal\r\n> project. Once we can support this without breaking system views etc.,\r\n> then it's easy to enable with a new column in pg_database.\r\n\r\nSo this patch only enables the default cluster collation (DEFAULT_COLLATION_OID) to be a deterministic ICU collation, but doesn't extend the metadata in a way that would enable database collations to be ICU collations?\r\n\r\nWaiting for the pattern matching problem to be solved in general before creating the metadata to support ICU collations everywhere will make it more difficult for members of the community to help solve the pattern matching problem. \r\n\r\nWhat additional metadata changes would be required to enable an ICU collation to be specified at either the cluster-level or the database-level, even if new checks need to be added to disallow a nondeterministic collation to be specified at the cluster level for now?\r\n\r\n\r\n", "msg_date": "Mon, 17 Jan 2022 19:07:38 +0000", "msg_from": "\"Finnerty, Jim\" <jfinnert@amazon.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hi,\n\nOn Mon, Jan 17, 2022 at 07:07:38PM +0000, Finnerty, Jim wrote:\n> On 10.01.22 12:49, Daniel Verite wrote:\n> \n> > I think some users would want their db-wide ICU collation to be\n> > case/accent-insensitive. \n> ...\n> > IIRC, that was the context for some questions where people were\n> > enquiring about db-wide ICU collations.\n> \n> +1. There is the DEFAULT_COLLATION_OID, which is the cluster-level default\n> collation, a.k.a. the \"global collation\", as distinct from the \"db-wide\"\n> database-level default collation, which controls the default type of the\n> collatable types within that database.\n\nThere's no cluster-level default collation, and DEFAULT_COLLATION_OID is always\ndatabase-level (and template1 having a specific default collation). The\ntemplate0 database is there to be able to support different databases with\ndifferent default collations, among other things.\n\nSo this patchset would allow per-database default ICU collation, although not\nnon-deterministic ones.\n\n\n", "msg_date": "Tue, 18 Jan 2022 11:47:13 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hi,\n\nOn Thu, Jan 13, 2022 at 09:39:42AM +0100, Peter Eisentraut wrote:\n> On 11.01.22 12:08, Julien Rouhaud wrote:\n> > > So, unless there are concerns, I'm going to see about making a patch to call\n> > > pg_newlocale_from_collation() even with the default collation. That would\n> > > make the actual feature patch quite a bit smaller, since we won't have to\n> > > patch every call site of pg_newlocale_from_collation().\n> > +1 for me!\n> \n> Here is that patch.\n\nThe patch is quite straightforward so I don't have much to say, it all looks\ngood and passes all regression tests.\n\n> If this is applied, then in my estimation all these hunks will completely\n> disappear from the global ICU patch. So this would be a significant win.\n\nAgreed, the patch will be quite smaller and also easier to review. Are you\nplanning to apply it on its own or add it to the default ICU patchset? Given\nthe possible backpatch conflicts it can bring I'm not sure it's worthy enough\nto apply on its own.\n\n\n", "msg_date": "Tue, 18 Jan 2022 12:02:46 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 18.01.22 05:02, Julien Rouhaud wrote:\n>> If this is applied, then in my estimation all these hunks will completely\n>> disappear from the global ICU patch. So this would be a significant win.\n> Agreed, the patch will be quite smaller and also easier to review. Are you\n> planning to apply it on its own or add it to the default ICU patchset?\n\nMy plan is to apply this patch in the next few days.\n\n\n", "msg_date": "Tue, 18 Jan 2022 13:54:50 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 18.01.22 13:54, Peter Eisentraut wrote:\n> On 18.01.22 05:02, Julien Rouhaud wrote:\n>>> If this is applied, then in my estimation all these hunks will \n>>> completely\n>>> disappear from the global ICU patch.  So this would be a significant \n>>> win.\n>> Agreed, the patch will be quite smaller and also easier to review. \n>> Are you\n>> planning to apply it on its own or add it to the default ICU patchset?\n> \n> My plan is to apply this patch in the next few days.\n\nThis patch has been committed.\n\nHere is a second preparation patch: Change collate and ctype fields to \ntype text.\n\nI think this is useful by itself because it allows longer locale names. \nICU locale names with several options appended can be longer than 63 \nbytes. This case is probably broken right now. Also, it saves space in \nthe typical case, since most locale names are not anywhere near 63 bytes.", "msg_date": "Fri, 21 Jan 2022 10:44:24 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hi,\n\nOn Fri, Jan 21, 2022 at 10:44:24AM +0100, Peter Eisentraut wrote:\n> \n> Here is a second preparation patch: Change collate and ctype fields to type\n> text.\n> \n> I think this is useful by itself because it allows longer locale names. ICU\n> locale names with several options appended can be longer than 63 bytes.\n> This case is probably broken right now. Also, it saves space in the typical\n> case, since most locale names are not anywhere near 63 bytes.\n\nI totally agree.\n\n> From 1c46bf3138ad42074971aa3130142236de7e63f7 Mon Sep 17 00:00:00 2001\n> From: Peter Eisentraut <peter@eisentraut.org>\n> Date: Fri, 21 Jan 2022 10:01:25 +0100\n> Subject: [PATCH] Change collate and ctype fields to type text\n\n+\t\t\tcollversionstr = TextDatumGetCString(datum);\n+\n \t\t\tactual_versionstr = get_collation_actual_version(collform->collprovider, collcollate);\n \t\t\tif (!actual_versionstr)\n \t\t\t{\n@@ -1606,7 +1616,6 @@ pg_newlocale_from_collation(Oid collid)\n \t\t\t\t\t\t(errmsg(\"collation \\\"%s\\\" has no actual version, but a version was specified\",\n \t\t\t\t\t\t\t\tNameStr(collform->collname))));\n \t\t\t}\n-\t\t\tcollversionstr = TextDatumGetCString(collversion);\n\n\nIs that change intended? There isn't any usage of the collversionstr before\nthe possible error when actual_versionstr is missing.\n\nApart from that the patch looks good to me, all tests pass and no issue with\nbuilding the doc either.\n\n\n", "msg_date": "Fri, 21 Jan 2022 21:51:19 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 21.01.22 14:51, Julien Rouhaud wrote:\n>> From 1c46bf3138ad42074971aa3130142236de7e63f7 Mon Sep 17 00:00:00 2001\n>> From: Peter Eisentraut <peter@eisentraut.org>\n>> Date: Fri, 21 Jan 2022 10:01:25 +0100\n>> Subject: [PATCH] Change collate and ctype fields to type text\n> \n> +\t\t\tcollversionstr = TextDatumGetCString(datum);\n> +\n> \t\t\tactual_versionstr = get_collation_actual_version(collform->collprovider, collcollate);\n> \t\t\tif (!actual_versionstr)\n> \t\t\t{\n> @@ -1606,7 +1616,6 @@ pg_newlocale_from_collation(Oid collid)\n> \t\t\t\t\t\t(errmsg(\"collation \\\"%s\\\" has no actual version, but a version was specified\",\n> \t\t\t\t\t\t\t\tNameStr(collform->collname))));\n> \t\t\t}\n> -\t\t\tcollversionstr = TextDatumGetCString(collversion);\n> \n> \n> Is that change intended? There isn't any usage of the collversionstr before\n> the possible error when actual_versionstr is missing.\n\nI wanted to move it closer to the SysCacheGetAttr() where the \"datum\" \nvalue is obtained. It seemed weird to get the datum, then do other \nthings, then decode the datum.\n\n\n", "msg_date": "Fri, 21 Jan 2022 15:24:02 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Fri, Jan 21, 2022 at 03:24:02PM +0100, Peter Eisentraut wrote:\n> On 21.01.22 14:51, Julien Rouhaud wrote:\n> > Is that change intended? There isn't any usage of the collversionstr before\n> > the possible error when actual_versionstr is missing.\n> \n> I wanted to move it closer to the SysCacheGetAttr() where the \"datum\" value\n> is obtained. It seemed weird to get the datum, then do other things, then\n> decode the datum.\n\nOh ok. It won't make much difference performance-wise, so no objection.\n\n\n", "msg_date": "Sat, 22 Jan 2022 00:13:31 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 21.01.22 17:13, Julien Rouhaud wrote:\n> On Fri, Jan 21, 2022 at 03:24:02PM +0100, Peter Eisentraut wrote:\n>> On 21.01.22 14:51, Julien Rouhaud wrote:\n>>> Is that change intended? There isn't any usage of the collversionstr before\n>>> the possible error when actual_versionstr is missing.\n>>\n>> I wanted to move it closer to the SysCacheGetAttr() where the \"datum\" value\n>> is obtained. It seemed weird to get the datum, then do other things, then\n>> decode the datum.\n> \n> Oh ok. It won't make much difference performance-wise, so no objection.\n\nI have committed this and will provide follow-up patches in the next few \ndays.\n\n\n", "msg_date": "Thu, 27 Jan 2022 09:10:46 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 27.01.22 09:10, Peter Eisentraut wrote:\n> On 21.01.22 17:13, Julien Rouhaud wrote:\n>> On Fri, Jan 21, 2022 at 03:24:02PM +0100, Peter Eisentraut wrote:\n>>> On 21.01.22 14:51, Julien Rouhaud wrote:\n>>>> Is that change intended?  There isn't any usage of the \n>>>> collversionstr before\n>>>> the possible error when actual_versionstr is missing.\n>>>\n>>> I wanted to move it closer to the SysCacheGetAttr() where the \"datum\" \n>>> value\n>>> is obtained.  It seemed weird to get the datum, then do other things, \n>>> then\n>>> decode the datum.\n>>\n>> Oh ok.  It won't make much difference performance-wise, so no objection.\n> \n> I have committed this and will provide follow-up patches in the next few \n> days.\n\nHere is the main patch rebased on the various changes that have been \ncommitted in the meantime. There is still some work to be done on the \nuser interfaces of initdb, createdb, etc.\n\nI have split out the database-level collation version tracking into a \nseparate patch [0]. I think we should get that one in first and then \nrefresh this one.\n\n[0]: \nhttps://www.postgresql.org/message-id/flat/f0ff3190-29a3-5b39-a179-fa32eee57db6%40enterprisedb.com", "msg_date": "Wed, 2 Feb 2022 14:01:23 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 02.02.22 14:01, Peter Eisentraut wrote:\n> Here is the main patch rebased on the various changes that have been \n> committed in the meantime.  There is still some work to be done on the \n> user interfaces of initdb, createdb, etc.\n> \n> I have split out the database-level collation version tracking into a \n> separate patch [0].  I think we should get that one in first and then \n> refresh this one.\n\nAll that preliminary work has been completed, so here is a new patch.\n\nThere isn't actually much left here now except all the new DDL and \ncommand-line options to set this up and documentation for those. I have \ngiven all that another review and I hope it's more intuitive now, but I \nguess there will be other opinions.\n\nI have changed the terminology a bit to match ICU better. It's now \ncalled \"ICU locale ID\" and \"locale provider\" (instead of \"collation\"). \nIt might actually cover things that are not strictly collations (such as \nthe isalpha stuff in text search, maybe, in the future).\n\nOne thing that is left that bothers me is that the invocations of \nget_collation_actual_version() have all gotten quite complicated. I'm \nthinking about ways to refactor that, but I haven't got a great idea yet.", "msg_date": "Wed, 16 Feb 2022 15:25:40 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hi,\n\nOn Wed, Feb 16, 2022 at 03:25:40PM +0100, Peter Eisentraut wrote:\n>\n> All that preliminary work has been completed, so here is a new patch.\n>\n> There isn't actually much left here now except all the new DDL and\n> command-line options to set this up and documentation for those. I have\n> given all that another review and I hope it's more intuitive now, but I\n> guess there will be other opinions.\n\nSorry it took me a bit of time to come back to this patch.\n\nTL;DR it works as expected. I just have a few comments, mostly on the doc.\n\nI say it works because I did manually check, as far as I can see there isn't\nany test that ensures it.\n\nI'm using this naive scenario:\n\nDROP DATABASE IF EXISTS dbicu;\nCREATE DATABASE dbicu LOCALE_PROVIDER icu LOCALE 'en_US' ICU_LOCALE 'en-u-kf-upper' template 'template0';\n\\c dbicu\nCREATE COLLATION upperfirst (provider = icu, locale = 'en-u-kf-upper');\nCREATE TABLE icu(def text, en text COLLATE \"en_US\", upfirst text COLLATE upperfirst);\nINSERT INTO icu VALUES ('a', 'a', 'a'), ('b','b','b'), ('A','A','A'), ('B','B','B');\nSELECT def AS def FROM icu ORDER BY def;\nSELECT def AS en FROM icu ORDER BY en;\nSELECT def AS upfirst FROM icu ORDER BY upfirst;\nSELECT def AS upfirst_explicit FROM icu ORDER BY en COLLATE upperfirst;\nSELECT def AS en_x_explicit FROM icu ORDER BY def COLLATE \"en-x-icu\";\n\nMaybe there should be some test along those lines included in the patch?\n\n> I have changed the terminology a bit to match ICU better. It's now called\n> \"ICU locale ID\" and \"locale provider\" (instead of \"collation\"). It might\n> actually cover things that are not strictly collations (such as the isalpha\n> stuff in text search, maybe, in the future).\n\nI'm not sure that's actually such an improvement as-is. Simply saying \"ICU\nlocale ID\" is, at least for me, somewhat ambiguous as I don't see any place in\nour docs where it's clearly defined. I'm afraid that users might confuse it\nwith the OID of a pg_collation line, or even a collation name (like en-x-icu),\nespecially since there's no simple way to know if what you used means what you\nthought it meant.\n\nAlso, it's not even used consistently in the patch. I can see e.g. \"ICU\nlocale\" or \"ICU locale setting\" being used:\n\n+ <varlistentry>\n+ <term><replaceable class=\"parameter\">icu_locale</replaceable></term>\n+ <listitem>\n+ <para>\n+ Specifies the ICU locale if the ICU locale provider is used. If\n+ this is not specified, the value from the <literal>LOCALE</literal>\n+ option is used.\n+ </para>\n+ </listitem>\n+ </varlistentry>\n\n+ <term><option>--icu-locale=<replaceable class=\"parameter\">locale</replaceable></option></term>\n+ <listitem>\n+ <para>\n+ Specifies the ICU locale setting to be used in this database, if the\n+ ICU locale provider is selected.\n+ </para>\n\nMaybe we could point to the ICU documentation for a clear notion of what a\nlocale ID is, and/or use their own short definition [1]:\n\n> The locale object in ICU is an identifier that specifies a particular locale\n> and has fields for language, country, and an optional code to specify further\n> variants or subdivisions. These fields also can be represented as a string\n> with the fields separated by an underscore.\n\nIt seems critical to be crystal clear about what should be specified there.\n\nI spent some time looking at the ICU api trying to figure out if using a\nposix locale name (e.g. en_US) was actually compatible with an ICU locale name.\nIt seems that ICU accept any of 'en-us', 'en-US', 'en_us' or 'en_US' as the\nsame locale, but I might be wrong. I also didn't find a way to figure out how\nto ask ICU if the locale identifier passed is complete garbage or not. One\nsure thing is that the system collation we import are of the form 'en-us', so\nit seems weird to have this form in pg_collation and by default another form in\npg_database.\n\nAll in all I'm a bit worried of having the icu_locale optional. Note that this\nis inconsistent with createdb(), as there's at least one code path where the\nicu_locale is not optional:\n\n+ if (dblocprovider == COLLPROVIDER_ICU)\n+ {\n+ /*\n+ * This would happen if template0 uses the libc provider but the new\n+ * database uses icu.\n+ */\n+ if (!dbiculocale)\n+ ereport(ERROR,\n+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n+ errmsg(\"ICU locale must be specified\")));\n+ }\n\n>\n> One thing that is left that bothers me is that the invocations of\n> get_collation_actual_version() have all gotten quite complicated. I'm\n> thinking about ways to refactor that, but I haven't got a great idea yet.\n\nIndeed, and I don't have a great idea either. Maybe\nget_collation_actual_version_extended that would accept both strings?\n\n\nIn CREATE DATABASE manual:\n\n+ Specifies the provider to use for the default collation in this\n+ database. Possible values are:\n+ <literal>icu</literal>,<indexterm><primary>ICU</primary></indexterm>\n+ <literal>libc</literal>. <literal>libc</literal> is the default. The\n+ available choices depend on the operating system and build options.\n\nThat's actually not true as pg_strcasecmp is used in createdb():\n\n+ if (pg_strcasecmp(locproviderstr, \"icu\") == 0)\n+ dblocprovider = COLLPROVIDER_ICU;\n+ else if (pg_strcasecmp(locproviderstr, \"libc\") == 0)\n+ dblocprovider = COLLPROVIDER_LIBC;\n+ else\n+ ereport(ERROR,\n+ (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),\n+ errmsg(\"unrecognized locale provider: %s\",\n+ locproviderstr)));\n\nBy extension that's the same for createdb, but createdb manual doesn't\nexplicitly mention that case is important so I guess that's ok.\n\n\n- To alter the default collation order or character set classes, use the\n- <option>--lc-collate</option> and <option>--lc-ctype</option> options.\n- Collation orders other than <literal>C</literal> or <literal>POSIX</literal> also have\n- a performance penalty. For these reasons it is important to choose the\n- right locale when running <command>initdb</command>.\n+ To choose a different locale for the cluster, use the option\n+ <option>--locale</option>. There are also individual options\n+ <option>--lc-*</option> (see below) to set values for the individual locale\n+ categories. Note that inconsistent settings for different locale\n+ categories can give nonsensical results, so this should be used with care.\n\nUnless I'm missing something you entirely removed the warninng about the\nperformance penalty when using non C/POSIX locale?\n\n+ To chose the specific ICU locale ID to apply, use the option\n+ <option>--icu-locale</option>. The ICU locale ID defaults to\n+ <option>--locale</option> or the environment, as above (with some name\n+ mangling applied to make the locale naming appropriate for ICU). Note that\n+ for implementation reasons and to support legacy code,\n+ <command>initdb</command> will still select and initialize libc locale\n+ settings when the ICU locale provider is used.\n\ninitdb has some specific processing to transform the default libc locale to\nsomething more appropriate, but as far as I can see creatdb / CREATE DATABASE\naren't doing that. It seems inconsistent, and IMHO another reason why\ndefaulting to the libc locale looks like a bad idea.\n\nWhile on that topic, the doc should probably mention that default ICU\ncollations can only be deterministic.\n\n@@ -168,18 +175,6 @@ DefineCollation(ParseState *pstate, List *names, List *parameters, bool if_not_e\n errmsg(\"collation \\\"default\\\" cannot be copied\")));\n }\n\n- if (localeEl)\n- {\n- collcollate = defGetString(localeEl);\n- collctype = defGetString(localeEl);\n- }\n[...]\n\nI tried to read the function and quickly got confused about whether possible\nproblematic conditions could be reached or not and had protection or not. I\nthink that DefineCollation is becoming more and more unreadable, with a mix of\nfromEl, !fromEl and either. Maybe it would be a good time to refactor the code\na bit and have have something like\n\nif (fromEl)\n{\n // initialize all specific things\n}\nelse\n{\n // initialize all specific things\n}\n\n// handle defaults and sanity checks\n\nWhat do you think?\n\nAlso unrelated, but how about raising a warning about possibly hiding\ncorruption if you use CREATE COLLATION ... VERSION or CREATE DATABASE ...\nCOLLATION_VERSION if !IsBinaryUpgrade()?\n\nin AlterCollation(), pg_collation_actual_version(), AlterDatabaseRefreshColl()\nand pg_database_collation_actual_version():\n\n- datum = SysCacheGetAttr(COLLOID, tup, Anum_pg_collation_collcollate, &isnull);\n- Assert(!isnull);\n- newversion = get_collation_actual_version(collForm->collprovider, TextDatumGetCString(datum));\n+ datum = SysCacheGetAttr(COLLOID, tup, collForm->collprovider == COLLPROVIDER_ICU ? Anum_pg_collation_colliculocale : Anum_pg_collation_collcollate, &isnull);\n+ if (!isnull)\n+ newversion = get_collation_actual_version(collForm->collprovider, TextDatumGetCString(datum));\n+ else\n+ newversion = NULL;\n\nThe columns are now nullable, but can you actually end up with a null locale\nname in the expected field without manual DML on the catalog, corruption or\nsimilar? I think it should be a plain error explaining the inconsistency\nrather then silently assuming there's no version. Note that at least\npg_newlocale_from_collation() asserts that the specific libc/icu field it's\ninterested in isn't null.\n\n+ else if (strcmp(defel->defname, \"icu_locale\") == 0)\n+ {\n+ if (diculocale)\n+ errorConflictingDefElem(defel, pstate);\n+ diculocale = defel;\n+ }\n+ else if (strcmp(defel->defname, \"locale_provider\") == 0)\n+ {\n+ if (dlocprovider)\n+ ereport(ERROR,\n+ (errcode(ERRCODE_SYNTAX_ERROR),\n+ errmsg(\"conflicting or redundant options\"),\n+ parser_errposition(pstate, defel->location)));\n+ dlocprovider = defel;\n+ }\n\nWhy not using errorConflictingDefElem for locale_provider?\n\nin createdb():\n\n+ if (dblocprovider == COLLPROVIDER_ICU)\n+ {\n+ /*\n+ * This would happen if template0 uses the libc provider but the new\n+ * database uses icu.\n+ */\n+ if (!dbiculocale)\n+ ereport(ERROR,\n+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n+ errmsg(\"ICU locale must be specified\")));\n+ }\n+\n+ if (dblocprovider == COLLPROVIDER_ICU)\n+ {\n+#ifdef USE_ICU\n[...]\n\nSeems like a refactoring leftover, no need for two blocks. Also, I think it\nwould be better to first error out if there's no support for ICU rather than\ncomplaining about a possibly missing locale that wouldn't be accepted anyway.\n\n+void\n+make_icu_collator(const char *iculocstr,\n+ struct pg_locale_struct *resultp)\n+{\n+#ifdef USE_ICU\n+[...]\n+ /* We will leak this string if we get an error below :-( */\n+ resultp->info.icu.locale = MemoryContextStrdup(TopMemoryContext, iculocstr);\n+ resultp->info.icu.ucol = collator;\n+#else /* not USE_ICU */\n+ /* could get here if a collation was created by a build with ICU */\n+ ereport(ERROR,\n+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n+ errmsg(\"ICU is not supported in this build\"), \\\n+ errhint(\"You need to rebuild PostgreSQL using %s.\", \"--with-icu\")));\n+#endif /* not USE_ICU */\n+}\n\nThe comment about the leak possibility needs some tweaking since it's been\nextracted from a larger function.\n\nNot material for this patch, but:\n@@ -1475,7 +1524,12 @@ pg_newlocale_from_collation(Oid collid)\n Assert(OidIsValid(collid));\n\n if (collid == DEFAULT_COLLATION_OID)\n- return (pg_locale_t) 0;\n+ {\n+ if (default_locale.provider == COLLPROVIDER_ICU)\n+ return &default_locale;\n+ else\n+ return (pg_locale_t) 0;\n+ }\n\nI'm wondering if we could now always return &default_locale and avoid having to\ncheck if the function returned something in all callers, since CheckMyDatabase\nnow initialize it.\n\n@@ -2184,6 +2195,50 @@ setlocales(void)\n check_locale_name(LC_CTYPE, lc_messages, &canonname);\n lc_messages = canonname;\n #endif\n+\n+ if (locale_provider == COLLPROVIDER_ICU)\n+ {\n+ if (!icu_locale && locale)\n+ icu_locale = locale;\n+\n+ /*\n+ * If ICU is selected but no ICU locale has been given, take the\n[...]\n+ /*\n+ * Check ICU locale name\n+ */\n+#ifdef USE_ICU\n+ {\n+ UErrorCode status;\n+\n+ status = U_ZERO_ERROR;\n+ ucol_open(icu_locale, &status);\n+ if (U_FAILURE(status))\n+ {\n+ pg_log_error(\"could not open collator for locale \\\"%s\\\": %s\",\n+ icu_locale, u_errorName(status));\n+ exit(1);\n+ }\n+ }\n+#else\n+ pg_log_error(\"ICU is not supported in this build\");\n+ fprintf(stderr, _(\"You need to rebuild PostgreSQL using %s.\\n\"), \"--with-icu\");\n+ exit(1);\n+#endif\n+ }\n\nShouldn't all the code before checking the locale name also be in the #ifdef\nUSE_ICU? Also, the comment should be consistent with the doc and mention\nICU locale ID.\n\n@@ -2859,6 +2870,17 @@ dumpDatabase(Archive *fout)\n appendPQExpBufferStr(creaQry, \" ENCODING = \");\n appendStringLiteralAH(creaQry, encoding, fout);\n }\n+ if (strlen(datlocprovider) > 0)\n+ {\n+ appendPQExpBufferStr(creaQry, \" LOCALE_PROVIDER = \");\n+ if (datlocprovider[0] == 'c')\n+ appendPQExpBufferStr(creaQry, \"libc\");\n+ else if (datlocprovider[0] == 'i')\n+ appendPQExpBufferStr(creaQry, \"icu\");\n+ else\n+ fatal(\"unrecognized locale provider: %s\",\n+ datlocprovider);\n+ }\n if (strlen(collate) > 0 && strcmp(collate, ctype) == 0)\n {\n\nAFAICS datlocprovider shouldn't be empty. Maybe raise an error or an assert if\nthat's the case?\n\n\n# CREATE DATABASE db1 LOCALE_PROVIDER icu ICU_LOCALE \"fr-x-icu\";\nERROR: 22023: new locale provider (i) does not match locale provider of the template database (c)\nHINT: Use the same locale provider as in the template database, or use template0 as template.\n\nIt feels strange to write \"LOCALE_PROVIDER icu\" and get \"provider (i)\" in the\nerror message. I think it would be better to emit the user-facing value, not\ninternal one.\n\nFinally, there are some changes in pg_collation, I'm assuming it's done for\nconsistency since pg_database may need two different locale information, but it\nshould probably be at least mentioned in the commit message.\n\n\n[1]: https://unicode-org.github.io/icu/userguide/locale/#:~:text=The%20locale%20object%20in%20ICU,fields%20separated%20by%20an%20underscore.\n\n\n", "msg_date": "Sat, 5 Mar 2022 16:38:30 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 05.03.22 09:38, Julien Rouhaud wrote:\n> @@ -168,18 +175,6 @@ DefineCollation(ParseState *pstate, List *names, List *parameters, bool if_not_e\n> errmsg(\"collation \\\"default\\\" cannot be copied\")));\n> }\n> \n> - if (localeEl)\n> - {\n> - collcollate = defGetString(localeEl);\n> - collctype = defGetString(localeEl);\n> - }\n> [...]\n> \n> I tried to read the function and quickly got confused about whether possible\n> problematic conditions could be reached or not and had protection or not. I\n> think that DefineCollation is becoming more and more unreadable, with a mix of\n> fromEl, !fromEl and either. Maybe it would be a good time to refactor the code\n> a bit and have have something like\n> \n> if (fromEl)\n> {\n> // initialize all specific things\n> }\n> else\n> {\n> // initialize all specific things\n> }\n> \n> // handle defaults and sanity checks\n> \n> What do you think?\n\nHow about the attached?", "msg_date": "Thu, 10 Mar 2022 10:52:41 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Thu, Mar 10, 2022 at 10:52:41AM +0100, Peter Eisentraut wrote:\n> On 05.03.22 09:38, Julien Rouhaud wrote:\n> > @@ -168,18 +175,6 @@ DefineCollation(ParseState *pstate, List *names, List *parameters, bool if_not_e\n> > errmsg(\"collation \\\"default\\\" cannot be copied\")));\n> > }\n> > \n> > - if (localeEl)\n> > - {\n> > - collcollate = defGetString(localeEl);\n> > - collctype = defGetString(localeEl);\n> > - }\n> > [...]\n> > \n> > I tried to read the function and quickly got confused about whether possible\n> > problematic conditions could be reached or not and had protection or not. I\n> > think that DefineCollation is becoming more and more unreadable, with a mix of\n> > fromEl, !fromEl and either. Maybe it would be a good time to refactor the code\n> > a bit and have have something like\n> > \n> > if (fromEl)\n> > {\n> > // initialize all specific things\n> > }\n> > else\n> > {\n> > // initialize all specific things\n> > }\n> > \n> > // handle defaults and sanity checks\n> > \n> > What do you think?\n> \n> How about the attached?\n\nThanks! That's exactly what I had in mind. I think it's easier to follow and\nmake sure of what it's doing exactly, so +1 for it.\n\n\n", "msg_date": "Thu, 10 Mar 2022 18:27:12 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 05.03.22 09:38, Julien Rouhaud wrote:\n> I say it works because I did manually check, as far as I can see there isn't\n> any test that ensures it.\n> \n> I'm using this naive scenario:\n> \n> DROP DATABASE IF EXISTS dbicu;\n> CREATE DATABASE dbicu LOCALE_PROVIDER icu LOCALE 'en_US' ICU_LOCALE 'en-u-kf-upper' template 'template0';\n> \\c dbicu\n> CREATE COLLATION upperfirst (provider = icu, locale = 'en-u-kf-upper');\n> CREATE TABLE icu(def text, en text COLLATE \"en_US\", upfirst text COLLATE upperfirst);\n> INSERT INTO icu VALUES ('a', 'a', 'a'), ('b','b','b'), ('A','A','A'), ('B','B','B');\n> SELECT def AS def FROM icu ORDER BY def;\n> SELECT def AS en FROM icu ORDER BY en;\n> SELECT def AS upfirst FROM icu ORDER BY upfirst;\n> SELECT def AS upfirst_explicit FROM icu ORDER BY en COLLATE upperfirst;\n> SELECT def AS en_x_explicit FROM icu ORDER BY def COLLATE \"en-x-icu\";\n> \n> Maybe there should be some test along those lines included in the patch?\n\nI added something like this to a new test suite under src/test/icu/. \n(src/test/locale/ was already used for something else.)\n\n> Also, it's not even used consistently in the patch. I can see e.g. \"ICU\n> locale\" or \"ICU locale setting\" being used:\n\nI have fixed those.\n\n> Maybe we could point to the ICU documentation for a clear notion of what a\n> locale ID is, and/or use their own short definition [1]:\n> \n>> The locale object in ICU is an identifier that specifies a particular locale\n>> and has fields for language, country, and an optional code to specify further\n>> variants or subdivisions. These fields also can be represented as a string\n>> with the fields separated by an underscore.\n\nI think the Localization chapter needs to be reorganized a bit, but I'll \nleave that for a separate patch.\n\n> I spent some time looking at the ICU api trying to figure out if using a\n> posix locale name (e.g. en_US) was actually compatible with an ICU locale name.\n> It seems that ICU accept any of 'en-us', 'en-US', 'en_us' or 'en_US' as the\n> same locale, but I might be wrong. I also didn't find a way to figure out how\n> to ask ICU if the locale identifier passed is complete garbage or not. One\n> sure thing is that the system collation we import are of the form 'en-us', so\n> it seems weird to have this form in pg_collation and by default another form in\n> pg_database.\n\nYeah it seems to be inconsistent about that. The locale ID \ndocumentation appears to indicate that \"en_US\" is the canonical form, \nbut when you ask it to list all the locales it knows about it returns \n\"en-US\".\n\n> In CREATE DATABASE manual:\n> \n> + Specifies the provider to use for the default collation in this\n> + database. Possible values are:\n> + <literal>icu</literal>,<indexterm><primary>ICU</primary></indexterm>\n> + <literal>libc</literal>. <literal>libc</literal> is the default. The\n> + available choices depend on the operating system and build options.\n> \n> That's actually not true as pg_strcasecmp is used in createdb():\n> \n> + if (pg_strcasecmp(locproviderstr, \"icu\") == 0)\n> + dblocprovider = COLLPROVIDER_ICU;\n> + else if (pg_strcasecmp(locproviderstr, \"libc\") == 0)\n> + dblocprovider = COLLPROVIDER_LIBC;\n> + else\n> + ereport(ERROR,\n> + (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),\n> + errmsg(\"unrecognized locale provider: %s\",\n> + locproviderstr)));\n\nI don't understand what the concern is here.\n\n> Unless I'm missing something you entirely removed the warninng about the\n> performance penalty when using non C/POSIX locale?\n\nYeah, I think it is not the job of the initdb man page to lecture people \nabout the merits of their locale choice. The same performance warning \ncan also be found in the localization chapter; we don't need to repeat \nit everywhere a locale choice is mentioned.\n\n> initdb has some specific processing to transform the default libc locale to\n> something more appropriate, but as far as I can see creatdb / CREATE DATABASE\n> aren't doing that. It seems inconsistent, and IMHO another reason why\n> defaulting to the libc locale looks like a bad idea.\n\nThis has all been removed. The separate ICU locale option should now be \nrequired everywhere (initdb, createdb, CREATE DATABASE).\n\n> While on that topic, the doc should probably mention that default ICU\n> collations can only be deterministic.\n\nWell, there is no option to do otherwise, so I'm not sure where/how to \nmention that. We usually don't document options that don't exist. ;-)\n\n> Also unrelated, but how about raising a warning about possibly hiding\n> corruption if you use CREATE COLLATION ... VERSION or CREATE DATABASE ...\n> COLLATION_VERSION if !IsBinaryUpgrade()?\n\nHmm, there is a point to that. But then we should just make that an \nerror. Otherwise, we raise the warning but then there is no way to \n\"fix\" what was warned about. Seems confusing.\n\n> in AlterCollation(), pg_collation_actual_version(), AlterDatabaseRefreshColl()\n> and pg_database_collation_actual_version():\n> \n> - datum = SysCacheGetAttr(COLLOID, tup, Anum_pg_collation_collcollate, &isnull);\n> - Assert(!isnull);\n> - newversion = get_collation_actual_version(collForm->collprovider, TextDatumGetCString(datum));\n> + datum = SysCacheGetAttr(COLLOID, tup, collForm->collprovider == COLLPROVIDER_ICU ? Anum_pg_collation_colliculocale : Anum_pg_collation_collcollate, &isnull);\n> + if (!isnull)\n> + newversion = get_collation_actual_version(collForm->collprovider, TextDatumGetCString(datum));\n> + else\n> + newversion = NULL;\n> \n> The columns are now nullable, but can you actually end up with a null locale\n> name in the expected field without manual DML on the catalog, corruption or\n> similar? I think it should be a plain error explaining the inconsistency\n> rather then silently assuming there's no version. Note that at least\n> pg_newlocale_from_collation() asserts that the specific libc/icu field it's\n> interested in isn't null.\n\nThis is required because the default collations's fields are null now.\n\n> Why not using errorConflictingDefElem for locale_provider?\n\nfixed\n\n> in createdb():\n> \n> + if (dblocprovider == COLLPROVIDER_ICU)\n> + {\n> + /*\n> + * This would happen if template0 uses the libc provider but the new\n> + * database uses icu.\n> + */\n> + if (!dbiculocale)\n> + ereport(ERROR,\n> + (errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n> + errmsg(\"ICU locale must be specified\")));\n> + }\n> +\n> + if (dblocprovider == COLLPROVIDER_ICU)\n> + {\n> +#ifdef USE_ICU\n> [...]\n> \n> Seems like a refactoring leftover, no need for two blocks.\n\nThese are two independent blocks in my mind. It's possible that someone \nmight want to insert something in the middle at some point.\n\n> Also, I think it\n> would be better to first error out if there's no support for ICU rather than\n> complaining about a possibly missing locale that wouldn't be accepted anyway.\n\nSeems better to do general syntax checks first and then deeper checks of \nthe passed values.\n\n> +void\n> +make_icu_collator(const char *iculocstr,\n> + struct pg_locale_struct *resultp)\n> +{\n> +#ifdef USE_ICU\n> +[...]\n> + /* We will leak this string if we get an error below :-( */\n> + resultp->info.icu.locale = MemoryContextStrdup(TopMemoryContext, iculocstr);\n> + resultp->info.icu.ucol = collator;\n> +#else /* not USE_ICU */\n> + /* could get here if a collation was created by a build with ICU */\n> + ereport(ERROR,\n> + (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),\n> + errmsg(\"ICU is not supported in this build\"), \\\n> + errhint(\"You need to rebuild PostgreSQL using %s.\", \"--with-icu\")));\n> +#endif /* not USE_ICU */\n> +}\n> \n> The comment about the leak possibility needs some tweaking since it's been\n> extracted from a larger function.\n\nfixed\n\n> Not material for this patch, but:\n> @@ -1475,7 +1524,12 @@ pg_newlocale_from_collation(Oid collid)\n> Assert(OidIsValid(collid));\n> \n> if (collid == DEFAULT_COLLATION_OID)\n> - return (pg_locale_t) 0;\n> + {\n> + if (default_locale.provider == COLLPROVIDER_ICU)\n> + return &default_locale;\n> + else\n> + return (pg_locale_t) 0;\n> + }\n> \n> I'm wondering if we could now always return &default_locale and avoid having to\n> check if the function returned something in all callers, since CheckMyDatabase\n> now initialize it.\n\nMaybe that's something to look into, but that would probably require \nupdating a call callers to handle the return values differently, which \nwould require quite a bit of work.\n\n> Shouldn't all the code before checking the locale name also be in the #ifdef\n> USE_ICU?\n\nI like to keep the #ifdef sections as small as possible and limited to \nthe code that really uses the respective library.\n\n> @@ -2859,6 +2870,17 @@ dumpDatabase(Archive *fout)\n> appendPQExpBufferStr(creaQry, \" ENCODING = \");\n> appendStringLiteralAH(creaQry, encoding, fout);\n> }\n> + if (strlen(datlocprovider) > 0)\n> + {\n> + appendPQExpBufferStr(creaQry, \" LOCALE_PROVIDER = \");\n> + if (datlocprovider[0] == 'c')\n> + appendPQExpBufferStr(creaQry, \"libc\");\n> + else if (datlocprovider[0] == 'i')\n> + appendPQExpBufferStr(creaQry, \"icu\");\n> + else\n> + fatal(\"unrecognized locale provider: %s\",\n> + datlocprovider);\n> + }\n> if (strlen(collate) > 0 && strcmp(collate, ctype) == 0)\n> {\n> \n> AFAICS datlocprovider shouldn't be empty. Maybe raise an error or an assert if\n> that's the case?\n\nYeah that was bogus, copied from the earlier encoding handling, which is \nprobably also bogus, but I'm not touching that here.\n\n> # CREATE DATABASE db1 LOCALE_PROVIDER icu ICU_LOCALE \"fr-x-icu\";\n> ERROR: 22023: new locale provider (i) does not match locale provider of the template database (c)\n> HINT: Use the same locale provider as in the template database, or use template0 as template.\n> \n> It feels strange to write \"LOCALE_PROVIDER icu\" and get \"provider (i)\" in the\n> error message. I think it would be better to emit the user-facing value, not\n> internal one.\n\nFixed. I had added a collprovider_name() function but didn't use it here.\n\n> Finally, there are some changes in pg_collation, I'm assuming it's done for\n> consistency since pg_database may need two different locale information, but it\n> should probably be at least mentioned in the commit message.\n\ndone", "msg_date": "Mon, 14 Mar 2022 13:50:50 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Mon, Mar 14, 2022 at 8:51 AM Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n> [ new patches ]\n\nI'm not very knowledgeable about this topic, but to me, it seems\nconfusing to think of having both a libc collation and an ICU\ncollation associated with a database. I have two main questions:\n\n1. What will happen if I set the ICU collation to something that\ndoesn't match the libc collation? How bad are the consequences?\n\n2. If I want to avoid a mismatch between the two, then I will need a\nway to figure out which libc collation corresponds to a given ICU\ncollation. How do I do that?\n\nI have a sneaking suspicion that I'm not going to like the answer to\nquestion #2 very much, but maybe that's life. I feel like this whole\narea is far too full of magical things. True practitioners know that\nif you utter some mysterious incantation to the Lords of ICU, you can\nget exactly the behavior you want. And ... everyone else has no idea\nwhat to do.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Mon, 14 Mar 2022 14:57:48 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Mon, Mar 14, 2022 at 01:50:50PM +0100, Peter Eisentraut wrote:\n> On 05.03.22 09:38, Julien Rouhaud wrote:\n> > I say it works because I did manually check, as far as I can see there isn't\n> > any test that ensures it.\n> >\n> > I'm using this naive scenario:\n> >\n> > DROP DATABASE IF EXISTS dbicu;\n> > CREATE DATABASE dbicu LOCALE_PROVIDER icu LOCALE 'en_US' ICU_LOCALE 'en-u-kf-upper' template 'template0';\n> > \\c dbicu\n> > CREATE COLLATION upperfirst (provider = icu, locale = 'en-u-kf-upper');\n> > CREATE TABLE icu(def text, en text COLLATE \"en_US\", upfirst text COLLATE upperfirst);\n> > INSERT INTO icu VALUES ('a', 'a', 'a'), ('b','b','b'), ('A','A','A'), ('B','B','B');\n> > SELECT def AS def FROM icu ORDER BY def;\n> > SELECT def AS en FROM icu ORDER BY en;\n> > SELECT def AS upfirst FROM icu ORDER BY upfirst;\n> > SELECT def AS upfirst_explicit FROM icu ORDER BY en COLLATE upperfirst;\n> > SELECT def AS en_x_explicit FROM icu ORDER BY def COLLATE \"en-x-icu\";\n> >\n> > Maybe there should be some test along those lines included in the patch?\n>\n> I added something like this to a new test suite under src/test/icu/.\n> (src/test/locale/ was already used for something else.)\n\nGreat, thanks!\n\n> > > The locale object in ICU is an identifier that specifies a particular locale\n> > > and has fields for language, country, and an optional code to specify further\n> > > variants or subdivisions. These fields also can be represented as a string\n> > > with the fields separated by an underscore.\n>\n> I think the Localization chapter needs to be reorganized a bit, but I'll\n> leave that for a separate patch.\n\nWFM.\n\n> > I spent some time looking at the ICU api trying to figure out if using a\n> > posix locale name (e.g. en_US) was actually compatible with an ICU locale name.\n> > It seems that ICU accept any of 'en-us', 'en-US', 'en_us' or 'en_US' as the\n> > same locale, but I might be wrong. I also didn't find a way to figure out how\n> > to ask ICU if the locale identifier passed is complete garbage or not. One\n> > sure thing is that the system collation we import are of the form 'en-us', so\n> > it seems weird to have this form in pg_collation and by default another form in\n> > pg_database.\n>\n> Yeah it seems to be inconsistent about that. The locale ID documentation\n> appears to indicate that \"en_US\" is the canonical form, but when you ask it\n> to list all the locales it knows about it returns \"en-US\".\n\nYeah I saw that too when checking is POSIX locale names were valid, and that's\nnot great.\n>\n> > In CREATE DATABASE manual:\n> >\n> > + Specifies the provider to use for the default collation in this\n> > + database. Possible values are:\n> > + <literal>icu</literal>,<indexterm><primary>ICU</primary></indexterm>\n> > + <literal>libc</literal>. <literal>libc</literal> is the default. The\n> > + available choices depend on the operating system and build options.\n> >\n> > That's actually not true as pg_strcasecmp is used in createdb():\n>\n> I don't understand what the concern is here.\n\nAh sorry I missed the <indexterm>, I thought the possible values listed were\nicu, ICU and libc. Shouldn't the ICU <indexterm> be before the icu <literal>\nrather than the libc, or at least before the comma?\n>\n> Yeah, I think it is not the job of the initdb man page to lecture people\n> about the merits of their locale choice. The same performance warning can\n> also be found in the localization chapter; we don't need to repeat it\n> everywhere a locale choice is mentioned.\n\nAh, I tried to look for another place where the same warning could be found but\nmissed it. I'm fine with it then!\n\n> > While on that topic, the doc should probably mention that default ICU\n> > collations can only be deterministic.\n>\n> Well, there is no option to do otherwise, so I'm not sure where/how to\n> mention that. We usually don't document options that don't exist. ;-)\n\nSure, but I'm afraid that users may still be tempted to use ICU locales like\nund-u-ks-level2 from the case_insensitive example in the doc and hope that it\nwill work accordingly. Or maybe it's just me that still sees ICU as dark magic\nand want to be extra cautious.\n\nUnrelated, but I just realized that we have PGC_INTERNAL gucs for lc_ctype and\nlc_collate. Should we add one for icu_locale too?\n\n> > Also unrelated, but how about raising a warning about possibly hiding\n> > corruption if you use CREATE COLLATION ... VERSION or CREATE DATABASE ...\n> > COLLATION_VERSION if !IsBinaryUpgrade()?\n>\n> Hmm, there is a point to that. But then we should just make that an error.\n> Otherwise, we raise the warning but then there is no way to \"fix\" what was\n> warned about. Seems confusing.\n\nI was afraid that an error was a bit too much, but if that's acceptable I agree\nthat it's better.\n\n> > in AlterCollation(), pg_collation_actual_version(), AlterDatabaseRefreshColl()\n> > and pg_database_collation_actual_version():\n> >\n> > - datum = SysCacheGetAttr(COLLOID, tup, Anum_pg_collation_collcollate, &isnull);\n> > - Assert(!isnull);\n> > - newversion = get_collation_actual_version(collForm->collprovider, TextDatumGetCString(datum));\n> > + datum = SysCacheGetAttr(COLLOID, tup, collForm->collprovider == COLLPROVIDER_ICU ? Anum_pg_collation_colliculocale : Anum_pg_collation_collcollate, &isnull);\n> > + if (!isnull)\n> > + newversion = get_collation_actual_version(collForm->collprovider, TextDatumGetCString(datum));\n> > + else\n> > + newversion = NULL;\n> >\n> > The columns are now nullable, but can you actually end up with a null locale\n> > name in the expected field without manual DML on the catalog, corruption or\n> > similar? I think it should be a plain error explaining the inconsistency\n> > rather then silently assuming there's no version. Note that at least\n> > pg_newlocale_from_collation() asserts that the specific libc/icu field it's\n> > interested in isn't null.\n>\n> This is required because the default collations's fields are null now.\n\nYes I saw that, but that's a specific exception. Detecting whether it's the\nDEFAULT_COLLATION_OID or not and raise an error when a null value isn't\nexpected seems like it could be worthwhile.\n\n> > I'm wondering if we could now always return &default_locale and avoid having to\n> > check if the function returned something in all callers, since CheckMyDatabase\n> > now initialize it.\n>\n> Maybe that's something to look into, but that would probably require\n> updating a call callers to handle the return values differently, which would\n> require quite a bit of work.\n\nAgreed, I just wanted to mention it before forgetting about it.\n\nSo apart from the few details mentioned above I'm happy with this patch!\n\nThere might still be some more adjustments needed based on Robert's comment.\nAt the very least it doesn't seem unreasonable to forbid a default ICU\ncollation with a C/POSIX lc_ctype for instance.\n\n\n", "msg_date": "Tue, 15 Mar 2022 15:41:03 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "\nOn 14.03.22 19:57, Robert Haas wrote:\n> 1. What will happen if I set the ICU collation to something that\n> doesn't match the libc collation? How bad are the consequences?\n\nThese are unrelated, so there are no consequences.\n\n> 2. If I want to avoid a mismatch between the two, then I will need a\n> way to figure out which libc collation corresponds to a given ICU\n> collation. How do I do that?\n\nYou can specify the same name for both.\n\n\n", "msg_date": "Tue, 15 Mar 2022 17:58:17 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Tue, Mar 15, 2022 at 12:58 PM Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n> On 14.03.22 19:57, Robert Haas wrote:\n> > 1. What will happen if I set the ICU collation to something that\n> > doesn't match the libc collation? How bad are the consequences?\n>\n> These are unrelated, so there are no consequences.\n\nCan you please elaborate on this?\n\n> > 2. If I want to avoid a mismatch between the two, then I will need a\n> > way to figure out which libc collation corresponds to a given ICU\n> > collation. How do I do that?\n>\n> You can specify the same name for both.\n\nHmm. If every name were valid in both systems, I don't think you'd be\nproposing two fields.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 15 Mar 2022 13:28:01 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Can we get some more consistent terminology around the term \"locale\"?\r\n\r\nIn ICU, the \"locale\" is just the first part of what we can pass to the \"locale\" parameter in CREATE COLLATION - the part before the optional '@' delimiter. The ICU locale does not include the secondary or tertiary properties, so it is usually just the country and the language, e.g. en_US (or en-US), but it can also be something like es_TRADITIONAL for traditional Spanish. \r\n\r\nI think it would be an improvement in clarity if we consistently use the term 'locale' to mean the same thing that ICU means by that term, and not to have the thing that we call the \"locale\" also include collation modifiers, or to imply that a locale is the same thing as a collation.\r\n\r\n /Jim\r\n\r\n\r\n\r\n\r\n", "msg_date": "Tue, 15 Mar 2022 19:47:09 +0000", "msg_from": "\"Finnerty, Jim\" <jfinnert@amazon.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "\tJulien Rouhaud wrote:\n\n> > > While on that topic, the doc should probably mention that default ICU\n> > > collations can only be deterministic.\n> >\n> > Well, there is no option to do otherwise, so I'm not sure where/how to\n> > mention that. We usually don't document options that don't exist. ;-)\n> \n> Sure, but I'm afraid that users may still be tempted to use ICU locales like\n> und-u-ks-level2 from the case_insensitive example in the doc and hope that\n> it will work accordingly.\n\n+1.\n\nThe CREATE DATABASE doc says this currently:\n\nicu_locale\n\n Specifies the ICU locale ID if the ICU locale provider is used.\n\n\nISTM that we need to say explicitly that this locale will be used by\ndefault to compare all collatable strings, except that it's overruled\nby a bytewise comparison to break ties in case of equality.\n\nThe idea is to describe what the backend will do with the setting\nrather than saying that we don't have a nondeterministic option.\n\n\nBest regards,\n-- \nDaniel Vérité\nhttps://postgresql.verite.pro/\nTwitter: @DanielVerite\n\n\n", "msg_date": "Tue, 15 Mar 2022 20:48:00 +0100", "msg_from": "\"Daniel Verite\" <daniel@manitou-mail.org>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "\tFinnerty, Jim wrote:\n\n> In ICU, the \"locale\" is just the first part of what we can pass to the\n> \"locale\" parameter in CREATE COLLATION - the part before the optional '@'\n> delimiter. The ICU locale does not include the secondary or tertiary\n> properties,\n\nWhy not? Please see\nhttps://unicode-org.github.io/icu/userguide/locale\n\nIt says that \"a locale consists of one or more pieces of ordered\ninformation\", the pieces being a language code, a script code, a\ncountry code, a variant code, and keywords.\n\n\nBest regards,\n-- \nDaniel Vérité\nhttps://postgresql.verite.pro/\nTwitter: @DanielVerite\n\n\n", "msg_date": "Tue, 15 Mar 2022 21:19:41 +0100", "msg_from": "\"Daniel Verite\" <daniel@manitou-mail.org>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 15.03.22 18:28, Robert Haas wrote:\n> On Tue, Mar 15, 2022 at 12:58 PM Peter Eisentraut\n> <peter.eisentraut@enterprisedb.com> wrote:\n>> On 14.03.22 19:57, Robert Haas wrote:\n>>> 1. What will happen if I set the ICU collation to something that\n>>> doesn't match the libc collation? How bad are the consequences?\n>>\n>> These are unrelated, so there are no consequences.\n> \n> Can you please elaborate on this?\n\nThe code that is aware of ICU generally works like this:\n\nif (locale_provider == ICU)\n result = call ICU code\nelse\n result = call libc code\nreturn result\n\nHowever, there is code out there, both within PostgreSQL itself and in \nextensions, that does not do that yet. Ideally, we would eventually \nchange all that over, but it's not happening now. So we ought to \npreserve the ability to set the libc to keep that legacy code working \nfor now.\n\nThis legacy code by definition doesn't know about ICU, so it doesn't \ncare whether the ICU setting \"matches\" the libc setting or anything like \nthat. It will just do its thing depending on its own setting.\n\nThe only consequence of settings that don't match is that the different \npieces of code behave semantically inconsistently (e.g., some routine \nthinks the data is Greek and other code thinks the data is French). But \nthat's up to the user to set correctly. And the actual scenarios where \nyou can actually do anything semantically relevant this way are very \nlimited.\n\nA second point is that the LC_CTYPE setting tells other parts of libc \nwhat the current encoding is. This affects gettext for example. So you \nneed to set this to something sensible even if you don't use libc locale \nroutines otherwise.\n\n>>> 2. If I want to avoid a mismatch between the two, then I will need a\n>>> way to figure out which libc collation corresponds to a given ICU\n>>> collation. How do I do that?\n>>\n>> You can specify the same name for both.\n> \n> Hmm. If every name were valid in both systems, I don't think you'd be\n> proposing two fields.\n\nEarlier versions of this patch and predecessor patches indeed had common \nfields. But in fact the two systems accept different values if you want \nto delve into the advanced features. But for basic usage something like \n\"en_US\" will work for both.\n\n\n", "msg_date": "Wed, 16 Mar 2022 15:25:09 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 15.03.22 08:41, Julien Rouhaud wrote:\n>>>> The locale object in ICU is an identifier that specifies a particular locale\n>>>> and has fields for language, country, and an optional code to specify further\n>>>> variants or subdivisions. These fields also can be represented as a string\n>>>> with the fields separated by an underscore.\n>>\n>> I think the Localization chapter needs to be reorganized a bit, but I'll\n>> leave that for a separate patch.\n> \n> WFM.\n\nI ended up writing a bit of content for that chapter.\n\n>>> While on that topic, the doc should probably mention that default ICU\n>>> collations can only be deterministic.\n>>\n>> Well, there is no option to do otherwise, so I'm not sure where/how to\n>> mention that. We usually don't document options that don't exist. ;-)\n> \n> Sure, but I'm afraid that users may still be tempted to use ICU locales like\n> und-u-ks-level2 from the case_insensitive example in the doc and hope that it\n> will work accordingly. Or maybe it's just me that still sees ICU as dark magic\n> and want to be extra cautious.\n\nI have added this to the CREATE DATABASE ref page.\n\n> Unrelated, but I just realized that we have PGC_INTERNAL gucs for lc_ctype and\n> lc_collate. Should we add one for icu_locale too?\n\nI'm not sure. I think the existing ones are more for backward \ncompatibility with the time before it was settable per database.\n\n>>> in AlterCollation(), pg_collation_actual_version(), AlterDatabaseRefreshColl()\n>>> and pg_database_collation_actual_version():\n>>>\n>>> - datum = SysCacheGetAttr(COLLOID, tup, Anum_pg_collation_collcollate, &isnull);\n>>> - Assert(!isnull);\n>>> - newversion = get_collation_actual_version(collForm->collprovider, TextDatumGetCString(datum));\n>>> + datum = SysCacheGetAttr(COLLOID, tup, collForm->collprovider == COLLPROVIDER_ICU ? Anum_pg_collation_colliculocale : Anum_pg_collation_collcollate, &isnull);\n>>> + if (!isnull)\n>>> + newversion = get_collation_actual_version(collForm->collprovider, TextDatumGetCString(datum));\n>>> + else\n>>> + newversion = NULL;\n>>>\n>>> The columns are now nullable, but can you actually end up with a null locale\n>>> name in the expected field without manual DML on the catalog, corruption or\n>>> similar? I think it should be a plain error explaining the inconsistency\n>>> rather then silently assuming there's no version. Note that at least\n>>> pg_newlocale_from_collation() asserts that the specific libc/icu field it's\n>>> interested in isn't null.\n>>\n>> This is required because the default collations's fields are null now.\n> \n> Yes I saw that, but that's a specific exception. Detecting whether it's the\n> DEFAULT_COLLATION_OID or not and raise an error when a null value isn't\n> expected seems like it could be worthwhile.\n\nI have fixed that as you suggest.\n\n> So apart from the few details mentioned above I'm happy with this patch!\n\ncommitted!\n\n\n", "msg_date": "Thu, 17 Mar 2022 11:28:39 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hi, \r\nThank you to all the developers.\r\nI found that the description of the pg_database.daticulocale column was not written in the documentation. \r\nThe attached small patch adds a description of the daticulocale column to catalogs.sgml.\r\n\r\nRegards,\r\nNoriyoshi Shinoda\r\n-----Original Message-----\r\nFrom: Peter Eisentraut <peter.eisentraut@enterprisedb.com> \r\nSent: Thursday, March 17, 2022 7:29 PM\r\nTo: Julien Rouhaud <rjuju123@gmail.com>\r\nCc: pgsql-hackers <pgsql-hackers@postgresql.org>; Daniel Verite <daniel@manitou-mail.org>\r\nSubject: Re: ICU for global collation\r\n\r\nOn 15.03.22 08:41, Julien Rouhaud wrote:\r\n>>>> The locale object in ICU is an identifier that specifies a \r\n>>>> particular locale and has fields for language, country, and an \r\n>>>> optional code to specify further variants or subdivisions. These \r\n>>>> fields also can be represented as a string with the fields separated by an underscore.\r\n>>\r\n>> I think the Localization chapter needs to be reorganized a bit, but \r\n>> I'll leave that for a separate patch.\r\n> \r\n> WFM.\r\n\r\nI ended up writing a bit of content for that chapter.\r\n\r\n>>> While on that topic, the doc should probably mention that default \r\n>>> ICU collations can only be deterministic.\r\n>>\r\n>> Well, there is no option to do otherwise, so I'm not sure where/how \r\n>> to mention that. We usually don't document options that don't exist. \r\n>> ;-)\r\n> \r\n> Sure, but I'm afraid that users may still be tempted to use ICU \r\n> locales like\r\n> und-u-ks-level2 from the case_insensitive example in the doc and hope \r\n> that it will work accordingly. Or maybe it's just me that still sees \r\n> ICU as dark magic and want to be extra cautious.\r\n\r\nI have added this to the CREATE DATABASE ref page.\r\n\r\n> Unrelated, but I just realized that we have PGC_INTERNAL gucs for \r\n> lc_ctype and lc_collate. Should we add one for icu_locale too?\r\n\r\nI'm not sure. I think the existing ones are more for backward compatibility with the time before it was settable per database.\r\n\r\n>>> in AlterCollation(), pg_collation_actual_version(), \r\n>>> AlterDatabaseRefreshColl() and pg_database_collation_actual_version():\r\n>>>\r\n>>> - datum = SysCacheGetAttr(COLLOID, tup, Anum_pg_collation_collcollate, &isnull);\r\n>>> - Assert(!isnull);\r\n>>> - newversion = get_collation_actual_version(collForm->collprovider, TextDatumGetCString(datum));\r\n>>> + datum = SysCacheGetAttr(COLLOID, tup, collForm->collprovider == COLLPROVIDER_ICU ? Anum_pg_collation_colliculocale : Anum_pg_collation_collcollate, &isnull);\r\n>>> + if (!isnull)\r\n>>> + newversion = get_collation_actual_version(collForm->collprovider, TextDatumGetCString(datum));\r\n>>> + else\r\n>>> + newversion = NULL;\r\n>>>\r\n>>> The columns are now nullable, but can you actually end up with a \r\n>>> null locale name in the expected field without manual DML on the \r\n>>> catalog, corruption or similar? I think it should be a plain error \r\n>>> explaining the inconsistency rather then silently assuming there's \r\n>>> no version. Note that at least\r\n>>> pg_newlocale_from_collation() asserts that the specific libc/icu \r\n>>> field it's interested in isn't null.\r\n>>\r\n>> This is required because the default collations's fields are null now.\r\n> \r\n> Yes I saw that, but that's a specific exception. Detecting whether \r\n> it's the DEFAULT_COLLATION_OID or not and raise an error when a null \r\n> value isn't expected seems like it could be worthwhile.\r\n\r\nI have fixed that as you suggest.\r\n\r\n> So apart from the few details mentioned above I'm happy with this patch!\r\n\r\ncommitted!", "msg_date": "Thu, 17 Mar 2022 12:01:14 +0000", "msg_from": "\"Shinoda, Noriyoshi (PN Japan FSIP)\" <noriyoshi.shinoda@hpe.com>", "msg_from_op": false, "msg_subject": "RE: ICU for global collation" }, { "msg_contents": "On 17.03.22 13:01, Shinoda, Noriyoshi (PN Japan FSIP) wrote:\n> Thank you to all the developers.\n> I found that the description of the pg_database.daticulocale column was not written in the documentation.\n> The attached small patch adds a description of the daticulocale column to catalogs.sgml.\n\ncommitted, thanks\n\n\n", "msg_date": "Thu, 17 Mar 2022 14:14:52 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Thu, Mar 17, 2022 at 6:15 AM Peter Eisentraut\n<peter.eisentraut@enterprisedb.com> wrote:\n> committed, thanks\n\nGlad that this finally happened. Thanks to everybody involved!\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Thu, 17 Mar 2022 12:34:50 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hi,\n\nOn 2022-03-17 14:14:52 +0100, Peter Eisentraut wrote:\n> On 17.03.22 13:01, Shinoda, Noriyoshi (PN Japan FSIP) wrote:\n> > Thank you to all the developers.\n> > I found that the description of the pg_database.daticulocale column was not written in the documentation.\n> > The attached small patch adds a description of the daticulocale column to catalogs.sgml.\n> \n> committed, thanks\n\nWee! That's a long time weakness addressed...\n\n\nJust saw a weird failure after rebasing my meson branch ontop of this. Tests\npassed on debian, suse, centos 8 stream, fedora rawhide (failed due to an\nindependent reason), but not on centos 7.\n\n\nall runs: https://cirrus-ci.com/build/5190538184884224\ncentos 7: https://cirrus-ci.com/task/4786632883699712?logs=tests_world#L204\ncentos 7 failure: https://api.cirrus-ci.com/v1/artifact/task/4786632883699712/log/build/testrun/icu/t/010_database/log/regress_log_010_database\n\nnot ok 1 - sort by database default locale\n# Failed test 'sort by database default locale'\n# at /tmp/cirrus-ci-build/src/test/icu/t/010_database.pl line 28.\n# got: 'a\n# A\n# b\n# B'\n# expected: 'A\n# a\n# B\n# b'\nok 2 - sort by explicit collation standard\nnot ok 3 - sort by explicit collation upper first\n# Failed test 'sort by explicit collation upper first'\n# at /tmp/cirrus-ci-build/src/test/icu/t/010_database.pl line 42.\n# got: 'a\n# A\n# b\n# B'\n# expected: 'A\n# a\n# B\n# b'\nok 4 - ICU locale must be specified for ICU provider: exit code not 0\nok 5 - ICU locale must be specified for ICU provider: error message\n1..5\n\nThis is a run building with meson. But I've now triggered builds with autoconf\non centos 7 as well and that also failed. See\nhttps://cirrus-ci.com/task/6194007767252992?logs=test_world#L378\n\nSo it looks like older ICU versions don't work?\n\nGreetings,\n\nAndres Freund\n\nPS: I had not yet passed with_icu in the initdb tests for meson, that's why\nthere's two failures with autoconf but only one with meson.\n\n\n", "msg_date": "Thu, 17 Mar 2022 17:01:40 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Thu, Mar 17, 2022 at 02:14:52PM +0100, Peter Eisentraut wrote:\n> On 17.03.22 13:01, Shinoda, Noriyoshi (PN Japan FSIP) wrote:\n> > Thank you to all the developers.\n> > I found that the description of the pg_database.daticulocale column was not written in the documentation.\n> > The attached small patch adds a description of the daticulocale column to catalogs.sgml.\n>\n> committed, thanks\n\nThanks a lot both! Glad to finally have that feature, as soon as we'll fix\nthe few reported problems.\n\n\n", "msg_date": "Fri, 18 Mar 2022 14:52:17 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hi,\n\nOn 2022-03-17 14:14:52 +0100, Peter Eisentraut wrote:\n> committed, thanks\n\nJust noticed that this adds a new warning when building with -O3:\n\nIn file included from /home/andres/src/postgresql/src/include/catalog/pg_collation.h:22,\n from /home/andres/src/postgresql/src/backend/commands/dbcommands.c:39:\nIn function ‘collprovider_name’,\n inlined from ‘createdb’ at /home/andres/src/postgresql/src/backend/commands/dbcommands.c:514:4:\n../../../src/include/catalog/pg_collation_d.h:47:9: warning: ‘src_locprovider’ may be used uninitialized [-Wmaybe-uninitialized]\n 47 | switch (c)\n | ^~~~~~\n/home/andres/src/postgresql/src/backend/commands/dbcommands.c: In function ‘createdb’:\n/home/andres/src/postgresql/src/backend/commands/dbcommands.c:112:25: note: ‘src_locprovider’ was declared here\n 112 | char src_locprovider;\n | ^~~~~~~~~~~~~~~\n\nI'd fixed that for nearby variables in 3f6b3be39ca9... Gonna just NULL\ninitialize it as well.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 18 Mar 2022 18:47:07 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "commit f2553d43060edb210b36c63187d52a632448e1d2 says >=1500 in a few places,\nbut in pg_upgrade says <=1500, which looks wrong for upgrades from v15.\nI think it should say <= 1400.\n\nOn Wed, Feb 02, 2022 at 02:01:23PM +0100, Peter Eisentraut wrote:\n> --- a/src/bin/pg_dump/pg_dump.c\n> +++ b/src/bin/pg_dump/pg_dump.c\n> @@ -2792,6 +2794,10 @@ dumpDatabase(Archive *fout)\n> \t\tappendPQExpBuffer(dbQry, \"datminmxid, \");\n> \telse\n> \t\tappendPQExpBuffer(dbQry, \"0 AS datminmxid, \");\n> +\tif (fout->remoteVersion >= 150000)\n> +\t\tappendPQExpBuffer(dbQry, \"datcollprovider, \");\n> +\telse\n> +\t\tappendPQExpBuffer(dbQry, \"'c' AS datcollprovider, \");\n> \tappendPQExpBuffer(dbQry,\n> \t\t\t\t\t \"(SELECT spcname FROM pg_tablespace t WHERE t.oid = dattablespace) AS tablespace, \"\n> \t\t\t\t\t \"shobj_description(oid, 'pg_database') AS description \"\n\n> diff --git a/src/bin/pg_upgrade/info.c b/src/bin/pg_upgrade/info.c\n> index 69ef23119f..2a9ca0e389 100644\n> --- a/src/bin/pg_upgrade/info.c\n> +++ b/src/bin/pg_upgrade/info.c\n> @@ -312,11 +312,20 @@ get_db_infos(ClusterInfo *cluster)\n> \t\t\t\ti_spclocation;\n> \tchar\t\tquery[QUERY_ALLOC];\n> \n> \tsnprintf(query, sizeof(query),\n> -\t\t\t \"SELECT d.oid, d.datname, d.encoding, d.datcollate, d.datctype, \"\n> +\t\t\t \"SELECT d.oid, d.datname, d.encoding, d.datcollate, d.datctype, \");\n> +\tif (GET_MAJOR_VERSION(old_cluster.major_version) <= 1500)\n> +\t\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n> +\t\t\t\t \"'c' AS datcollprovider, NULL AS daticucoll, \");\n> +\telse\n> +\t\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n> +\t\t\t\t \"datcollprovider, daticucoll, \");\n> +\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n> \t\t\t \"pg_catalog.pg_tablespace_location(t.oid) AS spclocation \"\n> \t\t\t \"FROM pg_catalog.pg_database d \"\n> \t\t\t \" LEFT OUTER JOIN pg_catalog.pg_tablespace t \"\n\n> --- a/src/bin/psql/describe.c\n> +++ b/src/bin/psql/describe.c\n> @@ -896,6 +896,18 @@ listAllDbs(const char *pattern, bool verbose)\n> \t\t\t\t\t gettext_noop(\"Encoding\"),\n> \t\t\t\t\t gettext_noop(\"Collate\"),\n> \t\t\t\t\t gettext_noop(\"Ctype\"));\n> +\tif (pset.sversion >= 150000)\n> +\t\tappendPQExpBuffer(&buf,\n> +\t\t\t\t\t\t \" d.daticucoll as \\\"%s\\\",\\n\"\n> +\t\t\t\t\t\t \" CASE d.datcollprovider WHEN 'c' THEN 'libc' WHEN 'i' THEN 'icu' END AS \\\"%s\\\",\\n\",\n> +\t\t\t\t\t\t gettext_noop(\"ICU Collation\"),\n> +\t\t\t\t\t\t gettext_noop(\"Coll. Provider\"));\n> +\telse\n> +\t\tappendPQExpBuffer(&buf,\n> +\t\t\t\t\t\t \" d.datcollate as \\\"%s\\\",\\n\"\n> +\t\t\t\t\t\t \" 'libc' AS \\\"%s\\\",\\n\",\n> +\t\t\t\t\t\t gettext_noop(\"ICU Collation\"),\n> +\t\t\t\t\t\t gettext_noop(\"Coll. Provider\"));\n> \tappendPQExpBufferStr(&buf, \" \");\n> \tprintACLColumn(&buf, \"d.datacl\");\n> \tif (verbose)\n\n> @@ -4617,6 +4629,15 @@ listCollations(const char *pattern, bool verbose, bool showSystem)\n> \t\t\t\t\t gettext_noop(\"Collate\"),\n> \t\t\t\t\t gettext_noop(\"Ctype\"));\n> \n> +\tif (pset.sversion >= 150000)\n> +\t\tappendPQExpBuffer(&buf,\n> +\t\t\t\t\t\t \",\\n c.collicucoll AS \\\"%s\\\"\",\n> +\t\t\t\t\t\t gettext_noop(\"ICU Collation\"));\n> +\telse\n> +\t\tappendPQExpBuffer(&buf,\n> +\t\t\t\t\t\t \",\\n c.collcollate AS \\\"%s\\\"\",\n> +\t\t\t\t\t\t gettext_noop(\"ICU Collation\"));\n> +\n> \tif (pset.sversion >= 100000)\n> \t\tappendPQExpBuffer(&buf,\n> \t\t\t\t\t\t \",\\n CASE c.collprovider WHEN 'd' THEN 'default' WHEN 'c' THEN 'libc' WHEN 'i' THEN 'icu' END AS \\\"%s\\\"\",\n\n\n", "msg_date": "Sat, 25 Jun 2022 10:19:30 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hi,\n\nOn Sat, Jun 25, 2022 at 10:19:30AM -0500, Justin Pryzby wrote:\n> commit f2553d43060edb210b36c63187d52a632448e1d2 says >=1500 in a few places,\n> but in pg_upgrade says <=1500, which looks wrong for upgrades from v15.\n> I think it should say <= 1400.\n> \n> On Wed, Feb 02, 2022 at 02:01:23PM +0100, Peter Eisentraut wrote:\n> > diff --git a/src/bin/pg_upgrade/info.c b/src/bin/pg_upgrade/info.c\n> > index 69ef23119f..2a9ca0e389 100644\n> > --- a/src/bin/pg_upgrade/info.c\n> > +++ b/src/bin/pg_upgrade/info.c\n> > @@ -312,11 +312,20 @@ get_db_infos(ClusterInfo *cluster)\n> > \t\t\t\ti_spclocation;\n> > \tchar\t\tquery[QUERY_ALLOC];\n> > \n> > \tsnprintf(query, sizeof(query),\n> > -\t\t\t \"SELECT d.oid, d.datname, d.encoding, d.datcollate, d.datctype, \"\n> > +\t\t\t \"SELECT d.oid, d.datname, d.encoding, d.datcollate, d.datctype, \");\n> > +\tif (GET_MAJOR_VERSION(old_cluster.major_version) <= 1500)\n> > +\t\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n> > +\t\t\t\t \"'c' AS datcollprovider, NULL AS daticucoll, \");\n> > +\telse\n> > +\t\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n> > +\t\t\t\t \"datcollprovider, daticucoll, \");\n> > +\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n> > \t\t\t \"pg_catalog.pg_tablespace_location(t.oid) AS spclocation \"\n> > \t\t\t \"FROM pg_catalog.pg_database d \"\n> > \t\t\t \" LEFT OUTER JOIN pg_catalog.pg_tablespace t \"\n\nIndeed!\n\n\n", "msg_date": "Sun, 26 Jun 2022 11:51:24 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Sun, Jun 26, 2022 at 11:51:24AM +0800, Julien Rouhaud wrote:\n> On Sat, Jun 25, 2022 at 10:19:30AM -0500, Justin Pryzby wrote:\n>>> +\tif (GET_MAJOR_VERSION(old_cluster.major_version) <= 1500)\n>>> +\t\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n>>> +\t\t\t\t \"'c' AS datcollprovider, NULL AS daticucoll, \");\n>>> +\telse\n>>> +\t\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n>>> +\t\t\t\t \"datcollprovider, daticucoll, \");\n>>> +\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n>>> \t\t\t \"pg_catalog.pg_tablespace_location(t.oid) AS spclocation \"\n>>> \t\t\t \"FROM pg_catalog.pg_database d \"\n>>> \t\t\t \" LEFT OUTER JOIN pg_catalog.pg_tablespace t \"\n> \n> Indeed!\n\nOops. Beta2 tagging is very close by, so I think that it would be\nbetter to not take a risk on that now, and this is an issue only when\nupgrading from v15 where datcollprovider is ICU for a database.\nAs things stand, someone using beta1 with this new feature, running\npg_upgrade to beta2 would lose any non-libc locale provider set.\n--\nMichael", "msg_date": "Sun, 26 Jun 2022 16:20:34 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 26.06.22 05:51, Julien Rouhaud wrote:\n> Hi,\n> \n> On Sat, Jun 25, 2022 at 10:19:30AM -0500, Justin Pryzby wrote:\n>> commit f2553d43060edb210b36c63187d52a632448e1d2 says >=1500 in a few places,\n>> but in pg_upgrade says <=1500, which looks wrong for upgrades from v15.\n>> I think it should say <= 1400.\n>>\n>> On Wed, Feb 02, 2022 at 02:01:23PM +0100, Peter Eisentraut wrote:\n>>> diff --git a/src/bin/pg_upgrade/info.c b/src/bin/pg_upgrade/info.c\n>>> index 69ef23119f..2a9ca0e389 100644\n>>> --- a/src/bin/pg_upgrade/info.c\n>>> +++ b/src/bin/pg_upgrade/info.c\n>>> @@ -312,11 +312,20 @@ get_db_infos(ClusterInfo *cluster)\n>>> \t\t\t\ti_spclocation;\n>>> \tchar\t\tquery[QUERY_ALLOC];\n>>> \n>>> \tsnprintf(query, sizeof(query),\n>>> -\t\t\t \"SELECT d.oid, d.datname, d.encoding, d.datcollate, d.datctype, \"\n>>> +\t\t\t \"SELECT d.oid, d.datname, d.encoding, d.datcollate, d.datctype, \");\n>>> +\tif (GET_MAJOR_VERSION(old_cluster.major_version) <= 1500)\n\nI think the fix here is to change <= to < ?\n\n>>> +\t\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n>>> +\t\t\t\t \"'c' AS datcollprovider, NULL AS daticucoll, \");\n>>> +\telse\n>>> +\t\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n>>> +\t\t\t\t \"datcollprovider, daticucoll, \");\n>>> +\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n>>> \t\t\t \"pg_catalog.pg_tablespace_location(t.oid) AS spclocation \"\n>>> \t\t\t \"FROM pg_catalog.pg_database d \"\n>>> \t\t\t \" LEFT OUTER JOIN pg_catalog.pg_tablespace t \"\n> \n> Indeed!\n> \n> \n\n\n\n", "msg_date": "Mon, 27 Jun 2022 08:23:59 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Mon, Jun 27, 2022 at 08:23:59AM +0200, Peter Eisentraut wrote:\n> On 26.06.22 05:51, Julien Rouhaud wrote:\n>> On Sat, Jun 25, 2022 at 10:19:30AM -0500, Justin Pryzby wrote:\n>>>> +\tif (GET_MAJOR_VERSION(old_cluster.major_version) <= 1500)\n> \n> I think the fix here is to change <= to < ?\n\nYes.\n--\nMichael", "msg_date": "Mon, 27 Jun 2022 15:42:19 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 27.06.22 08:42, Michael Paquier wrote:\n> On Mon, Jun 27, 2022 at 08:23:59AM +0200, Peter Eisentraut wrote:\n>> On 26.06.22 05:51, Julien Rouhaud wrote:\n>>> On Sat, Jun 25, 2022 at 10:19:30AM -0500, Justin Pryzby wrote:\n>>>>> +\tif (GET_MAJOR_VERSION(old_cluster.major_version) <= 1500)\n>>\n>> I think the fix here is to change <= to < ?\n> \n> Yes.\n\nOk, committed.\n\n(I see now that in the context of pg_upgrade, writing <= 1400 is \nequivalent, but I find that confusing, so I did < 1500.)\n\n\n", "msg_date": "Mon, 27 Jun 2022 09:10:29 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Mon, Jun 27, 2022 at 09:10:29AM +0200, Peter Eisentraut wrote:\n> On 27.06.22 08:42, Michael Paquier wrote:\n> > On Mon, Jun 27, 2022 at 08:23:59AM +0200, Peter Eisentraut wrote:\n> > > On 26.06.22 05:51, Julien Rouhaud wrote:\n> > > > On Sat, Jun 25, 2022 at 10:19:30AM -0500, Justin Pryzby wrote:\n> > > > > > +\tif (GET_MAJOR_VERSION(old_cluster.major_version) <= 1500)\n> > > \n> > > I think the fix here is to change <= to < ?\n> > \n> > Yes.\n> \n> Ok, committed.\n> \n> (I see now that in the context of pg_upgrade, writing <= 1400 is equivalent,\n> but I find that confusing, so I did < 1500.)\n\nI suggested using <= 1400 for consistency with the other code, and per\nbc1fbc960. But YMMV.\n\n-- \nJustin\n\n\n", "msg_date": "Mon, 27 Jun 2022 20:32:05 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hello everyone in this thread!\n\nWhile reading and testing the patch that adds ICU for global collations \n[1] I noticed on master (1c5818b9c68e5c2ac8f19d372f24cce409de1a26) and \nREL_15_STABLE (63b64d8270691894a9a8f2d4e929e7780020edb8) that:\n\n1) pg_upgrade from REL_14_STABLE \n(63b64d8270691894a9a8f2d4e929e7780020edb8) does not always work:\n\nFor REL_14_STABLE:\n\n$ initdb -D data_old\n\nFor REL_15_STABLE or master:\n\n$ initdb -D data_new --locale-provider icu --icu-locale ru-RU\n$ pg_upgrade -d .../data_old -D data_new -b ... -B ...\n...\nRestoring database schemas in the new cluster\n template1\n*failure*\n\nConsult the last few lines of \n\"data_new/pg_upgrade_output.d/20220815T142454.223/log/pg_upgrade_dump_1.log\" \nfor\nthe probable cause of the failure.\nFailure, exiting\n\nIn \ndata_new/pg_upgrade_output.d/20220815T142454.223/log/pg_upgrade_dump_1.log:\n\npg_restore: error: could not execute query: server closed the connection \nunexpectedly\n\tThis probably means the server terminated abnormally\n\tbefore or while processing the request.\nCommand was: CREATE DATABASE \"template1\" WITH TEMPLATE = template0 OID = \n1 ENCODING = 'UTF8' LOCALE_PROVIDER = libc LOCALE = 'en_US.UTF-8';\n\nIn \ndata_new/pg_upgrade_output.d/20220815T142454.223/log/pg_upgrade_server.log:\n\nTRAP: FailedAssertion(\"(dblocprovider == COLLPROVIDER_ICU && \ndbiculocale) || (dblocprovider != COLLPROVIDER_ICU && !dbiculocale)\", \nFile: \"dbcommands.c\", Line: 1292, PID: 69247)\npostgres: marina postgres [local] CREATE \nDATABASE(ExceptionalCondition+0xb9)[0xb4d8ec]\npostgres: marina postgres [local] CREATE \nDATABASE(createdb+0x1abc)[0x68ca99]\npostgres: marina postgres [local] CREATE \nDATABASE(standard_ProcessUtility+0x651)[0x9b1d82]\npostgres: marina postgres [local] CREATE \nDATABASE(ProcessUtility+0x122)[0x9b172a]\npostgres: marina postgres [local] CREATE DATABASE[0x9b01cf]\npostgres: marina postgres [local] CREATE DATABASE[0x9b0433]\npostgres: marina postgres [local] CREATE \nDATABASE(PortalRun+0x2fe)[0x9af95d]\npostgres: marina postgres [local] CREATE DATABASE[0x9a953b]\npostgres: marina postgres [local] CREATE \nDATABASE(PostgresMain+0x733)[0x9ada6b]\npostgres: marina postgres [local] CREATE DATABASE[0x8ec632]\npostgres: marina postgres [local] CREATE DATABASE[0x8ebfbb]\npostgres: marina postgres [local] CREATE DATABASE[0x8e8653]\npostgres: marina postgres [local] CREATE \nDATABASE(PostmasterMain+0x1226)[0x8e7f26]\npostgres: marina postgres [local] CREATE DATABASE[0x7bbccb]\n/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf3)[0x7eff082f90b3]\npostgres: marina postgres [local] CREATE DATABASE(_start+0x2e)[0x49c29e]\n2022-08-15 14:24:56.124 MSK [69231] LOG: server process (PID 69247) was \nterminated by signal 6: Aborted\n2022-08-15 14:24:56.124 MSK [69231] DETAIL: Failed process was running: \nCREATE DATABASE \"template1\" WITH TEMPLATE = template0 OID = 1 ENCODING = \n'UTF8' LOCALE_PROVIDER = libc LOCALE = 'en_US.UTF-8';\n\n1.1) It looks like there's a bug in the function get_db_infos \n(src/bin/pg_upgrade/info.c), where the version of the old cluster is \nalways checked:\n\nif (GET_MAJOR_VERSION(old_cluster.major_version) < 1500)\n\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n\t\t\t \"'c' AS datlocprovider, NULL AS daticulocale, \");\nelse\n\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n\t\t\t \"datlocprovider, daticulocale, \");\n\nWith the simple patch\n\ndiff --git a/src/bin/pg_upgrade/info.c b/src/bin/pg_upgrade/info.c\nindex \ndf374ce4b362b4c6c87fc1fd0e476e5d6d353d9e..53ea348e211d3ac38334292bc16cb814bc13bb87 \n100644\n--- a/src/bin/pg_upgrade/info.c\n+++ b/src/bin/pg_upgrade/info.c\n@@ -319,7 +319,7 @@ get_db_infos(ClusterInfo *cluster)\n\n \tsnprintf(query, sizeof(query),\n \t\t\t \"SELECT d.oid, d.datname, d.encoding, d.datcollate, d.datctype, \");\n-\tif (GET_MAJOR_VERSION(old_cluster.major_version) < 1500)\n+\tif (GET_MAJOR_VERSION(cluster->major_version) < 1500)\n \t\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n \t\t\t\t \"'c' AS datlocprovider, NULL AS daticulocale, \");\n \telse\n\nI got the expected error during the upgrade:\n\nlocale providers for database \"template1\" do not match: old \"libc\", new \n\"icu\"\nFailure, exiting\n\n1.2) It looks like the mentioned asserion in dbcommands.c conflicts with \nthe following lines earlier:\n\nif (dbiculocale == NULL)\n\tdbiculocale = src_iculocale;\n\nThe following patch works for me:\n\ndiff --git a/src/backend/commands/dbcommands.c \nb/src/backend/commands/dbcommands.c\nindex \nb31a30550b025d48ba3cc250dc4c15f41f9a80be..17a2942341e528c01182fb6d4878580f2706bec9 \n100644\n--- a/src/backend/commands/dbcommands.c\n+++ b/src/backend/commands/dbcommands.c\n@@ -1048,6 +1048,8 @@ createdb(ParseState *pstate, const CreatedbStmt \n*stmt)\n \t\t\t\t\t(errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n \t\t\t\t\t errmsg(\"ICU locale must be specified\")));\n \t}\n+\telse\n+\t\tdbiculocale = NULL;\n\n \tif (dblocprovider == COLLPROVIDER_ICU)\n \t\tcheck_icu_locale(dbiculocale);\n\n2) CREATE DATABASE does not always require the icu locale unlike initdb \nand createdb:\n\n$ initdb -D data --locale en_US.UTF-8 --locale-provider icu\n...\ninitdb: error: ICU locale must be specified\n\n$ initdb -D data --locale en_US.UTF-8\n$ pg_ctl -D data -l logfile start\n\n$ createdb mydb --locale en_US.UTF-8 --template template0 \n--locale-provider icu\ncreatedb: error: database creation failed: ERROR: ICU locale must be \nspecified\n\n$ psql -c \"CREATE DATABASE mydb LOCALE \\\"en_US.UTF-8\\\" TEMPLATE \ntemplate0 LOCALE_PROVIDER icu\" postgres\nCREATE DATABASE\n\n$ psql -c \"CREATE DATABASE mydb TEMPLATE template0 LOCALE_PROVIDER icu\" \npostgres\nERROR: ICU locale must be specified\n\nI'm wondering if this is not a fully-supported feature (because createdb \ncreates an SQL command with LC_COLLATE and LC_CTYPE options instead of \nLOCALE option) or is it a bug in CREATE DATABASE?.. From \nsrc/backend/commands/dbcommands.c:\n\nif (dblocprovider == COLLPROVIDER_ICU && !dbiculocale)\n{\n\tif (dlocale && dlocale->arg)\n\t\tdbiculocale = defGetString(dlocale);\n}\n\n[1] \nhttps://github.com/postgres/postgres/commit/f2553d43060edb210b36c63187d52a632448e1d2\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Mon, 15 Aug 2022 15:06:32 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hi,\n\nOn Mon, Aug 15, 2022 at 03:06:32PM +0300, Marina Polyakova wrote:\n>\n> 1.1) It looks like there's a bug in the function get_db_infos\n> (src/bin/pg_upgrade/info.c), where the version of the old cluster is always\n> checked:\n>\n> if (GET_MAJOR_VERSION(old_cluster.major_version) < 1500)\n> \tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n> \t\t\t \"'c' AS datlocprovider, NULL AS daticulocale, \");\n> else\n> \tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n> \t\t\t \"datlocprovider, daticulocale, \");\n>\n> With the simple patch\n>\n> diff --git a/src/bin/pg_upgrade/info.c b/src/bin/pg_upgrade/info.c\n> index df374ce4b362b4c6c87fc1fd0e476e5d6d353d9e..53ea348e211d3ac38334292bc16cb814bc13bb87\n> 100644\n> --- a/src/bin/pg_upgrade/info.c\n> +++ b/src/bin/pg_upgrade/info.c\n> @@ -319,7 +319,7 @@ get_db_infos(ClusterInfo *cluster)\n>\n> \tsnprintf(query, sizeof(query),\n> \t\t\t \"SELECT d.oid, d.datname, d.encoding, d.datcollate, d.datctype, \");\n> -\tif (GET_MAJOR_VERSION(old_cluster.major_version) < 1500)\n> +\tif (GET_MAJOR_VERSION(cluster->major_version) < 1500)\n> \t\tsnprintf(query + strlen(query), sizeof(query) - strlen(query),\n> \t\t\t\t \"'c' AS datlocprovider, NULL AS daticulocale, \");\n> \telse\n>\n> I got the expected error during the upgrade:\n>\n> locale providers for database \"template1\" do not match: old \"libc\", new\n> \"icu\"\n> Failure, exiting\n\nGood catch. There's unfortunately not a lot of regression tests for\nICU-initialized clusters. I'm wondering if the build-farm client could be\ntaught about the locale provider rather than assuming libc. Clearly that\nwouldn't have caught this issue, but it should still increase the coverage a\nbit (I'm thinking of the recent problem with the abbreviated keys).\n\n> 1.2) It looks like the mentioned asserion in dbcommands.c conflicts with the\n> following lines earlier:\n>\n> if (dbiculocale == NULL)\n> \tdbiculocale = src_iculocale;\n>\n> The following patch works for me:\n>\n> diff --git a/src/backend/commands/dbcommands.c\n> b/src/backend/commands/dbcommands.c\n> index b31a30550b025d48ba3cc250dc4c15f41f9a80be..17a2942341e528c01182fb6d4878580f2706bec9\n> 100644\n> --- a/src/backend/commands/dbcommands.c\n> +++ b/src/backend/commands/dbcommands.c\n> @@ -1048,6 +1048,8 @@ createdb(ParseState *pstate, const CreatedbStmt *stmt)\n> \t\t\t\t\t(errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n> \t\t\t\t\t errmsg(\"ICU locale must be specified\")));\n> \t}\n> +\telse\n> +\t\tdbiculocale = NULL;\n>\n> \tif (dblocprovider == COLLPROVIDER_ICU)\n> \t\tcheck_icu_locale(dbiculocale);\n\nI think it would be better to do that in the various variable initialization.\nMaybe switch the dblocprovider and dbiculocale initialization, and only\ninitialize dbiculocale if dblocprovider is COLLPROVIDER_ICU.\n\n> 2) CREATE DATABASE does not always require the icu locale unlike initdb and\n> createdb:\n>\n> $ createdb mydb --locale en_US.UTF-8 --template template0 --locale-provider\n> icu\n> createdb: error: database creation failed: ERROR: ICU locale must be\n> specified\n>\n> $ psql -c \"CREATE DATABASE mydb LOCALE \\\"en_US.UTF-8\\\" TEMPLATE template0\n> LOCALE_PROVIDER icu\" postgres\n> CREATE DATABASE\n>\n> I'm wondering if this is not a fully-supported feature (because createdb\n> creates an SQL command with LC_COLLATE and LC_CTYPE options instead of\n> LOCALE option) or is it a bug in CREATE DATABASE?.. From\n> src/backend/commands/dbcommands.c:\n>\n> if (dblocprovider == COLLPROVIDER_ICU && !dbiculocale)\n> {\n> \tif (dlocale && dlocale->arg)\n> \t\tdbiculocale = defGetString(dlocale);\n> }\n\nThis discrepancy between createdb and CREATE DATABASE looks like an oversight,\nas createdb indeed interprets --locale as:\n\n\tif (locale)\n\t{\n\t\tif (lc_ctype)\n\t\t\tpg_fatal(\"only one of --locale and --lc-ctype can be specified\");\n\t\tif (lc_collate)\n\t\t\tpg_fatal(\"only one of --locale and --lc-collate can be specified\");\n\t\tlc_ctype = locale;\n\t\tlc_collate = locale;\n\t}\n\nAFAIK the fallback in the CREATE DATABASE case is expected as POSIX locale\nnames should be accepted by icu, so this should work for createdb too.\n\n\n", "msg_date": "Thu, 18 Aug 2022 00:53:59 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2022-08-17 19:53, Julien Rouhaud wrote:\n> Good catch. There's unfortunately not a lot of regression tests for\n> ICU-initialized clusters. I'm wondering if the build-farm client could \n> be\n> taught about the locale provider rather than assuming libc. Clearly \n> that\n> wouldn't have caught this issue, but it should still increase the \n> coverage a\n> bit (I'm thinking of the recent problem with the abbreviated keys).\n\nLooking at installchecks with different locales (e.g. see [1] with \nsv_SE.UTF-8) - why not?..\n\n>> diff --git a/src/backend/commands/dbcommands.c\n>> b/src/backend/commands/dbcommands.c\n>> index \n>> b31a30550b025d48ba3cc250dc4c15f41f9a80be..17a2942341e528c01182fb6d4878580f2706bec9\n>> 100644\n>> --- a/src/backend/commands/dbcommands.c\n>> +++ b/src/backend/commands/dbcommands.c\n>> @@ -1048,6 +1048,8 @@ createdb(ParseState *pstate, const CreatedbStmt \n>> *stmt)\n>> \t\t\t\t\t(errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n>> \t\t\t\t\t errmsg(\"ICU locale must be specified\")));\n>> \t}\n>> +\telse\n>> +\t\tdbiculocale = NULL;\n>> \n>> \tif (dblocprovider == COLLPROVIDER_ICU)\n>> \t\tcheck_icu_locale(dbiculocale);\n> \n> I think it would be better to do that in the various variable \n> initialization.\n> Maybe switch the dblocprovider and dbiculocale initialization, and only\n> initialize dbiculocale if dblocprovider is COLLPROVIDER_ICU.\n\ndiff --git a/src/backend/commands/dbcommands.c \nb/src/backend/commands/dbcommands.c\nindex \nb31a30550b025d48ba3cc250dc4c15f41f9a80be..883f381f3453142790f728a3725586cebe2e2f20 \n100644\n--- a/src/backend/commands/dbcommands.c\n+++ b/src/backend/commands/dbcommands.c\n@@ -1012,10 +1012,10 @@ createdb(ParseState *pstate, const CreatedbStmt \n*stmt)\n \t\tdbcollate = src_collate;\n \tif (dbctype == NULL)\n \t\tdbctype = src_ctype;\n-\tif (dbiculocale == NULL)\n-\t\tdbiculocale = src_iculocale;\n \tif (dblocprovider == '\\0')\n \t\tdblocprovider = src_locprovider;\n+\tif (dbiculocale == NULL && dblocprovider == COLLPROVIDER_ICU)\n+\t\tdbiculocale = src_iculocale;\n\n \t/* Some encodings are client only */\n \tif (!PG_VALID_BE_ENCODING(encoding))\n\nThen it seemed to me that it was easier to first get all the parameters \nfrom the template database as usual and then process them as needed. But \nwith your suggestion the failed assertion will check the code above more \naccurately...\n\n> This discrepancy between createdb and CREATE DATABASE looks like an \n> oversight,\n> as createdb indeed interprets --locale as:\n> \n> \tif (locale)\n> \t{\n> \t\tif (lc_ctype)\n> \t\t\tpg_fatal(\"only one of --locale and --lc-ctype can be specified\");\n> \t\tif (lc_collate)\n> \t\t\tpg_fatal(\"only one of --locale and --lc-collate can be specified\");\n> \t\tlc_ctype = locale;\n> \t\tlc_collate = locale;\n> \t}\n> \n> AFAIK the fallback in the CREATE DATABASE case is expected as POSIX \n> locale\n> names should be accepted by icu, so this should work for createdb too.\n\nOh, great, thanks!\n\n> > > I spent some time looking at the ICU api trying to figure out if using a\n> > > posix locale name (e.g. en_US) was actually compatible with an ICU locale name.\n> > > It seems that ICU accept any of 'en-us', 'en-US', 'en_us' or 'en_US' as the\n> > > same locale, but I might be wrong. I also didn't find a way to figure out how\n> > > to ask ICU if the locale identifier passed is complete garbage or not. One\n> > > sure thing is that the system collation we import are of the form 'en-us', so\n> > > it seems weird to have this form in pg_collation and by default another form in\n> > > pg_database.\n> >\n> > Yeah it seems to be inconsistent about that. The locale ID documentation\n> > appears to indicate that \"en_US\" is the canonical form, but when you ask it\n> > to list all the locales it knows about it returns \"en-US\".\n> \n> Yeah I saw that too when checking is POSIX locale names were valid, and \n> that's\n> not great.\n\nI'm sorry but IIUC pg_import_system_collations uses uloc_getAvailable to \nget the locale ID and then specifically calls uloc_toLanguageTag?..\n\n> I don't think that initdb --collation-provider icu should be allowed \n> without\n> --icu-locale, same for --collation-provider libc *with* --icu-locale.\n\n> > initdb has some specific processing to transform the default libc locale to\n> > something more appropriate, but as far as I can see creatdb / CREATE DATABASE\n> > aren't doing that. It seems inconsistent, and IMHO another reason why\n> > defaulting to the libc locale looks like a bad idea.\n> \n> This has all been removed. The separate ICU locale option should now \n> be\n> required everywhere (initdb, createdb, CREATE DATABASE).\n\nIf it's a feature and not a bug in CREATE DATABASE, why should not it \nwork in initdb too? Here we define locale/lc_collate/lc_ctype for the \nfirst 3 databases in the cluster in much the same way...\n\nP.S. FYI there seems to be a bug for very old ICU versions: in master \n(92fce4e1eda9b24d73f583fbe9b58f4e03f097a4):\n\n$ initdb -D data &&\npg_ctl -D data -l logfile start &&\npsql -c \"CREATE DATABASE mydb LOCALE \\\"C.UTF-8\\\" LOCALE_PROVIDER icu \nTEMPLATE template0\" postgres &&\npsql -c \"SELECT 1\" mydb\n\nWARNING: database \"mydb\" has a collation version mismatch\nDETAIL: The database was created using collation version 49.192.0.42, \nbut the operating system provides version 49.192.5.42.\nHINT: Rebuild all objects in this database that use the default \ncollation and run ALTER DATABASE mydb REFRESH COLLATION VERSION, or \nbuild PostgreSQL with the right library version.\n\nSee the additional output (diff_log_icu_collator_locale.patch) in the \nlogfile:\n\n2022-08-20 11:38:30.162 MSK [136546] LOG: check_icu_locale \nuloc_getDefault() en_US\n2022-08-20 11:38:30.162 MSK [136546] STATEMENT: CREATE DATABASE mydb \nLOCALE \"C.UTF-8\" LOCALE_PROVIDER icu TEMPLATE template0\n2022-08-20 11:38:30.163 MSK [136546] LOG: check_icu_locale icu_locale \nC.UTF-8 valid_locale en_US version 49.192.0.42\n2022-08-20 11:38:30.163 MSK [136546] STATEMENT: CREATE DATABASE mydb \nLOCALE \"C.UTF-8\" LOCALE_PROVIDER icu TEMPLATE template0\n2022-08-20 11:38:30.163 MSK [136546] LOG: get_collation_actual_version \nuloc_getDefault() en_US\n2022-08-20 11:38:30.163 MSK [136546] STATEMENT: CREATE DATABASE mydb \nLOCALE \"C.UTF-8\" LOCALE_PROVIDER icu TEMPLATE template0\n2022-08-20 11:38:30.163 MSK [136546] LOG: get_collation_actual_version \nicu_locale C.UTF-8 valid_locale en_US version 49.192.0.42\n2022-08-20 11:38:30.163 MSK [136546] STATEMENT: CREATE DATABASE mydb \nLOCALE \"C.UTF-8\" LOCALE_PROVIDER icu TEMPLATE template0\n2022-08-20 11:38:30.224 MSK [136548] LOG: make_icu_collator \nuloc_getDefault() c\n2022-08-20 11:38:30.225 MSK [136548] LOG: make_icu_collator icu_locale \nC.UTF-8 valid_locale root version 49.192.5.42\n2022-08-20 11:38:30.225 MSK [136548] LOG: get_collation_actual_version \nuloc_getDefault() c\n2022-08-20 11:38:30.225 MSK [136548] LOG: get_collation_actual_version \nicu_locale C.UTF-8 valid_locale root version 49.192.5.42\n2022-08-20 11:38:30.225 MSK [136548] WARNING: database \"mydb\" has a \ncollation version mismatch\n2022-08-20 11:38:30.225 MSK [136548] DETAIL: The database was created \nusing collation version 49.192.0.42, but the operating system provides \nversion 49.192.5.42.\n2022-08-20 11:38:30.225 MSK [136548] HINT: Rebuild all objects in this \ndatabase that use the default collation and run ALTER DATABASE mydb \nREFRESH COLLATION VERSION, or build PostgreSQL with the right library \nversion.\n\n[1] \nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=loach&dt=2022-08-18%2006%3A25%3A17\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Sat, 20 Aug 2022 12:41:51 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 15.08.22 14:06, Marina Polyakova wrote:\n> 1.1) It looks like there's a bug in the function get_db_infos \n> (src/bin/pg_upgrade/info.c), where the version of the old cluster is \n> always checked:\n> \n> if (GET_MAJOR_VERSION(old_cluster.major_version) < 1500)\n>     snprintf(query + strlen(query), sizeof(query) - strlen(query),\n>              \"'c' AS datlocprovider, NULL AS daticulocale, \");\n> else\n>     snprintf(query + strlen(query), sizeof(query) - strlen(query),\n>              \"datlocprovider, daticulocale, \");\n> \n> With the simple patch\n> \n> diff --git a/src/bin/pg_upgrade/info.c b/src/bin/pg_upgrade/info.c\n> index \n> df374ce4b362b4c6c87fc1fd0e476e5d6d353d9e..53ea348e211d3ac38334292bc16cb814bc13bb87 \n> 100644\n> --- a/src/bin/pg_upgrade/info.c\n> +++ b/src/bin/pg_upgrade/info.c\n> @@ -319,7 +319,7 @@ get_db_infos(ClusterInfo *cluster)\n> \n>      snprintf(query, sizeof(query),\n>               \"SELECT d.oid, d.datname, d.encoding, d.datcollate, \n> d.datctype, \");\n> -    if (GET_MAJOR_VERSION(old_cluster.major_version) < 1500)\n> +    if (GET_MAJOR_VERSION(cluster->major_version) < 1500)\n>          snprintf(query + strlen(query), sizeof(query) - strlen(query),\n>                   \"'c' AS datlocprovider, NULL AS daticulocale, \");\n>      else\n\nfixed\n\n> 1.2) It looks like the mentioned asserion in dbcommands.c conflicts with \n> the following lines earlier:\n> \n> if (dbiculocale == NULL)\n>     dbiculocale = src_iculocale;\n\nfixed\n\n> I'm wondering if this is not a fully-supported feature (because createdb \n> creates an SQL command with LC_COLLATE and LC_CTYPE options instead of \n> LOCALE option) or is it a bug in CREATE DATABASE?.. From \n> src/backend/commands/dbcommands.c:\n> \n> if (dblocprovider == COLLPROVIDER_ICU && !dbiculocale)\n> {\n>     if (dlocale && dlocale->arg)\n>         dbiculocale = defGetString(dlocale);\n> }\n\nI think this piece of code was left over from some earlier attempts to \nspecify the libc locale and the icu locale with one option, which never \nreally worked well. The CREATE DATABASE man page does not mention that \nLOCALE provides the default for ICU_LOCALE. Hence, I think we should \ndelete this.\n\n\n", "msg_date": "Mon, 22 Aug 2022 16:10:59 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2022-08-22 17:10, Peter Eisentraut wrote:\n> On 15.08.22 14:06, Marina Polyakova wrote:\n>> 1.1) It looks like there's a bug in the function get_db_infos \n>> (src/bin/pg_upgrade/info.c), where the version of the old cluster is \n>> always checked:\n>> \n>> if (GET_MAJOR_VERSION(old_cluster.major_version) < 1500)\n>>     snprintf(query + strlen(query), sizeof(query) - strlen(query),\n>>              \"'c' AS datlocprovider, NULL AS daticulocale, \");\n>> else\n>>     snprintf(query + strlen(query), sizeof(query) - strlen(query),\n>>              \"datlocprovider, daticulocale, \");\n>> \n>> With the simple patch\n>> \n>> diff --git a/src/bin/pg_upgrade/info.c b/src/bin/pg_upgrade/info.c\n>> index \n>> df374ce4b362b4c6c87fc1fd0e476e5d6d353d9e..53ea348e211d3ac38334292bc16cb814bc13bb87 \n>> 100644\n>> --- a/src/bin/pg_upgrade/info.c\n>> +++ b/src/bin/pg_upgrade/info.c\n>> @@ -319,7 +319,7 @@ get_db_infos(ClusterInfo *cluster)\n>> \n>>      snprintf(query, sizeof(query),\n>>               \"SELECT d.oid, d.datname, d.encoding, d.datcollate, \n>> d.datctype, \");\n>> -    if (GET_MAJOR_VERSION(old_cluster.major_version) < 1500)\n>> +    if (GET_MAJOR_VERSION(cluster->major_version) < 1500)\n>>          snprintf(query + strlen(query), sizeof(query) - \n>> strlen(query),\n>>                   \"'c' AS datlocprovider, NULL AS daticulocale, \");\n>>      else\n> \n> fixed\n> \n>> 1.2) It looks like the mentioned asserion in dbcommands.c conflicts \n>> with the following lines earlier:\n>> \n>> if (dbiculocale == NULL)\n>>     dbiculocale = src_iculocale;\n> \n> fixed\n> \n>> I'm wondering if this is not a fully-supported feature (because \n>> createdb creates an SQL command with LC_COLLATE and LC_CTYPE options \n>> instead of LOCALE option) or is it a bug in CREATE DATABASE?.. From \n>> src/backend/commands/dbcommands.c:\n>> \n>> if (dblocprovider == COLLPROVIDER_ICU && !dbiculocale)\n>> {\n>>     if (dlocale && dlocale->arg)\n>>         dbiculocale = defGetString(dlocale);\n>> }\n> \n> I think this piece of code was left over from some earlier attempts to\n> specify the libc locale and the icu locale with one option, which\n> never really worked well. The CREATE DATABASE man page does not\n> mention that LOCALE provides the default for ICU_LOCALE. Hence, I\n> think we should delete this.\n\nThank you!\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Mon, 22 Aug 2022 17:17:31 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Mon, Aug 22, 2022 at 04:10:59PM +0200, Peter Eisentraut wrote:\n> I think this piece of code was left over from some earlier attempts to\n> specify the libc locale and the icu locale with one option, which never\n> really worked well. The CREATE DATABASE man page does not mention that\n> LOCALE provides the default for ICU_LOCALE. Hence, I think we should delete\n> this.\n\nAs of 36f729e, is there anything left to address on this thread or\nshould this open item be closed?\n--\nMichael", "msg_date": "Tue, 23 Aug 2022 13:16:31 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "My colleague Andrew Bille found another bug in master \n(b4e936859dc441102eb0b6fb7a104f3948c90490) and REL_15_STABLE \n(2c63b0930aee1bb5c265fad4a65c9d0b62b1f9da): pg_collation.colliculocale \nis not dumped. See check_icu_locale.sh:\n\nIn the old cluster:\nSELECT collname, colliculocale FROM pg_collation WHERE collname = \n'testcoll_backwards'\n collname | colliculocale\n--------------------+-------------------\n testcoll_backwards | @colBackwards=yes\n(1 row)\n\nIn the new cluster:\nSELECT collname, colliculocale FROM pg_collation WHERE collname = \n'testcoll_backwards'\n collname | colliculocale\n--------------------+---------------\n testcoll_backwards |\n(1 row)\n\ndiff_dump_colliculocale.patch works for me.\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Tue, 23 Aug 2022 20:59:02 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Tue, Aug 23, 2022 at 08:59:02PM +0300, Marina Polyakova wrote:\n> My colleague Andrew Bille found another bug in master\n> (b4e936859dc441102eb0b6fb7a104f3948c90490) and REL_15_STABLE\n> (2c63b0930aee1bb5c265fad4a65c9d0b62b1f9da): pg_collation.colliculocale is\n> not dumped. See check_icu_locale.sh:\n> \n> In the old cluster:\n> SELECT collname, colliculocale FROM pg_collation WHERE collname =\n> 'testcoll_backwards'\n> collname | colliculocale\n> --------------------+-------------------\n> testcoll_backwards | @colBackwards=yes\n> (1 row)\n> \n> In the new cluster:\n> SELECT collname, colliculocale FROM pg_collation WHERE collname =\n> 'testcoll_backwards'\n> collname | colliculocale\n> --------------------+---------------\n> testcoll_backwards |\n> (1 row)\n> \n> diff_dump_colliculocale.patch works for me.\n\nUgh. Good catch, again! I have not tested the patch in details but\nthis looks rather sane to me on a quick read. Peter?\n--\nMichael", "msg_date": "Wed, 24 Aug 2022 13:38:44 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Wed, Aug 24, 2022 at 01:38:44PM +0900, Michael Paquier wrote:\n> On Tue, Aug 23, 2022 at 08:59:02PM +0300, Marina Polyakova wrote:\n> > My colleague Andrew Bille found another bug in master\n> > (b4e936859dc441102eb0b6fb7a104f3948c90490) and REL_15_STABLE\n> > (2c63b0930aee1bb5c265fad4a65c9d0b62b1f9da): pg_collation.colliculocale is\n> > not dumped. See check_icu_locale.sh:\n> > \n> > In the old cluster:\n> > SELECT collname, colliculocale FROM pg_collation WHERE collname =\n> > 'testcoll_backwards'\n> > collname | colliculocale\n> > --------------------+-------------------\n> > testcoll_backwards | @colBackwards=yes\n> > (1 row)\n> > \n> > In the new cluster:\n> > SELECT collname, colliculocale FROM pg_collation WHERE collname =\n> > 'testcoll_backwards'\n> > collname | colliculocale\n> > --------------------+---------------\n> > testcoll_backwards |\n> > (1 row)\n> > \n> > diff_dump_colliculocale.patch works for me.\n> \n> Ugh. Good catch, again!\n\n+1\n\n> I have not tested the patch in details but\n> this looks rather sane to me on a quick read. Peter?\n\nPatch looks good to me too.\n\n\n", "msg_date": "Wed, 24 Aug 2022 16:59:23 +0800", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 24.08.22 10:59, Julien Rouhaud wrote:\n>> I have not tested the patch in details but\n>> this looks rather sane to me on a quick read. Peter?\n> Patch looks good to me too.\n\nCommitted, thanks.\n\n(This should conclude all the issues discussed in this thread recently.)\n\n\n", "msg_date": "Wed, 24 Aug 2022 20:28:24 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Wed, Aug 24, 2022 at 08:28:24PM +0200, Peter Eisentraut wrote:\n> Committed, thanks.\n> \n> (This should conclude all the issues discussed in this thread recently.)\n\nPlease note that this open item was still listed as open. I have\nclosed it now.\n--\nMichael", "msg_date": "Tue, 30 Aug 2022 22:03:28 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hello!\n\nIMO after adding ICU for global collations [1] the behaviour of createdb \nand CREATE DATABASE is a bit inconsistent when both locale and \nlc_collate (or locale and lc_ctype) options are used:\n\n$ createdb mydb --locale C --lc-collate C --template template0\ncreatedb: error: only one of --locale and --lc-collate can be specified\n$ psql -c \"create database mydb locale = 'C' lc_collate = 'C' template = \n'template0'\" postgres\nCREATE DATABASE\n\n From the CREATE DATABASE documentation [2]:\n\nlocale\nThis is a shortcut for setting LC_COLLATE and LC_CTYPE at once. If you \nspecify this, you cannot specify either of those parameters.\n\nThe patch diff_return_back_create_database_error.patch returns back the \nremoved code for CREATE DATABASE so it behaves like createdb as \nbefore...\n\n[1] \nhttps://github.com/postgres/postgres/commit/f2553d43060edb210b36c63187d52a632448e1d2\n[2] https://www.postgresql.org/docs/devel/sql-createdatabase.html\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Mon, 05 Sep 2022 18:14:00 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "In pg14:\n|postgres=# create database a LC_COLLATE C LC_CTYPE C LOCALE C;\n|ERROR: conflicting or redundant options\n|DETAIL: LOCALE cannot be specified together with LC_COLLATE or LC_CTYPE.\n\nIn pg15:\n|postgres=# create database a LC_COLLATE \"en_US.UTF-8\" LC_CTYPE \"en_US.UTF-8\" LOCALE \"en_US.UTF-8\" ;\n|CREATE DATABASE\n\nf2553d430 actually relaxed the restriction by removing this check:\n\n- if (dlocale && (dcollate || dctype))\n- ereport(ERROR,\n- (errcode(ERRCODE_SYNTAX_ERROR),\n- errmsg(\"conflicting or redundant options\"),\n- errdetail(\"LOCALE cannot be specified together with LC_COLLATE or LC_CTYPE.\")));\n\nBut isn't the right fix to do the corresponding thing in createdb\n(relaxing the frontend restriction rather than reverting its relaxation\nin the backend).\n\ndiff --git a/src/bin/scripts/createdb.c b/src/bin/scripts/createdb.c\nindex e523e58b218..5b80e56dfd9 100644\n--- a/src/bin/scripts/createdb.c\n+++ b/src/bin/scripts/createdb.c\n@@ -159,15 +159,10 @@ main(int argc, char *argv[])\n \t\t\texit(1);\n \t}\n \n-\tif (locale)\n-\t{\n-\t\tif (lc_ctype)\n-\t\t\tpg_fatal(\"only one of --locale and --lc-ctype can be specified\");\n-\t\tif (lc_collate)\n-\t\t\tpg_fatal(\"only one of --locale and --lc-collate can be specified\");\n+\tif (locale && !lc_ctype)\n \t\tlc_ctype = locale;\n+\tif (locale && !lc_collate)\n \t\tlc_collate = locale;\n-\t}\n \n \tif (encoding)\n \t{\n\n\nBTW it's somewhat crummy that it uses a string comparison, so if you\nwrite \"UTF8\" without a dash, it says this; it took me a few minutes to\nsee the difference...\n\npostgres=# create database a LC_COLLATE \"en_US.UTF8\" LC_CTYPE \"en_US.UTF8\" LOCALE \"en_US.UTF8\";\nERROR: new collation (en_US.UTF8) is incompatible with the collation of the template database (en_US.UTF-8)\n\n\n", "msg_date": "Fri, 9 Sep 2022 11:46:25 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2022-09-09 19:46, Justin Pryzby wrote:\n> In pg14:\n> |postgres=# create database a LC_COLLATE C LC_CTYPE C LOCALE C;\n> |ERROR: conflicting or redundant options\n> |DETAIL: LOCALE cannot be specified together with LC_COLLATE or \n> LC_CTYPE.\n> \n> In pg15:\n> |postgres=# create database a LC_COLLATE \"en_US.UTF-8\" LC_CTYPE\n> \"en_US.UTF-8\" LOCALE \"en_US.UTF-8\" ;\n> |CREATE DATABASE\n> \n> f2553d430 actually relaxed the restriction by removing this check:\n> \n> - if (dlocale && (dcollate || dctype))\n> - ereport(ERROR,\n> - (errcode(ERRCODE_SYNTAX_ERROR),\n> - errmsg(\"conflicting or redundant \n> options\"),\n> - errdetail(\"LOCALE cannot be specified\n> together with LC_COLLATE or LC_CTYPE.\")));\n> \n> But isn't the right fix to do the corresponding thing in createdb\n> (relaxing the frontend restriction rather than reverting its relaxation\n> in the backend).\n> \n> diff --git a/src/bin/scripts/createdb.c b/src/bin/scripts/createdb.c\n> index e523e58b218..5b80e56dfd9 100644\n> --- a/src/bin/scripts/createdb.c\n> +++ b/src/bin/scripts/createdb.c\n> @@ -159,15 +159,10 @@ main(int argc, char *argv[])\n> \t\t\texit(1);\n> \t}\n> \n> -\tif (locale)\n> -\t{\n> -\t\tif (lc_ctype)\n> -\t\t\tpg_fatal(\"only one of --locale and --lc-ctype can be specified\");\n> -\t\tif (lc_collate)\n> -\t\t\tpg_fatal(\"only one of --locale and --lc-collate can be specified\");\n> +\tif (locale && !lc_ctype)\n> \t\tlc_ctype = locale;\n> +\tif (locale && !lc_collate)\n> \t\tlc_collate = locale;\n> -\t}\n> \n> \tif (encoding)\n> \t{\n\nI agree with you that it is more comfortable and more similar to what \nhas already been done in initdb. IMO it would be easier to do it like \nthis:\n\ndiff --git a/src/bin/scripts/createdb.c b/src/bin/scripts/createdb.c\nindex \ne523e58b2189275dc603a06324a2f28b0f49d8b7..a1482df3d981a680dd3322052e7c03ddacc8dc26 \n100644\n--- a/src/bin/scripts/createdb.c\n+++ b/src/bin/scripts/createdb.c\n@@ -161,12 +161,10 @@ main(int argc, char *argv[])\n\n \tif (locale)\n \t{\n-\t\tif (lc_ctype)\n-\t\t\tpg_fatal(\"only one of --locale and --lc-ctype can be specified\");\n-\t\tif (lc_collate)\n-\t\t\tpg_fatal(\"only one of --locale and --lc-collate can be specified\");\n-\t\tlc_ctype = locale;\n-\t\tlc_collate = locale;\n+\t\tif (!lc_ctype)\n+\t\t\tlc_ctype = locale;\n+\t\tif (!lc_collate)\n+\t\t\tlc_collate = locale;\n \t}\n\n \tif (encoding)\n\nShould we change the behaviour of createdb and CREATE DATABASE in \nprevious major versions?..\n\n> BTW it's somewhat crummy that it uses a string comparison, so if you\n> write \"UTF8\" without a dash, it says this; it took me a few minutes to\n> see the difference...\n> \n> postgres=# create database a LC_COLLATE \"en_US.UTF8\" LC_CTYPE\n> \"en_US.UTF8\" LOCALE \"en_US.UTF8\";\n> ERROR: new collation (en_US.UTF8) is incompatible with the collation\n> of the template database (en_US.UTF-8)\n\nPerhaps we could check the locale itself with the function \nnormalize_libc_locale_name (collationcmds.c). But ISTM that the current \ncheck is a safety net in case the function pg_get_encoding_from_locale \n(chklocale.c) returns -1 or PG_SQL_ASCII...\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Tue, 13 Sep 2022 08:34:16 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 13.09.22 07:34, Marina Polyakova wrote:\n> I agree with you that it is more comfortable and more similar to what \n> has already been done in initdb. IMO it would be easier to do it like this:\n> \n> diff --git a/src/bin/scripts/createdb.c b/src/bin/scripts/createdb.c\n> index \n> e523e58b2189275dc603a06324a2f28b0f49d8b7..a1482df3d981a680dd3322052e7c03ddacc8dc26 100644\n> --- a/src/bin/scripts/createdb.c\n> +++ b/src/bin/scripts/createdb.c\n> @@ -161,12 +161,10 @@ main(int argc, char *argv[])\n> \n>      if (locale)\n>      {\n> -        if (lc_ctype)\n> -            pg_fatal(\"only one of --locale and --lc-ctype can be \n> specified\");\n> -        if (lc_collate)\n> -            pg_fatal(\"only one of --locale and --lc-collate can be \n> specified\");\n> -        lc_ctype = locale;\n> -        lc_collate = locale;\n> +        if (!lc_ctype)\n> +            lc_ctype = locale;\n> +        if (!lc_collate)\n> +            lc_collate = locale;\n>      }\n> \n>      if (encoding)\n\ndone that way\n\n> Should we change the behaviour of createdb and CREATE DATABASE in \n> previous major versions?..\n\nI don't see a need for that.\n\n>> BTW it's somewhat crummy that it uses a string comparison, so if you\n>> write \"UTF8\" without a dash, it says this; it took me a few minutes to\n>> see the difference...\n>>\n>> postgres=# create database a LC_COLLATE \"en_US.UTF8\" LC_CTYPE\n>> \"en_US.UTF8\" LOCALE \"en_US.UTF8\";\n>> ERROR:  new collation (en_US.UTF8) is incompatible with the collation\n>> of the template database (en_US.UTF-8)\n> \n> Perhaps we could check the locale itself with the function \n> normalize_libc_locale_name (collationcmds.c). But ISTM that the current \n> check is a safety net in case the function pg_get_encoding_from_locale \n> (chklocale.c) returns -1 or PG_SQL_ASCII...\n\nThis is not new behavior in PG15, is it?\n\n\n\n", "msg_date": "Tue, 13 Sep 2022 14:41:41 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2022-09-13 15:41, Peter Eisentraut wrote:\n> On 13.09.22 07:34, Marina Polyakova wrote:\n>> I agree with you that it is more comfortable and more similar to what \n>> has already been done in initdb. IMO it would be easier to do it like \n>> this:\n>> \n>> diff --git a/src/bin/scripts/createdb.c b/src/bin/scripts/createdb.c\n>> index \n>> e523e58b2189275dc603a06324a2f28b0f49d8b7..a1482df3d981a680dd3322052e7c03ddacc8dc26 \n>> 100644\n>> --- a/src/bin/scripts/createdb.c\n>> +++ b/src/bin/scripts/createdb.c\n>> @@ -161,12 +161,10 @@ main(int argc, char *argv[])\n>> \n>>      if (locale)\n>>      {\n>> -        if (lc_ctype)\n>> -            pg_fatal(\"only one of --locale and --lc-ctype can be \n>> specified\");\n>> -        if (lc_collate)\n>> -            pg_fatal(\"only one of --locale and --lc-collate can be \n>> specified\");\n>> -        lc_ctype = locale;\n>> -        lc_collate = locale;\n>> +        if (!lc_ctype)\n>> +            lc_ctype = locale;\n>> +        if (!lc_collate)\n>> +            lc_collate = locale;\n>>      }\n>> \n>>      if (encoding)\n> \n> done that way\n\nThank you!\n\n>>> BTW it's somewhat crummy that it uses a string comparison, so if you\n>>> write \"UTF8\" without a dash, it says this; it took me a few minutes \n>>> to\n>>> see the difference...\n>>> \n>>> postgres=# create database a LC_COLLATE \"en_US.UTF8\" LC_CTYPE\n>>> \"en_US.UTF8\" LOCALE \"en_US.UTF8\";\n>>> ERROR:  new collation (en_US.UTF8) is incompatible with the collation\n>>> of the template database (en_US.UTF-8)\n>> \n>> Perhaps we could check the locale itself with the function \n>> normalize_libc_locale_name (collationcmds.c). But ISTM that the \n>> current check is a safety net in case the function \n>> pg_get_encoding_from_locale (chklocale.c) returns -1 or \n>> PG_SQL_ASCII...\n> \n> This is not new behavior in PG15, is it?\n\nNo, it has always existed [1] AFAICS..\n\n[1] \nhttps://github.com/postgres/postgres/commit/61d967498802ab86d8897cb3c61740d7e9d712f6\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Tue, 13 Sep 2022 18:51:39 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hello!\n\nI was surprised that it is allowed to create clusters/databases where \nthe default ICU collations do not actually work due to unsupported \nencodings:\n\n$ initdb --encoding SQL_ASCII --locale-provider icu --icu-locale en-US \n-D data &&\npg_ctl -D data -l logfile start &&\npsql -c \"SELECT 'a' < 'b'\" template1\n...\nwaiting for server to start.... done\nserver started\nERROR: encoding \"SQL_ASCII\" not supported by ICU\n\n$ createdb --encoding SQL_ASCII --locale-provider icu --icu-locale en-US \n--template template0 mydb &&\npsql -c \"SELECT 'a' < 'b'\" mydb\nERROR: encoding \"SQL_ASCII\" not supported by ICU\n\nThe patch diff_check_icu_encoding.patch prohibits the creation of such \nobjects...\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Wed, 14 Sep 2022 17:19:34 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "At Wed, 14 Sep 2022 17:19:34 +0300, Marina Polyakova <m.polyakova@postgrespro.ru> wrote in \n> Hello!\n> \n> I was surprised that it is allowed to create clusters/databases where\n> the default ICU collations do not actually work due to unsupported\n> encodings:\n> \n> $ initdb --encoding SQL_ASCII --locale-provider icu --icu-locale en-US\n> -D data &&\n> pg_ctl -D data -l logfile start &&\n> psql -c \"SELECT 'a' < 'b'\" template1\n> ...\n> waiting for server to start.... done\n> server started\n> ERROR: encoding \"SQL_ASCII\" not supported by ICU\n\nIndeed. If I did the following, the direction of the patch looks fine\nto me.\n\nIf I executed initdb as follows, I would be told to specify\n--icu-locale option.\n\n> $ initdb --encoding sql-ascii --locale-provider icu hoge\n> ...\n> initdb: error: ICU locale must be specified\n\nHowever, when I reran the command, it complains about incompatible\nencoding this time. I think it's more user-friendly to check for the\nencoding compatibility before the check for missing --icu-locale\noption.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Thu, 15 Sep 2022 15:52:10 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2022-09-15 09:52, Kyotaro Horiguchi wrote:\n> If I executed initdb as follows, I would be told to specify\n> --icu-locale option.\n> \n>> $ initdb --encoding sql-ascii --locale-provider icu hoge\n>> ...\n>> initdb: error: ICU locale must be specified\n> \n> However, when I reran the command, it complains about incompatible\n> encoding this time. I think it's more user-friendly to check for the\n> encoding compatibility before the check for missing --icu-locale\n> option.\n> \n> regards.\n\nI agree with you. Here's another version of the patch. The \nlocale/encoding checks and reports in initdb have been reordered, \nbecause now the encoding is set first and only then the ICU locale is \nchecked.\n\nP.S. While working on the patch, I discovered that UTF8 encoding is \nalways used for the ICU provider in initdb unless it is explicitly \nspecified by the user:\n\nif (!encoding && locale_provider == COLLPROVIDER_ICU)\n\tencodingid = PG_UTF8;\n\nIMO this creates additional errors for locales with other encodings:\n\n$ initdb --locale de_DE.iso885915@euro --locale-provider icu \n--icu-locale de-DE\n...\ninitdb: error: encoding mismatch\ninitdb: detail: The encoding you selected (UTF8) and the encoding that \nthe selected locale uses (LATIN9) do not match. This would lead to \nmisbehavior in various character string processing functions.\ninitdb: hint: Rerun initdb and either do not specify an encoding \nexplicitly, or choose a matching combination.\n\nAnd ICU supports many encodings, see the contents of pg_enc2icu_tbl in \nencnames.c...\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 15 Sep 2022 18:41:31 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Wed, Sep 14, 2022 at 05:19:34PM +0300, Marina Polyakova wrote:\n> I was surprised that it is allowed to create clusters/databases where the\n> default ICU collations do not actually work due to unsupported encodings:\n> \n> $ initdb --encoding SQL_ASCII --locale-provider icu --icu-locale en-US -D\n> data &&\n> pg_ctl -D data -l logfile start &&\n> psql -c \"SELECT 'a' < 'b'\" template1\n> ...\n> waiting for server to start.... done\n> server started\n> ERROR: encoding \"SQL_ASCII\" not supported by ICU\n> \n> $ createdb --encoding SQL_ASCII --locale-provider icu --icu-locale en-US\n> --template template0 mydb &&\n> psql -c \"SELECT 'a' < 'b'\" mydb\n> ERROR: encoding \"SQL_ASCII\" not supported by ICU\n> \n> The patch diff_check_icu_encoding.patch prohibits the creation of such\n> objects...\n\nAgreed that it is a bit confusing to get this type of error after the\ndatabase has been created when querying it due to a mix of unsupported\noptions. Peter?\n--\nMichael", "msg_date": "Fri, 16 Sep 2022 11:28:09 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "At Thu, 15 Sep 2022 18:41:31 +0300, Marina Polyakova <m.polyakova@postgrespro.ru> wrote in \n> P.S. While working on the patch, I discovered that UTF8 encoding is\n> always used for the ICU provider in initdb unless it is explicitly\n> specified by the user:\n> \n> if (!encoding && locale_provider == COLLPROVIDER_ICU)\n> \tencodingid = PG_UTF8;\n> \n> IMO this creates additional errors for locales with other encodings:\n> \n> $ initdb --locale de_DE.iso885915@euro --locale-provider icu\n> --icu-locale de-DE\n> ...\n> initdb: error: encoding mismatch\n> initdb: detail: The encoding you selected (UTF8) and the encoding that\n> the selected locale uses (LATIN9) do not match. This would lead to\n> misbehavior in various character string processing functions.\n> initdb: hint: Rerun initdb and either do not specify an encoding\n> explicitly, or choose a matching combination.\n> \n> And ICU supports many encodings, see the contents of pg_enc2icu_tbl in\n> encnames.c...\n\nIt seems to me the best default that fits almost all cases using icu\nlocales.\n\nSo, we need to specify encoding explicitly in that case.\n\n$ initdb --encoding iso-8859-15 --locale de_DE.iso885915@euro --locale-provider icu --icu-locale de-DE\n\nHowever, I think it is hardly understantable from the documentation.\n\n(I checked this using euc-jp [1] so it might be wrong..)\n\n[1] initdb --encoding euc-jp --locale ja_JP.eucjp --locale-provider icu --icu-locale ja-x-icu\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 16 Sep 2022 13:55:19 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2022-09-15 09:52, Kyotaro Horiguchi wrote:\n> If I executed initdb as follows, I would be told to specify\n> --icu-locale option.\n> \n>> $ initdb --encoding sql-ascii --locale-provider icu hoge\n>> ...\n>> initdb: error: ICU locale must be specified\n> \n> However, when I reran the command, it complains about incompatible\n> encoding this time. I think it's more user-friendly to check for the\n> encoding compatibility before the check for missing --icu-locale\n> option.\n> \n> regards.\n\nIn continuation of options check: AFAICS the following checks in initdb\n\n\tif (locale_provider == COLLPROVIDER_ICU)\n\t{\n\t\tif (!icu_locale)\n\t\t\tpg_fatal(\"ICU locale must be specified\");\n\n\t\t/*\n\t\t * In supported builds, the ICU locale ID will be checked by the\n\t\t * backend during post-bootstrap initialization.\n\t\t */\n#ifndef USE_ICU\n\t\tpg_fatal(\"ICU is not supported in this build\");\n#endif\n\t}\n\nare executed approximately when they are executed in create database \nafter getting all the necessary data from the template database:\n\nif (dblocprovider == COLLPROVIDER_ICU)\n{\n\t/*\n\t * This would happen if template0 uses the libc provider but the new\n\t * database uses icu.\n\t */\n\tif (!dbiculocale)\n\t\tereport(ERROR,\n\t\t\t\t(errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n\t\t\t\t errmsg(\"ICU locale must be specified\")));\n}\n\nif (dblocprovider == COLLPROVIDER_ICU)\n\tcheck_icu_locale(dbiculocale);\n\nBut perhaps the check that --icu-locale cannot be specified unless \nlocale provider icu is chosen should also be moved here? So all these \nchecks will be in one place and it will use the provider from the \ntemplate database (which could be icu):\n\n$ initdb --locale-provider icu --icu-locale en-US -D data &&\npg_ctl -D data -l logfile start &&\ncreatedb --icu-locale ru-RU --template template0 mydb\n...\ncreatedb: error: database creation failed: ERROR: ICU locale cannot be \nspecified unless locale provider is ICU\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Fri, 16 Sep 2022 09:49:28 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2022-09-16 07:55, Kyotaro Horiguchi wrote:\n> At Thu, 15 Sep 2022 18:41:31 +0300, Marina Polyakova\n> <m.polyakova@postgrespro.ru> wrote in\n>> P.S. While working on the patch, I discovered that UTF8 encoding is\n>> always used for the ICU provider in initdb unless it is explicitly\n>> specified by the user:\n>> \n>> if (!encoding && locale_provider == COLLPROVIDER_ICU)\n>> \tencodingid = PG_UTF8;\n>> \n>> IMO this creates additional errors for locales with other encodings:\n>> \n>> $ initdb --locale de_DE.iso885915@euro --locale-provider icu\n>> --icu-locale de-DE\n>> ...\n>> initdb: error: encoding mismatch\n>> initdb: detail: The encoding you selected (UTF8) and the encoding that\n>> the selected locale uses (LATIN9) do not match. This would lead to\n>> misbehavior in various character string processing functions.\n>> initdb: hint: Rerun initdb and either do not specify an encoding\n>> explicitly, or choose a matching combination.\n>> \n>> And ICU supports many encodings, see the contents of pg_enc2icu_tbl in\n>> encnames.c...\n> \n> It seems to me the best default that fits almost all cases using icu\n> locales.\n> \n> So, we need to specify encoding explicitly in that case.\n> \n> $ initdb --encoding iso-8859-15 --locale de_DE.iso885915@euro\n> --locale-provider icu --icu-locale de-DE\n> \n> However, I think it is hardly understantable from the documentation.\n> \n> (I checked this using euc-jp [1] so it might be wrong..)\n> \n> [1] initdb --encoding euc-jp --locale ja_JP.eucjp --locale-provider\n> icu --icu-locale ja-x-icu\n> \n> regards.\n\nThank you!\n\nIMO it is hardly understantable from the program output either - it \nlooks like I manually chose the encoding UTF8. Maybe first inform about \nselected encoding?..\n\ndiff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c\nindex \n6aeec8d426c52414b827686781c245291f27ed1f..348bbbeba0f5bc7ff601912bf883510d580b814c \n100644\n--- a/src/bin/initdb/initdb.c\n+++ b/src/bin/initdb/initdb.c\n@@ -2310,7 +2310,11 @@ setup_locale_encoding(void)\n \t}\n\n \tif (!encoding && locale_provider == COLLPROVIDER_ICU)\n+\t{\n \t\tencodingid = PG_UTF8;\n+\t\tprintf(_(\"The default database encoding has been set to \\\"%s\\\" for a \nbetter experience with the ICU provider.\\n\"),\n+\t\t\t pg_encoding_to_char(encodingid));\n+\t}\n \telse if (!encoding)\n \t{\n \t\tint\t\t\tctype_enc;\n\nISTM that such choices (e.g. UTF8 for Windows in some cases) are \ndescribed in the documentation [1] as\n\nBy default, initdb uses the locale provider libc, takes the locale \nsettings from the environment, and determines the encoding from the \nlocale settings. This is almost always sufficient, unless there are \nspecial requirements.\n\n[1] https://www.postgresql.org/docs/devel/app-initdb.html\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Fri, 16 Sep 2022 10:31:42 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 15.09.22 17:41, Marina Polyakova wrote:\n> I agree with you. Here's another version of the patch. The \n> locale/encoding checks and reports in initdb have been reordered, \n> because now the encoding is set first and only then the ICU locale is \n> checked.\n\nI committed something based on the first version of your patch. This \nreordering of the messages here was a little too much surgery for me at \nthis point. For instance, there are also messages in #ifdef WIN32 code \nthat would need to be reordered as well. I kept the overall structure \nof the code the same and just inserted the additional proposed checks.\n\nIf you want to pursue the reordering of the checks and messages overall, \na patch for the master branch could be considered.\n\n\n", "msg_date": "Fri, 16 Sep 2022 09:56:31 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 16.09.22 09:31, Marina Polyakova wrote:\n> IMO it is hardly understantable from the program output either - it \n> looks like I manually chose the encoding UTF8. Maybe first inform about \n> selected encoding?..\n\nYes, I included something like that in the patch just committed.\n\n> diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c\n> index \n> 6aeec8d426c52414b827686781c245291f27ed1f..348bbbeba0f5bc7ff601912bf883510d580b814c 100644\n> --- a/src/bin/initdb/initdb.c\n> +++ b/src/bin/initdb/initdb.c\n> @@ -2310,7 +2310,11 @@ setup_locale_encoding(void)\n>      }\n> \n>      if (!encoding && locale_provider == COLLPROVIDER_ICU)\n> +    {\n>          encodingid = PG_UTF8;\n> +        printf(_(\"The default database encoding has been set to \\\"%s\\\" \n> for a better experience with the ICU provider.\\n\"),\n> +               pg_encoding_to_char(encodingid));\n> +    }\n>      else if (!encoding)\n>      {\n>          int            ctype_enc;\n\n\n\n", "msg_date": "Fri, 16 Sep 2022 09:57:39 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "At Fri, 16 Sep 2022 09:49:28 +0300, Marina Polyakova <m.polyakova@postgrespro.ru> wrote in \n> On 2022-09-15 09:52, Kyotaro Horiguchi wrote:\n> > However, when I reran the command, it complains about incompatible\n> > encoding this time. I think it's more user-friendly to check for the\n> > encoding compatibility before the check for missing --icu-locale\n> > option.\n> > regards.\n> \n> In continuation of options check: AFAICS the following checks in\n> initdb\n> \n> \tif (locale_provider == COLLPROVIDER_ICU)\n> \t{\n> \t\tif (!icu_locale)\n> \t\t\tpg_fatal(\"ICU locale must be specified\");\n> \n> \t\t/*\n> \t\t * In supported builds, the ICU locale ID will be checked by the\n> \t\t * backend during post-bootstrap initialization.\n> \t\t */\n> #ifndef USE_ICU\n> \t\tpg_fatal(\"ICU is not supported in this build\");\n> #endif\n> \t}\n> \n> are executed approximately when they are executed in create database\n> after getting all the necessary data from the template database:\n\ninitdb doesn't work that way, but anyway, I realized that I am\nproposing to move that code in setlocales() to the caller function as\nthe result. I don't think setlocales() is the place for the code\nbecause icu locale has no business with what the function does. That\nbeing said there's no obvious reason we *need* to move the code out to\nits caller.\n\n> if (dblocprovider == COLLPROVIDER_ICU)\n> {\n> \t/*\n> \t * This would happen if template0 uses the libc provider but the new\n> \t * database uses icu.\n> \t */\n> \tif (!dbiculocale)\n> \t\tereport(ERROR,\n> \t\t\t\t(errcode(ERRCODE_INVALID_PARAMETER_VALUE),\n> \t\t\t\t errmsg(\"ICU locale must be specified\")));\n> }\n> \n> if (dblocprovider == COLLPROVIDER_ICU)\n> \tcheck_icu_locale(dbiculocale);\n> \n> But perhaps the check that --icu-locale cannot be specified unless\n> locale provider icu is chosen should also be moved here? So all these\n> checks will be in one place and it will use the provider from the\n> template database (which could be icu):\n> \n> $ initdb --locale-provider icu --icu-locale en-US -D data &&\n> pg_ctl -D data -l logfile start &&\n> createdb --icu-locale ru-RU --template template0 mydb\n> ...\n> createdb: error: database creation failed: ERROR: ICU locale cannot be\n> specified unless locale provider is ICU\n\nAnd, I realized that this causes bigger churn than I thought. So, I'm\nsorry but I withdraw the comment.\n\nThus the first proposed patch will be more or less the direction we\nwould go. And the patch looks good to me as a whole.\n\n+\t\t\t\t\t errmsg(\"encoding \\\"%s\\\" is not supported with ICU provider\",\n\n+\t\tpg_log_error(\"encoding \\\"%s\\\" is not supported with ICU provider\",\n+\t\t\t\t\t pg_encoding_to_char(encodingid));\n\nI might be wrong, but the messages look wrong to me. The alternatives\nbelow might work.\n\n\"encoding \\\"%s\\\" is not supported by ICU\"\n\"encoding \\\"%s\\\" cannot be used for/with ICU locales\"\n\n+\t\tpg_log_error_hint(\"Rerun %s and choose a matching combination.\",\n+\t\t\t\t\t\t progname);\n\nThis doesn't seem to provide users with useful information.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 16 Sep 2022 17:11:16 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "At Fri, 16 Sep 2022 09:56:31 +0200, Peter Eisentraut <peter.eisentraut@enterprisedb.com> wrote in \n> On 15.09.22 17:41, Marina Polyakova wrote:\n> > I agree with you. Here's another version of the patch. The\n> > locale/encoding checks and reports in initdb have been reordered,\n> > because now the encoding is set first and only then the ICU locale is\n> > checked.\n> \n> I committed something based on the first version of your patch. This\n> reordering of the messages here was a little too much surgery for me\n> at this point. For instance, there are also messages in #ifdef WIN32\n> code that would need to be reordered as well. I kept the overall\n> structure of the code the same and just inserted the additional\n> proposed checks.\n\nYeah, as I sent just before, I reached the same conclusion.\n\n> If you want to pursue the reordering of the checks and messages\n> overall, a patch for the master branch could be considered.\n\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 16 Sep 2022 17:14:25 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 16.09.22 08:49, Marina Polyakova wrote:\n> But perhaps the check that --icu-locale cannot be specified unless \n> locale provider icu is chosen should also be moved here? So all these \n> checks will be in one place and it will use the provider from the \n> template database (which could be icu):\n> \n> $ initdb --locale-provider icu --icu-locale en-US -D data &&\n> pg_ctl -D data -l logfile start &&\n> createdb --icu-locale ru-RU --template template0 mydb\n> ...\n> createdb: error: database creation failed: ERROR:  ICU locale cannot be \n> specified unless locale provider is ICU\n\nCan you be more specific about what you are proposing here? I'm not \nfollowing.\n\n\n\n", "msg_date": "Sat, 17 Sep 2022 06:58:36 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2022-09-16 10:57, Peter Eisentraut wrote:\n> On 16.09.22 09:31, Marina Polyakova wrote:\n>> IMO it is hardly understantable from the program output either - it \n>> looks like I manually chose the encoding UTF8. Maybe first inform \n>> about selected encoding?..\n> \n> Yes, I included something like that in the patch just committed.\n> \n>> diff --git a/src/bin/initdb/initdb.c b/src/bin/initdb/initdb.c\n>> index \n>> 6aeec8d426c52414b827686781c245291f27ed1f..348bbbeba0f5bc7ff601912bf883510d580b814c \n>> 100644\n>> --- a/src/bin/initdb/initdb.c\n>> +++ b/src/bin/initdb/initdb.c\n>> @@ -2310,7 +2310,11 @@ setup_locale_encoding(void)\n>>      }\n>> \n>>      if (!encoding && locale_provider == COLLPROVIDER_ICU)\n>> +    {\n>>          encodingid = PG_UTF8;\n>> +        printf(_(\"The default database encoding has been set to \n>> \\\"%s\\\" for a better experience with the ICU provider.\\n\"),\n>> +               pg_encoding_to_char(encodingid));\n>> +    }\n>>      else if (!encoding)\n>>      {\n>>          int            ctype_enc;\n\nThank you!\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Sat, 17 Sep 2022 09:25:00 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2022-09-16 11:11, Kyotaro Horiguchi wrote:\n> At Fri, 16 Sep 2022 09:49:28 +0300, Marina Polyakova\n> <m.polyakova@postgrespro.ru> wrote in\n>> In continuation of options check: AFAICS the following checks in\n>> initdb\n>> \n>> \tif (locale_provider == COLLPROVIDER_ICU)\n>> \t{\n>> \t\tif (!icu_locale)\n>> \t\t\tpg_fatal(\"ICU locale must be specified\");\n>> \n>> \t\t/*\n>> \t\t * In supported builds, the ICU locale ID will be checked by the\n>> \t\t * backend during post-bootstrap initialization.\n>> \t\t */\n>> #ifndef USE_ICU\n>> \t\tpg_fatal(\"ICU is not supported in this build\");\n>> #endif\n>> \t}\n>> \n>> are executed approximately when they are executed in create database\n>> after getting all the necessary data from the template database:\n> \n> initdb doesn't work that way, but anyway, I realized that I am\n> proposing to move that code in setlocales() to the caller function as\n> the result. I don't think setlocales() is the place for the code\n> because icu locale has no business with what the function does. That\n> being said there's no obvious reason we *need* to move the code out to\n> its caller.\n\nExcuse me, but could you explain your last sentence in more detail? I \nread that this code is not for setlocales and then - that it should not \nmoved from here, so I'm confused...\n\n> +\t\t\t\t\t errmsg(\"encoding \\\"%s\\\" is not supported with ICU provider\",\n> \n> +\t\tpg_log_error(\"encoding \\\"%s\\\" is not supported with ICU provider\",\n> +\t\t\t\t\t pg_encoding_to_char(encodingid));\n> \n> I might be wrong, but the messages look wrong to me. The alternatives\n> below might work.\n> \n> \"encoding \\\"%s\\\" is not supported by ICU\"\n> \"encoding \\\"%s\\\" cannot be used for/with ICU locales\"\n\nThe message indicates that the selected encoding cannot be used with the \nICU provider because it does not support it. But if the text of the \nmessage becomes better and clearer, I will only be glad.\n\n> +\t\tpg_log_error_hint(\"Rerun %s and choose a matching combination.\",\n> +\t\t\t\t\t\t progname);\n> \n> This doesn't seem to provide users with useful information.\n\nIt was commited in more verbose form:\n\npg_log_error_hint(\"Rerun %s and either do not specify an encoding \nexplicitly, \"\n\t\t\t\t \"or choose a matching combination.\",\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Sat, 17 Sep 2022 10:05:32 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Thanks to Kyotaro Horiguchi review we found out that there're \ninteresting cases due to the order of some ICU checks:\n\n1. ICU locale vs supported encoding:\n\n1.1.\n\nOn 2022-09-15 09:52, Kyotaro Horiguchi wrote:\n> If I executed initdb as follows, I would be told to specify\n> --icu-locale option.\n> \n>> $ initdb --encoding sql-ascii --locale-provider icu hoge\n>> ...\n>> initdb: error: ICU locale must be specified\n> \n> However, when I reran the command, it complains about incompatible\n> encoding this time. I think it's more user-friendly to check for the\n> encoding compatibility before the check for missing --icu-locale\n> option.\n\n1.2. (ok?)\n\n$ initdb --encoding sql-ascii --icu-locale en-US hoge\ninitdb: error: --icu-locale cannot be specified unless locale provider \n\"icu\" is chosen\n\n$ initdb --encoding sql-ascii --icu-locale en-US --locale-provider icu \nhoge\n...\ninitdb: error: encoding mismatch\ninitdb: detail: The encoding you selected (SQL_ASCII) is not supported \nwith the ICU provider.\ninitdb: hint: Rerun initdb and either do not specify an encoding \nexplicitly, or choose a matching combination.\n\n$ createdb --encoding sql-ascii --icu-locale en-US hoge\ncreatedb: error: database creation failed: ERROR: ICU locale cannot be \nspecified unless locale provider is ICU\n$ createdb --encoding sql-ascii --icu-locale en-US --locale-provider icu \nhoge\ncreatedb: error: database creation failed: ERROR: encoding \"SQL_ASCII\" \nis not supported with ICU provider\n\n2. For builds without ICU:\n\n2.1.\n\n$ initdb --locale-provider icu hoge\n...\ninitdb: error: ICU locale must be specified\n\n$ initdb --locale-provider icu --icu-locale en-US hoge\n...\ninitdb: error: ICU is not supported in this build\n\n$ createdb --locale-provider icu hoge\ncreatedb: error: database creation failed: ERROR: ICU locale must be \nspecified\n\n$ createdb --locale-provider icu --icu-locale en-US hoge\ncreatedb: error: database creation failed: ERROR: ICU is not supported \nin this build\n\nIMO, it would be more user-friendly to inform an unsupported build in \nthe first runs too..\n\n2.2. (ok?)\n\n$ initdb --icu-locale en-US hoge\ninitdb: error: --icu-locale cannot be specified unless locale provider \n\"icu\" is chosen\n$ initdb --icu-locale en-US --locale-provider icu hoge\n...\ninitdb: error: ICU is not supported in this build\n\n$ createdb --icu-locale en-US hoge\ncreatedb: error: database creation failed: ERROR: ICU locale cannot be \nspecified unless locale provider is ICU\n$ createdb --icu-locale en-US --locale-provider icu hoge\ncreatedb: error: database creation failed: ERROR: ICU is not supported \nin this build\n\n2.3.\n\n$ createdb --locale-provider icu --icu-locale en-US --encoding sql-ascii \nhoge\ncreatedb: error: database creation failed: ERROR: encoding \"SQL_ASCII\" \nis not supported with ICU provider\n$ createdb --locale-provider icu --icu-locale en-US --encoding utf8 hoge\ncreatedb: error: database creation failed: ERROR: ICU is not supported \nin this build\n\nIMO, it would be more user-friendly to inform an unsupported build in \nthe first run too..\n\n3.\n\nThe locale provider is ICU, but it has not yet been set from the \ntemplate database:\n\n> $ initdb --locale-provider icu --icu-locale en-US -D data &&\n> pg_ctl -D data -l logfile start &&\n> createdb --icu-locale ru-RU --template template0 mydb\n> ...\n> createdb: error: database creation failed: ERROR: ICU locale cannot be\n> specified unless locale provider is ICU\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Sat, 17 Sep 2022 11:33:30 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2022-09-16 10:56, Peter Eisentraut wrote:\n> On 15.09.22 17:41, Marina Polyakova wrote:\n>> I agree with you. Here's another version of the patch. The \n>> locale/encoding checks and reports in initdb have been reordered, \n>> because now the encoding is set first and only then the ICU locale is \n>> checked.\n> \n> I committed something based on the first version of your patch. This\n> reordering of the messages here was a little too much surgery for me\n> at this point. For instance, there are also messages in #ifdef WIN32\n> code that would need to be reordered as well. I kept the overall\n> structure of the code the same and just inserted the additional\n> proposed checks.\n> \n> If you want to pursue the reordering of the checks and messages\n> overall, a patch for the master branch could be considered.\n\nThank you! I already wrote about the order of the ICU checks in \ninitdb/create database, they were the only reason to propose such \nchanges...\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Sat, 17 Sep 2022 11:42:24 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 17.09.22 10:33, Marina Polyakova wrote:\n> Thanks to Kyotaro Horiguchi review we found out that there're \n> interesting cases due to the order of some ICU checks:\n> \n> 1. ICU locale vs supported encoding:\n> \n> 1.1.\n> \n> On 2022-09-15 09:52, Kyotaro Horiguchi wrote:\n>> If I executed initdb as follows, I would be told to specify\n>> --icu-locale option.\n>>\n>>> $ initdb --encoding sql-ascii --locale-provider icu hoge\n>>> ...\n>>> initdb: error: ICU locale must be specified\n>>\n>> However, when I reran the command, it complains about incompatible\n>> encoding this time.  I think it's more user-friendly to check for the\n>> encoding compatibility before the check for missing --icu-locale\n>> option.\n\nThis a valid point, but it would require quite a bit of work to move all \nthose checks around and re-verify the result, so I don't want to do it \nin PG15.\n\n> 1.2. (ok?)\n> \n> $ initdb --encoding sql-ascii --icu-locale en-US hoge\n> initdb: error: --icu-locale cannot be specified unless locale provider \n> \"icu\" is chosen\n> \n> $ initdb --encoding sql-ascii --icu-locale en-US --locale-provider icu hoge\n> ...\n> initdb: error: encoding mismatch\n> initdb: detail: The encoding you selected (SQL_ASCII) is not supported \n> with the ICU provider.\n> initdb: hint: Rerun initdb and either do not specify an encoding \n> explicitly, or choose a matching combination.\n> \n> $ createdb --encoding sql-ascii --icu-locale en-US hoge\n> createdb: error: database creation failed: ERROR:  ICU locale cannot be \n> specified unless locale provider is ICU\n> $ createdb --encoding sql-ascii --icu-locale en-US --locale-provider icu \n> hoge\n> createdb: error: database creation failed: ERROR:  encoding \"SQL_ASCII\" \n> is not supported with ICU provider\n\nI don't see a problem here.\n\n> 2. For builds without ICU:\n> \n> 2.1.\n> \n> $ initdb --locale-provider icu hoge\n> ...\n> initdb: error: ICU locale must be specified\n> \n> $ initdb --locale-provider icu --icu-locale en-US hoge\n> ...\n> initdb: error: ICU is not supported in this build\n> \n> $ createdb --locale-provider icu hoge\n> createdb: error: database creation failed: ERROR:  ICU locale must be \n> specified\n> \n> $ createdb --locale-provider icu --icu-locale en-US hoge\n> createdb: error: database creation failed: ERROR:  ICU is not supported \n> in this build\n> \n> IMO, it would be more user-friendly to inform an unsupported build in \n> the first runs too..\n\nAgain, this would require reorganizing a bunch of code to get some \ncosmetic benefit, which isn't a good idea now for PG15.\n\n> 2.2. (ok?)\n> 2.3.\n\nsame here\n\n> 3.\n> \n> The locale provider is ICU, but it has not yet been set from the \n> template database:\n> \n>> $ initdb --locale-provider icu --icu-locale en-US -D data &&\n>> pg_ctl -D data -l logfile start &&\n>> createdb --icu-locale ru-RU --template template0 mydb\n>> ...\n>> createdb: error: database creation failed: ERROR:  ICU locale cannot be\n>> specified unless locale provider is ICU\n\nPlease see attached patch for a fix. Does that work for you?", "msg_date": "Tue, 20 Sep 2022 05:59:04 -0400", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2022-09-20 12:59, Peter Eisentraut wrote:\n> On 17.09.22 10:33, Marina Polyakova wrote:\n>> 3.\n>> \n>> The locale provider is ICU, but it has not yet been set from the \n>> template database:\n>> \n>>> $ initdb --locale-provider icu --icu-locale en-US -D data &&\n>>> pg_ctl -D data -l logfile start &&\n>>> createdb --icu-locale ru-RU --template template0 mydb\n>>> ...\n>>> createdb: error: database creation failed: ERROR:  ICU locale cannot \n>>> be\n>>> specified unless locale provider is ICU\n> \n> Please see attached patch for a fix. Does that work for you?\n\nYes, it works. The following test checks this fix:\n\ndiff --git a/src/bin/scripts/t/020_createdb.pl \nb/src/bin/scripts/t/020_createdb.pl\nindex \nb87d8fc63b5246b02bcd4499aae815269b60df7c..c2464a99618cd7ca5616cc21121e1e4379b52baf \n100644\n--- a/src/bin/scripts/t/020_createdb.pl\n+++ b/src/bin/scripts/t/020_createdb.pl\n@@ -71,6 +71,14 @@ if ($ENV{with_icu} eq 'yes')\n \t$node2->command_ok(\n \t\t[ 'createdb', '-T', 'template0', '--locale-provider=libc', 'foobar55' \n],\n \t\t'create database with libc provider from template database with icu \nprovider');\n+\n+\t$node2->command_ok(\n+\t\t[\n+\t\t\t'createdb', '-T', 'template0', '--icu-locale',\n+\t\t\t'en-US', 'foobar56'\n+\t\t],\n+\t\t'create database with icu locale from template database with icu \nprovider'\n+\t);\n }\n else\n {\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Wed, 21 Sep 2022 09:50:55 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 21.09.22 08:50, Marina Polyakova wrote:\n> On 2022-09-20 12:59, Peter Eisentraut wrote:\n>> On 17.09.22 10:33, Marina Polyakova wrote:\n>>> 3.\n>>>\n>>> The locale provider is ICU, but it has not yet been set from the \n>>> template database:\n>>>\n>>>> $ initdb --locale-provider icu --icu-locale en-US -D data &&\n>>>> pg_ctl -D data -l logfile start &&\n>>>> createdb --icu-locale ru-RU --template template0 mydb\n>>>> ...\n>>>> createdb: error: database creation failed: ERROR:  ICU locale cannot be\n>>>> specified unless locale provider is ICU\n>>\n>> Please see attached patch for a fix.  Does that work for you?\n> \n> Yes, it works. The following test checks this fix:\n\nCommitted with that test, thanks. I think that covers all the ICU \nissues you reported for PG15 for now?\n\n\n\n", "msg_date": "Wed, 21 Sep 2022 10:53:00 -0400", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2022-09-21 17:53, Peter Eisentraut wrote:\n> Committed with that test, thanks. I think that covers all the ICU\n> issues you reported for PG15 for now?\n\nI thought about the order of the ICU checks - if it is ok to check that \nthe selected encoding is supported by ICU after printing all the locale \n& encoding information, why not to move almost all the ICU checks \nhere?..\n\nExamples of the work of the attached patch:\n\n1. ICU locale vs supported encoding:\n\n1.1.\n\n$ initdb --encoding sql-ascii --locale-provider icu hoge\n...\ninitdb: error: encoding mismatch\ninitdb: detail: The encoding you selected (SQL_ASCII) is not supported \nwith the ICU provider.\ninitdb: hint: Rerun initdb and either do not specify an encoding \nexplicitly, or choose a matching combination.\n\n1.2. (like before)\n\n$ initdb --encoding sql-ascii --icu-locale en-US hoge\ninitdb: error: --icu-locale cannot be specified unless locale provider \n\"icu\" is chosen\n\n$ createdb --encoding sql-ascii --icu-locale en-US hoge\ncreatedb: error: database creation failed: ERROR: ICU locale cannot be \nspecified unless locale provider is ICU\n\n2. For builds without ICU:\n\n2.1.\n\n$ initdb --locale-provider icu hoge\n...\ninitdb: error: ICU is not supported in this build\n\n$ createdb --locale-provider icu hoge\ncreatedb: error: database creation failed: ERROR: ICU is not supported \nin this build\n\n2.2. (like before)\n\n$ initdb --icu-locale en-US hoge\ninitdb: error: --icu-locale cannot be specified unless locale provider \n\"icu\" is chosen\n\n$ createdb --icu-locale en-US hoge\ncreatedb: error: database creation failed: ERROR: ICU locale cannot be \nspecified unless locale provider is ICU\n\n2.3.\n\n$ createdb --locale-provider icu --icu-locale en-US --encoding sql-ascii \nhoge\ncreatedb: error: database creation failed: ERROR: ICU is not supported \nin this build\n\n4. About errors in initdb:\n\n4.1. If icu_locale is not specified, but it is required, then we get \nthis:\n\n$ initdb --locale-provider icu hoge\nThe files belonging to this database system will be owned by user \n\"marina\".\nThis user must also own the server process.\n\nThe database cluster will be initialized with this locale configuration:\n provider: icu\n LC_COLLATE: en_US.UTF-8\n LC_CTYPE: en_US.UTF-8\n LC_MESSAGES: en_US.UTF-8\n LC_MONETARY: ru_RU.UTF-8\n LC_NUMERIC: ru_RU.UTF-8\n LC_TIME: ru_RU.UTF-8\nThe default database encoding has been set to \"UTF8\".\ninitdb: error: ICU locale must be specified\n\nAlmost the same if ICU is not supported in this build:\n\n$ initdb --locale-provider icu hoge\nThe files belonging to this database system will be owned by user \n\"marina\".\nThis user must also own the server process.\n\nThe database cluster will be initialized with this locale configuration:\n provider: icu\n LC_COLLATE: en_US.UTF-8\n LC_CTYPE: en_US.UTF-8\n LC_MESSAGES: en_US.UTF-8\n LC_MONETARY: ru_RU.UTF-8\n LC_NUMERIC: ru_RU.UTF-8\n LC_TIME: ru_RU.UTF-8\nThe default database encoding has been set to \"UTF8\".\ninitdb: error: ICU is not supported in this build\n\n4.2. If icu_locale is specified for the wrong provider, the error will \nbe at the beginning of the program start as before:\n\n$ initdb --icu-locale en-US hoge\ninitdb: error: --icu-locale cannot be specified unless locale provider \n\"icu\" is chosen\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 22 Sep 2022 21:06:07 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 22.09.22 20:06, Marina Polyakova wrote:\n> On 2022-09-21 17:53, Peter Eisentraut wrote:\n>> Committed with that test, thanks.  I think that covers all the ICU\n>> issues you reported for PG15 for now?\n> \n> I thought about the order of the ICU checks - if it is ok to check that \n> the selected encoding is supported by ICU after printing all the locale \n> & encoding information, why not to move almost all the ICU checks here?..\n\nIt's possible that we can do better, but I'm not going to add things \nlike that to PG 15 at this point unless it fixes a faulty behavior.\n\n\n\n", "msg_date": "Sat, 1 Oct 2022 14:07:29 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On 2022-10-01 15:07, Peter Eisentraut wrote:\n> On 22.09.22 20:06, Marina Polyakova wrote:\n>> On 2022-09-21 17:53, Peter Eisentraut wrote:\n>>> Committed with that test, thanks.  I think that covers all the ICU\n>>> issues you reported for PG15 for now?\n>> \n>> I thought about the order of the ICU checks - if it is ok to check \n>> that the selected encoding is supported by ICU after printing all the \n>> locale & encoding information, why not to move almost all the ICU \n>> checks here?..\n> \n> It's possible that we can do better, but I'm not going to add things\n> like that to PG 15 at this point unless it fixes a faulty behavior.\n\nWill PG 15 always have this order of ICU checks, is the current \nbehaviour correct enough? On the other hand, there may be a better fix \nfor PG 16+ and not all changes can be backported...\n\nOn 2022-09-16 10:56, Peter Eisentraut wrote:\n> On 15.09.22 17:41, Marina Polyakova wrote:\n>> I agree with you. Here's another version of the patch. The \n>> locale/encoding checks and reports in initdb have been reordered, \n>> because now the encoding is set first and only then the ICU locale is \n>> checked.\n> \n> I committed something based on the first version of your patch. This\n> reordering of the messages here was a little too much surgery for me\n> at this point. For instance, there are also messages in #ifdef WIN32\n> code that would need to be reordered as well. I kept the overall\n> structure of the code the same and just inserted the additional\n> proposed checks.\n> \n> If you want to pursue the reordering of the checks and messages\n> overall, a patch for the master branch could be considered.\n\nI've worked on this again (see attached patch) but I'm not sure if the \nmessages of encoding mismatches are clear enough without the full locale \ninformation. For\n\n$ initdb -D data --icu-locale en --locale-provider icu\n\ncompare the outputs:\n\nThe database cluster will be initialized with this locale configuration:\n provider: icu\n ICU locale: en\n LC_COLLATE: de_DE.iso885915@euro\n LC_CTYPE: de_DE.iso885915@euro\n LC_MESSAGES: en_US.utf8\n LC_MONETARY: de_DE.iso885915@euro\n LC_NUMERIC: de_DE.iso885915@euro\n LC_TIME: de_DE.iso885915@euro\nThe default database encoding has been set to \"UTF8\".\ninitdb: error: encoding mismatch\ninitdb: detail: The encoding you selected (UTF8) and the encoding that \nthe selected locale uses (LATIN9) do not match. This would lead to \nmisbehavior in various character string processing functions.\ninitdb: hint: Rerun initdb and either do not specify an encoding \nexplicitly, or choose a matching combination.\n\nand\n\nEncoding \"UTF8\" implied by locale will be set as the default database \nencoding.\ninitdb: error: encoding mismatch\ninitdb: detail: The encoding you selected (UTF8) and the encoding that \nthe selected locale uses (LATIN9) do not match. This would lead to \nmisbehavior in various character string processing functions.\ninitdb: hint: Rerun initdb and either do not specify an encoding \nexplicitly, or choose a matching combination.\n\nThe same without ICU, e.g. for\n\n$ initdb -D data\n\nthe output with locale information:\n\nThe database cluster will be initialized with this locale configuration:\n provider: libc\n LC_COLLATE: en_US.utf8\n LC_CTYPE: de_DE.iso885915@euro\n LC_MESSAGES: en_US.utf8\n LC_MONETARY: de_DE.iso885915@euro\n LC_NUMERIC: de_DE.iso885915@euro\n LC_TIME: de_DE.iso885915@euro\nThe default database encoding has accordingly been set to \"LATIN9\".\ninitdb: error: encoding mismatch\ninitdb: detail: The encoding you selected (LATIN9) and the encoding that \nthe selected locale uses (UTF8) do not match. This would lead to \nmisbehavior in various character string processing functions.\ninitdb: hint: Rerun initdb and either do not specify an encoding \nexplicitly, or choose a matching combination.\n\nand the \"shorter\" version:\n\nEncoding \"LATIN9\" implied by locale will be set as the default database \nencoding.\ninitdb: error: encoding mismatch\ninitdb: detail: The encoding you selected (LATIN9) and the encoding that \nthe selected locale uses (UTF8) do not match. This would lead to \nmisbehavior in various character string processing functions.\ninitdb: hint: Rerun initdb and either do not specify an encoding \nexplicitly, or choose a matching combination.\n\nBTW, what did you mean that \"there are also messages in #ifdef WIN32 \ncode that would need to be reordered as well\"?..\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Sat, 08 Oct 2022 21:08:18 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "Hello!\n\nI discovered an interesting behaviour during installcheck runs when the \ncluster was initialized with ICU locale provider:\n\n$ initdb --locale-provider icu --icu-locale en-US -D data &&\npg_ctl -D data -l logfile start\n\n1) The ECPG tests fail because they use the SQL_ASCII encoding [1], the \ndatabase template0 uses the ICU locale provider and SQL_ASCII is not \nsupported by ICU:\n\n$ make -C src/interfaces/ecpg/ installcheck\n...\n============== creating database \"ecpg1_regression\" ==============\nERROR: encoding \"SQL_ASCII\" is not supported with ICU provider\nERROR: database \"ecpg1_regression\" does not exist\ncommand failed: \"/home/marina/postgresql/master/my/inst/bin/psql\" -X -c \n\"CREATE DATABASE \\\"ecpg1_regression\\\" TEMPLATE=template0 \nENCODING='SQL_ASCII'\" -c \"ALTER DATABASE \\\"ecpg1_regression\\\" SET \nlc_messages TO 'C';ALTER DATABASE \\\"ecpg1_regression\\\" SET lc_monetary \nTO 'C';ALTER DATABASE \\\"ecpg1_regression\\\" SET lc_numeric TO 'C';ALTER \nDATABASE \\\"ecpg1_regression\\\" SET lc_time TO 'C';ALTER DATABASE \n\\\"ecpg1_regression\\\" SET bytea_output TO 'hex';ALTER DATABASE \n\\\"ecpg1_regression\\\" SET timezone_abbreviations TO 'Default';\" \n\"postgres\"\n\n2) The option --no-locale in pg_regress is described as \"use C locale\" \n[2]. But in this case the created databases actually use the ICU locale \nprovider with the ICU cluster locale from template0 (see \ndiff_check_backend_used_provider.patch):\n\n$ make NO_LOCALE=1 installcheck\n\nIn regression.diffs:\n\ndiff -U3 \n/home/marina/postgresql/master/src/test/regress/expected/test_setup.out \n/home/marina/postgresql/master/src/test/regress/results/test_setup.out\n--- \n/home/marina/postgresql/master/src/test/regress/expected/test_setup.out\t2022-09-27 \n05:31:27.674628815 +0300\n+++ \n/home/marina/postgresql/master/src/test/regress/results/test_setup.out\t2022-10-21 \n15:09:31.232992885 +0300\n@@ -143,6 +143,798 @@\n \\set filename :abs_srcdir '/data/person.data'\n COPY person FROM :'filename';\n VACUUM ANALYZE person;\n+NOTICE: varstrfastcmp_locale sss->collate_c 0 sss->locale 0xefacd0\n+NOTICE: varstrfastcmp_locale sss->locale->provider i\n+NOTICE: varstrfastcmp_locale sss->locale->info.icu.locale en-US\n...\n\nThe patch diff_fix_pg_regress_create_database.patch fixes both issues \nfor me.\n\n[1] \nhttps://github.com/postgres/postgres/blob/ce20f8b9f4354b46b40fd6ebf7ce5c37d08747e0/src/interfaces/ecpg/test/Makefile#L18\n[2] \nhttps://github.com/postgres/postgres/blob/ce20f8b9f4354b46b40fd6ebf7ce5c37d08747e0/src/test/regress/pg_regress.c#L1992\n\n-- \nMarina Polyakova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 21 Oct 2022 17:32:38 +0300", "msg_from": "Marina Polyakova <m.polyakova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" }, { "msg_contents": "On Fri, Oct 21, 2022 at 05:32:38PM +0300, Marina Polyakova wrote:\n> Hello!\n> \n> I discovered an interesting behaviour during installcheck runs when the\n> cluster was initialized with ICU locale provider:\n> \n> $ initdb --locale-provider icu --icu-locale en-US -D data &&\n> 2) The option --no-locale in pg_regress is described as \"use C locale\" [2].\n> But in this case the created databases actually use the ICU locale provider\n> with the ICU cluster locale from template0 (see\n> diff_check_backend_used_provider.patch):\n> \n> $ make NO_LOCALE=1 installcheck\n\nYes, this looks wrong on the ground on what -no-locale is expected to\ndo, aka use a C locale. Peter?\n--\nMichael", "msg_date": "Tue, 1 Nov 2022 16:03:11 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: ICU for global collation" } ]
[ { "msg_contents": "Hello all,\n\nI was just playing around with table partitioning and noticed\n1. When one inserts into a parent table with no partitions defined\nyet, it errors out\n2. Similarly, if we try to insert into a parent table a value which is\nnot covered in any partition and has no default partition defined, it\nerrors out\n\nThis does not sound very convenient. I was thinking of having some\nmechanism for such insertions which automatically creates a default\npartition and gives a notice for the user to know that it is going to\nthe default partition. Basically, always having a default partition.\nAfter all default is something that remains there by default, isn't\nit?\n\nI will be happy to know your thoughts on this.\n\n-- \nRegards,\nRafia Sabih\n\n\n", "msg_date": "Tue, 20 Aug 2019 16:37:51 +0200", "msg_from": "Rafia Sabih <rafia.pghackers@gmail.com>", "msg_from_op": true, "msg_subject": "Improve default partition" }, { "msg_contents": "> On Tue, Aug 20, 2019 at 4:45 PM Rafia Sabih <rafia.pghackers@gmail.com> wrote:\n>\n> This does not sound very convenient. I was thinking of having some\n> mechanism for such insertions which automatically creates a default\n> partition and gives a notice for the user to know that it is going to\n> the default partition.\n\nIf I remember correctly, there is a side effect when it's impossible to create\nany new partitions, that intersects with values from default partition (one has\nto detach a default partition, remove rows and attach it back). That could\nprobably be not always a desired outcome.\n\nBtw, there is a somewhat similar discussion in the ongoing thread [1].\n\n[1]: https://www.postgresql.org/message-id/flat/alpine.DEB.2.21.1907150711080.22273%40lancre\n\n\n", "msg_date": "Tue, 20 Aug 2019 19:41:19 +0200", "msg_from": "Dmitry Dolgov <9erthalion6@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Improve default partition" }, { "msg_contents": "On 2019-Aug-20, Rafia Sabih wrote:\n\n> This does not sound very convenient. I was thinking of having some\n> mechanism for such insertions which automatically creates a default\n> partition and gives a notice for the user to know that it is going to\n> the default partition. Basically, always having a default partition.\n> After all default is something that remains there by default, isn't\n> it?\n\nThere are shortcomings to having a default partition, so I don't think\nthis would be an universally welcome feature.\n\nI think auto-creation of partitions might be useful in some cases, but\nnot by default since there are caveats (possibility of deadlocks) and\nnot of the default partition.\n\nThe major problem I see with the default partition is that there's no\nway to create a partition that overlaps existing contents of the default\npartition, short of blocking everyone.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 20 Aug 2019 16:50:05 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Improve default partition" } ]
[ { "msg_contents": "I find the time displays like\n\n 01:03 ago\n\non the buildfarm status page unhelpful.\n\nFirst, I can never tell whether this is hours-minutes or minutes-seconds\n-- there is probably a less ambiguous format available.\n\nBut more importantly, the page doesn't say when it was generated, so a\nrelative time like this is meaningless. The page might have most\nrecently reloaded last night. That means when I look at the page, I\n*always* have to reload it first to make sense of the times.\n\nI notice that the page source actually includes absolute times that are\nthen converted to relative using some JavaScript. Could we perhaps just\nturn that off? Or preferably convert to local time. I can much easier\nmake sense of an absolute local time: I can compare that to the clock in\nthe corner of the screen, and I can compare that, say, to a commit\ntimestamp.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 21 Aug 2019 09:40:23 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "\"ago\" times on buildfarm status page" }, { "msg_contents": "On Wed, Aug 21, 2019 at 9:40 AM Peter Eisentraut <\npeter.eisentraut@2ndquadrant.com> wrote:\n\n> I find the time displays like\n>\n> 01:03 ago\n>\n> on the buildfarm status page unhelpful.\n>\n> First, I can never tell whether this is hours-minutes or minutes-seconds\n> -- there is probably a less ambiguous format available.\n>\n> But more importantly, the page doesn't say when it was generated, so a\n> relative time like this is meaningless. The page might have most\n> recently reloaded last night. That means when I look at the page, I\n> *always* have to reload it first to make sense of the times.\n>\n> I notice that the page source actually includes absolute times that are\n> then converted to relative using some JavaScript. Could we perhaps just\n> turn that off? Or preferably convert to local time. I can much easier\n> make sense of an absolute local time: I can compare that to the clock in\n> the corner of the screen, and I can compare that, say, to a commit\n> timestamp.\n>\n\nIt used to be that the \"ago\" part was generated on the server, but Andrew\nchanged that to the fixed timestamp + javascript to improve cachability and\nthus performance. Perhaps now that it's that it could be as easy as adding\na checkbox to the page (which could remember your preference in a cookie)\nthat switches between the two modes?\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/ <http://www.hagander.net/>\n Work: https://www.redpill-linpro.com/ <http://www.redpill-linpro.com/>\n\nOn Wed, Aug 21, 2019 at 9:40 AM Peter Eisentraut <peter.eisentraut@2ndquadrant.com> wrote:I find the time displays like\n\n    01:03 ago\n\non the buildfarm status page unhelpful.\n\nFirst, I can never tell whether this is hours-minutes or minutes-seconds\n-- there is probably a less ambiguous format available.\n\nBut more importantly, the page doesn't say when it was generated, so a\nrelative time like this is meaningless.  The page might have most\nrecently reloaded last night.  That means when I look at the page, I\n*always* have to reload it first to make sense of the times.\n\nI notice that the page source actually includes absolute times that are\nthen converted to relative using some JavaScript.  Could we perhaps just\nturn that off?  Or preferably convert to local time.  I can much easier\nmake sense of an absolute local time: I can compare that to the clock in\nthe corner of the screen, and I can compare that, say, to a commit\ntimestamp.It used to be that the \"ago\" part was generated on the server, but Andrew changed that to the fixed timestamp + javascript to improve cachability and thus performance. Perhaps now that it's that it could be as easy as adding a checkbox to the page (which could remember your preference in a cookie) that switches between the two modes? --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Wed, 21 Aug 2019 09:41:43 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "Magnus Hagander <magnus@hagander.net> writes:\n\n> On Wed, Aug 21, 2019 at 9:40 AM Peter Eisentraut <\n> peter.eisentraut@2ndquadrant.com> wrote:\n>\n>> I find the time displays like\n>>\n>> 01:03 ago\n>>\n>> on the buildfarm status page unhelpful.\n>>\n>> First, I can never tell whether this is hours-minutes or minutes-seconds\n>> -- there is probably a less ambiguous format available.\n>>\n>> But more importantly, the page doesn't say when it was generated, so a\n>> relative time like this is meaningless. The page might have most\n>> recently reloaded last night. That means when I look at the page, I\n>> *always* have to reload it first to make sense of the times.\n>>\n>> I notice that the page source actually includes absolute times that are\n>> then converted to relative using some JavaScript. Could we perhaps just\n>> turn that off? Or preferably convert to local time. I can much easier\n>> make sense of an absolute local time: I can compare that to the clock in\n>> the corner of the screen, and I can compare that, say, to a commit\n>> timestamp.\n>>\n>\n> It used to be that the \"ago\" part was generated on the server, but Andrew\n> changed that to the fixed timestamp + javascript to improve cachability and\n> thus performance. Perhaps now that it's that it could be as easy as adding\n> a checkbox to the page (which could remember your preference in a cookie)\n> that switches between the two modes?\n\nThe Javscript could also be made to update the \"ago\" part every minute,\nand show the absoulte time as a tooltip, which is what pretty much every\nother website does.\n\n- ilmari\n-- \n\"A disappointingly low fraction of the human race is,\n at any given time, on fire.\" - Stig Sandbeck Mathisen\n\n\n", "msg_date": "Wed, 21 Aug 2019 13:32:57 +0100", "msg_from": "ilmari@ilmari.org (Dagfinn Ilmari =?utf-8?Q?Manns=C3=A5ker?=)", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "Magnus Hagander <magnus@hagander.net> writes:\n> On Wed, Aug 21, 2019 at 9:40 AM Peter Eisentraut <\n> peter.eisentraut@2ndquadrant.com> wrote:\n>> I find the time displays like\n>> 01:03 ago\n>> on the buildfarm status page unhelpful.\n>> \n>> I notice that the page source actually includes absolute times that are\n>> then converted to relative using some JavaScript. Could we perhaps just\n>> turn that off?\n\n> It used to be that the \"ago\" part was generated on the server, but Andrew\n> changed that to the fixed timestamp + javascript to improve cachability and\n> thus performance. Perhaps now that it's that it could be as easy as adding\n> a checkbox to the page (which could remember your preference in a cookie)\n> that switches between the two modes?\n\nFWIW, I'm used to the way it's shown and would not like a change, so\nif this can be made user-settable as Magnus suggests, that would be\nbetter IMO.\n\nThe real problem with that column though is that it relies on run start\ntimes that are self-reported by the buildfarm clients, and some of them\nhave system clocks that are many hours off reality. What *I'd* like to\nsee is for the column to contain time of receipt of the buildfarm report\nat the server, less the measured runtime of the test.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 21 Aug 2019 09:55:26 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "\nOn 8/21/19 8:32 AM, Dagfinn Ilmari Mannsåker wrote:\n> Magnus Hagander <magnus@hagander.net> writes:\n>\n>> On Wed, Aug 21, 2019 at 9:40 AM Peter Eisentraut <\n>> peter.eisentraut@2ndquadrant.com> wrote:\n>>\n>>> I find the time displays like\n>>>\n>>> 01:03 ago\n>>>\n>>> on the buildfarm status page unhelpful.\n>>>\n>>> First, I can never tell whether this is hours-minutes or minutes-seconds\n>>> -- there is probably a less ambiguous format available.\n>>>\n>>> But more importantly, the page doesn't say when it was generated, so a\n>>> relative time like this is meaningless. The page might have most\n>>> recently reloaded last night. That means when I look at the page, I\n>>> *always* have to reload it first to make sense of the times.\n>>>\n>>> I notice that the page source actually includes absolute times that are\n>>> then converted to relative using some JavaScript. Could we perhaps just\n>>> turn that off? Or preferably convert to local time. I can much easier\n>>> make sense of an absolute local time: I can compare that to the clock in\n>>> the corner of the screen, and I can compare that, say, to a commit\n>>> timestamp.\n>>>\n>> It used to be that the \"ago\" part was generated on the server, but Andrew\n>> changed that to the fixed timestamp + javascript to improve cachability and\n>> thus performance. Perhaps now that it's that it could be as easy as adding\n>> a checkbox to the page (which could remember your preference in a cookie)\n>> that switches between the two modes?\n> The Javscript could also be made to update the \"ago\" part every minute,\n> and show the absoulte time as a tooltip, which is what pretty much every\n> other website does.\n>\n\n\nThe code for the page is here:\n<https://github.com/PGBuildFarm/server-code/blob/master/templates/status.tt>\n\n\nPatches welcome.\n\n\ncheers\n\n\nandrew\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Wed, 21 Aug 2019 10:52:59 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "\nOn 8/21/19 9:55 AM, Tom Lane wrote:\n>\n> The real problem with that column though is that it relies on run start\n> times that are self-reported by the buildfarm clients, and some of them\n> have system clocks that are many hours off reality. What *I'd* like to\n> see is for the column to contain time of receipt of the buildfarm report\n> at the server, less the measured runtime of the test.\n\n\nThat might be possible. I'll put it on my list of things to do. It's not\nhappening any time soon, though.\n\n\ncheers\n\n\nandrew\n\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Wed, 21 Aug 2019 11:07:02 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "\nOn 8/21/19 3:40 AM, Peter Eisentraut wrote:\n> I find the time displays like\n>\n> 01:03 ago\n>\n> on the buildfarm status page unhelpful.\n>\n> First, I can never tell whether this is hours-minutes or minutes-seconds\n> -- there is probably a less ambiguous format available.\n\n\n\nThis is hours:minutes. days are always explicitly prepended if greater\nthan 0.\n\n\n>\n> But more importantly, the page doesn't say when it was generated, so a\n> relative time like this is meaningless. The page might have most\n> recently reloaded last night. That means when I look at the page, I\n> *always* have to reload it first to make sense of the times.\n>\n> I notice that the page source actually includes absolute times that are\n> then converted to relative using some JavaScript. Could we perhaps just\n> turn that off? Or preferably convert to local time. I can much easier\n> make sense of an absolute local time: I can compare that to the clock in\n> the corner of the screen, and I can compare that, say, to a commit\n> timestamp.\n>\n\n\nMaybe.\n\n\nTBH the whole buildfarm UI is rather dated and clunky. But it needs work\nfrom a web monkey, which I am really not.\n\n\ncheers\n\n\nandrew\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Wed, 21 Aug 2019 11:10:04 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "\nOn 8/21/19 11:07 AM, Andrew Dunstan wrote:\n> On 8/21/19 9:55 AM, Tom Lane wrote:\n>> The real problem with that column though is that it relies on run start\n>> times that are self-reported by the buildfarm clients, and some of them\n>> have system clocks that are many hours off reality. What *I'd* like to\n>> see is for the column to contain time of receipt of the buildfarm report\n>> at the server, less the measured runtime of the test.\n>\n> That might be possible. I'll put it on my list of things to do. It's not\n> happening any time soon, though.\n>\n>\n\n\nWhat I have done quickly is to store a measure of the clock skew. We\nalready calculated it but we didn't store it. Initial indications are\nthat only a few have significant skew.\n\n\nStill, if we simply added the skew to the snapshot time that might be\nenough to achieve what you want. That would be a one line change, I think.\n\n\ncheers\n\n\nandrew\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Wed, 21 Aug 2019 15:40:15 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com> writes:\n> What I have done quickly is to store a measure of the clock skew. We\n> already calculated it but we didn't store it. Initial indications are\n> that only a few have significant skew.\n\nOh, I didn't know that the server had the ability to measure that.\n\n(Yes, I agree that there are just a couple with big skews at any\none time.)\n\n> Still, if we simply added the skew to the snapshot time that might be\n> enough to achieve what you want. That would be a one line change, I think.\n\n+1\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 21 Aug 2019 16:16:22 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "\nOn 8/21/19 4:16 PM, Tom Lane wrote:\n> Andrew Dunstan <andrew.dunstan@2ndquadrant.com> writes:\n>> What I have done quickly is to store a measure of the clock skew. We\n>> already calculated it but we didn't store it. Initial indications are\n>> that only a few have significant skew.\n> Oh, I didn't know that the server had the ability to measure that.\n>\n> (Yes, I agree that there are just a couple with big skews at any\n> one time.)\n>\n>> Still, if we simply added the skew to the snapshot time that might be\n>> enough to achieve what you want. That would be a one line change, I think.\n> +1\n>\n> \t\t\t\n\n\nDone. It's only happening prospectively, so we'll need to wait a few\ndays to see it flow through.\n\n\ncheers\n\n\nandrew\n\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Fri, 23 Aug 2019 09:21:59 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "\nOn 8/21/19 10:52 AM, Andrew Dunstan wrote:\n>>\n>> The Javscript could also be made to update the \"ago\" part every minute,\n>> and show the absoulte time as a tooltip, which is what pretty much every\n>> other website does.\n>>\n>\n> The code for the page is here:\n> <https://github.com/PGBuildFarm/server-code/blob/master/templates/status.tt>\n>\n>\n> Patches welcome.\n>\n>\n\n\nI have done both of these things.\n\n\ncheers\n\n\nandrew\n\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Sat, 24 Aug 2019 10:51:58 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com> writes:\n> On 8/21/19 4:16 PM, Tom Lane wrote:\n>> Andrew Dunstan <andrew.dunstan@2ndquadrant.com> writes:\n>>> Still, if we simply added the skew to the snapshot time that might be\n>>> enough to achieve what you want. That would be a one line change, I think.\n\n>> +1\n\n> Done. It's only happening prospectively, so we'll need to wait a few\n> days to see it flow through.\n\nHm, doesn't seem to have done the trick. The current dashboard page shows\n(in the v12 branch)\n\nmule ... 01:17 ago OK [97205d0] Config\nloach ... 01:32 ago OK [97205d0] Config\ndangomushi ... 02:11 ago OK [97205d0] Config\nbowerbird ... 02:23 ago scriptsCheck [97205d0] Details\nsnapper ... 02:48 ago OK [63fc3b1] Config\ncaiman ... 03:04 ago OK [97205d0] Config\nnightjar ... 03:17 ago recoveryCheck [97205d0] Details\nchub ... 03:29 ago OK [97205d0] Config\nclam ... 03:34 ago OK [97205d0] Config\ndemoiselle ... 03:45 ago OK [97205d0] Config\n\nsnapper is clearly out of line here: the commit it claims\nto have fetched 2:48 ago was obsoleted around seven hours ago.\n\n(Snapper is one of the machines that is typically inconsistent\nin this way. I've been assuming that's because its system clock\nis a few hours off ... but maybe there's something else going on?)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 26 Aug 2019 14:55:50 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "\nOn 8/26/19 2:55 PM, Tom Lane wrote:\n> Andrew Dunstan <andrew.dunstan@2ndquadrant.com> writes:\n>> On 8/21/19 4:16 PM, Tom Lane wrote:\n>>> Andrew Dunstan <andrew.dunstan@2ndquadrant.com> writes:\n>>>> Still, if we simply added the skew to the snapshot time that might be\n>>>> enough to achieve what you want. That would be a one line change, I think.\n>>> +1\n>> Done. It's only happening prospectively, so we'll need to wait a few\n>> days to see it flow through.\n> Hm, doesn't seem to have done the trick. The current dashboard page shows\n> (in the v12 branch)\n>\n> mule ... 01:17 ago OK [97205d0] Config\n> loach ... 01:32 ago OK [97205d0] Config\n> dangomushi ... 02:11 ago OK [97205d0] Config\n> bowerbird ... 02:23 ago scriptsCheck [97205d0] Details\n> snapper ... 02:48 ago OK [63fc3b1] Config\n> caiman ... 03:04 ago OK [97205d0] Config\n> nightjar ... 03:17 ago recoveryCheck [97205d0] Details\n> chub ... 03:29 ago OK [97205d0] Config\n> clam ... 03:34 ago OK [97205d0] Config\n> demoiselle ... 03:45 ago OK [97205d0] Config\n>\n> snapper is clearly out of line here: the commit it claims\n> to have fetched 2:48 ago was obsoleted around seven hours ago.\n>\n> (Snapper is one of the machines that is typically inconsistent\n> in this way. I've been assuming that's because its system clock\n> is a few hours off ... but maybe there's something else going on?)\n>\n> \t\t\t\n\n\n\n\nI think this is the problem:\n\n  'scmrepo' => '/home/pgbf/pgmirror.git',\n\nProbably this isn't updated often enough. It probably has little to do with the clock settings.\n\nThis is the kind of old-fashioned way of doing things. These days \"git_keep_mirror => 1\" along with the community repo as the base would avoid these problems.\n\ncheers\n\nandrew\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Mon, 26 Aug 2019 15:08:54 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "On Mon, Aug 26, 2019, at 9:08 PM, Andrew Dunstan wrote:\n> I think this is the problem:\n> \n> 'scmrepo' => '/home/pgbf/pgmirror.git',\n> \n> Probably this isn't updated often enough. It probably has little to do with the clock settings.\n> \n> This is the kind of old-fashioned way of doing things. These days \"git_keep_mirror => 1\" along with the community repo as the base would avoid these problems.\n\nWe've discussed this before (see below).\n\nThe configuration is intentionally like that. I specifically configured skate and snapper to build the exact same source, where skate builds with default buildfarm settings, while snapper builds with the settings actually used by Debian source packages.\n\nThese animals were set up to avoid cases we had in the past where Debian source packages failed to build on sparc, even though build animals running on Debian sparc were building fine:\n\nhttps://www.postgresql.org/message-id/000001d2f0c2%24e2d335a0%24a879a0e0%24%40turelinckx.be\n\nWith snapper building the exact same source as skate (as it is now), we have some point of reference if snapper fails but skate succeeds. I could configure snapper to perform an update of the repo before building, but then we give up this comparability in exchange for a bit more clarity regarding timestamps.\n\nBest regards,\nTom Turelinckx\n\nOn Thu, Nov 9, 2017, at 8:54 PM, Andrew Dunstan wrote:\n> \n> The first line of the log file is always something like this (see end of https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=nightjar&dt=2017-11-09%2018%3A59%3A01 )\n> \n> Last file mtime in snapshot: Thu Nov 9 17:56:07 2017 GMT\n> This should be the time of the last commit in the snapshot.\n>\n> On Mon, Nov 6, 2017 at 9:49 AM, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>>\n>> Tom Turelinckx <pgbf@twiska.com> writes:\n>>\n>> > On Fri, Nov 3, 2017, at 09:42 PM, Tom Lane wrote:\n>> >> Either that, or it's fallen through a wormhole ;-), but the results\n>> >> it's posting seem to be mis-timestamped by several hours, which is\n>> >> confusing. Please set its clock correctly. Maybe spin up ntpd?\n>> \n>> > The clock is correct, but the configuration may be unusual.\n>> \n>> > In fact, snapper runs on the same machine as skate, and it's using ntp.\n>> > At 7 AM (Western Europe), a local git repo is updated. In the morning,\n>> > skate builds from that local repo with the default buildfarm\n>> > configuration that most animals use. In the afternoon, snapper builds\n>> > from that local repo with the exact same configuration, per branch, that\n>> > the Debian source packages from the pgdg repo use on the same platform.\n>> > The local repo is updated only once per day to ensure that snapper and\n>> > skate build the same source with different settings, and they share the\n>> > git mirror and build root, as suggested in the build farm howto.\n>> \n>> Hm. So the issue really is that the build timestamp that the buildfarm\n>> client is reporting tells when it pulled from the local repo, not when\n>> that repo was last updated from the community server. Not sure if there's\n>> any simple way to improve that ... Andrew, any thoughts?\n\n\n", "msg_date": "Tue, 27 Aug 2019 10:33:39 +0200", "msg_from": "\"Tom Turelinckx\" <pgbf@twiska.com>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "\nOn 8/27/19 4:33 AM, Tom Turelinckx wrote:\n> On Mon, Aug 26, 2019, at 9:08 PM, Andrew Dunstan wrote:\n>> I think this is the problem:\n>>\n>> 'scmrepo' => '/home/pgbf/pgmirror.git',\n>>\n>> Probably this isn't updated often enough. It probably has little to do with the clock settings.\n>>\n>> This is the kind of old-fashioned way of doing things. These days \"git_keep_mirror => 1\" along with the community repo as the base would avoid these problems.\n> We've discussed this before (see below).\n>\n>\n> Hm. So the issue really is that the build timestamp that the buildfarm\n> client is reporting tells when it pulled from the local repo, not when\n> that repo was last updated from the community server. Not sure if there's\n> any simple way to improve that ... Andrew, any thoughts?\n\n\n\nMaybe we need an option to use the git commit time. instead of the\nsnapshot time.\n\n\ncheers\n\n\nandrew\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Tue, 27 Aug 2019 08:45:36 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "\nOn 8/27/19 8:45 AM, Andrew Dunstan wrote:\n> On 8/27/19 4:33 AM, Tom Turelinckx wrote:\n>> On Mon, Aug 26, 2019, at 9:08 PM, Andrew Dunstan wrote:\n>>> I think this is the problem:\n>>>\n>>> 'scmrepo' => '/home/pgbf/pgmirror.git',\n>>>\n>>> Probably this isn't updated often enough. It probably has little to do with the clock settings.\n>>>\n>>> This is the kind of old-fashioned way of doing things. These days \"git_keep_mirror => 1\" along with the community repo as the base would avoid these problems.\n>> We've discussed this before (see below).\n>>\n>>\n>> Hm. So the issue really is that the build timestamp that the buildfarm\n>> client is reporting tells when it pulled from the local repo, not when\n>> that repo was last updated from the community server. Not sure if there's\n>> any simple way to improve that ... Andrew, any thoughts?\n>\n>\n> Maybe we need an option to use the git commit time. instead of the\n> snapshot time.\n>\n>\n\nScratch that - we use this to calculate the duration of the first stage,\nso mangling it would just create another error.\n\n\nIt's tempting to say we should sort the dashboard by git reference time\nthen snapshot - that should be fairly doable. But what if there isn't a\ngit reference, as happens when there's a git failure for example. In\nthose cases Maybe just use the snapshot time?\n\n\nStoring the git timestanp would involve a table change in our second\nlargest table, so the team would need to discuss and plan it.\n\n\ncheers\n\n\nandrew\n\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Tue, 27 Aug 2019 09:47:25 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "\"Tom Turelinckx\" <pgbf@twiska.com> writes:\n> On Mon, Aug 26, 2019, at 9:08 PM, Andrew Dunstan wrote:\n>> I think this is the problem:\n>> 'scmrepo' => '/home/pgbf/pgmirror.git',\n>> Probably this isn't updated often enough. It probably has little to do with the clock settings.\n\n> The configuration is intentionally like that. I specifically configured skate and snapper to build the exact same source, where skate builds with default buildfarm settings, while snapper builds with the settings actually used by Debian source packages.\n\nTBH, I don't find that particularly important ... especially not for HEAD\nbuilds, where building a many-hours-old snapshot is pretty much in the\ncategory of \"why bother?\". On the whole, I think building from the latest\navailable source is the most useful policy. If there's some platform-\nor configuration-specific issue, it usually takes more than one build\ncycle for us to notice it anyway, so that ensuring two animals have exactly\ncomparable builds at any given instant isn't very helpful.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 27 Aug 2019 10:15:56 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" }, { "msg_contents": "\nOn 8/27/19 10:15 AM, Tom Lane wrote:\n> \"Tom Turelinckx\" <pgbf@twiska.com> writes:\n>> On Mon, Aug 26, 2019, at 9:08 PM, Andrew Dunstan wrote:\n>>> I think this is the problem:\n>>> 'scmrepo' => '/home/pgbf/pgmirror.git',\n>>> Probably this isn't updated often enough. It probably has little to do with the clock settings.\n>> The configuration is intentionally like that. I specifically configured skate and snapper to build the exact same source, where skate builds with default buildfarm settings, while snapper builds with the settings actually used by Debian source packages.\n> TBH, I don't find that particularly important ... especially not for HEAD\n> builds, where building a many-hours-old snapshot is pretty much in the\n> category of \"why bother?\". On the whole, I think building from the latest\n> available source is the most useful policy. If there's some platform-\n> or configuration-specific issue, it usually takes more than one build\n> cycle for us to notice it anyway, so that ensuring two animals have exactly\n> comparable builds at any given instant isn't very helpful.\n>\n> \t\t\t\n\n\n\nYeah, point. snapper seems the more important box here.\n\n\ncheers\n\n\nandrew\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Tue, 27 Aug 2019 10:27:32 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: \"ago\" times on buildfarm status page" } ]
[ { "msg_contents": "Hi, hackers.\n\nRight now if replication level is rgeater or equal than \"replica\", \nvacuum  of relation copies all its data to WAL:\n\n\n     /*\n      * We need to log the copied data in WAL iff WAL archiving/streaming is\n      * enabled AND it's a WAL-logged rel.\n      */\n     use_wal = XLogIsNeeded() && RelationNeedsWAL(NewHeap);\n\nObviously we have to do it for physical replication and WAL archiving.\nBut why do we need to do so expensive operation (actually copy all table \ndata three times) if we use logical replication?\nLogically vacuum doesn't change relation so there is no need to write \nany data to the log and process it by WAL sender.\n\nI wonder if we can check that\n\n1. wal_revel is \"logical\"\n2. There are no physical replication slots\n3. WAL archiving is disables\n\nand in this cases do not write cloned relation to the WAL?\nSmall patch implementing such behavior is attached to this mail.\nIt allows to significantly reduce WAL size when performing vacuum at \nmultimaster, which uses logical replication between cluster nodes.\n\nWhat can be wrong with such optimization?\n\n-- \n\nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Wed, 21 Aug 2019 12:20:18 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Optimization of vacuum for logical replication" }, { "msg_contents": "Am Mittwoch, den 21.08.2019, 12:20 +0300 schrieb Konstantin Knizhnik:\n> I wonder if we can check that\n> \n> 1. wal_revel is \"logical\"\n> 2. There are no physical replication slots\n> 3. WAL archiving is disables\n\nNot sure i get that correctly, i can still have a physical standby\nwithout replication slots connected to such an instance. How would your\nidea handle this situation?\n\n\tBernd\n\n\n\n\n", "msg_date": "Wed, 21 Aug 2019 11:34:34 +0200", "msg_from": "Bernd Helmle <mailings@oopsware.de>", "msg_from_op": false, "msg_subject": "Re: Optimization of vacuum for logical replication" }, { "msg_contents": "\n\nOn 21.08.2019 12:34, Bernd Helmle wrote:\n> Am Mittwoch, den 21.08.2019, 12:20 +0300 schrieb Konstantin Knizhnik:\n>> I wonder if we can check that\n>>\n>> 1. wal_revel is \"logical\"\n>> 2. There are no physical replication slots\n>> 3. WAL archiving is disables\n> Not sure i get that correctly, i can still have a physical standby\n> without replication slots connected to such an instance. How would your\n> idea handle this situation?\n\nYes, it is possible to have physical replica withotu replication slot.\nBut it is not safe, because there is always a risk that lag between \nmaster and replica becomes larger than size of WAL kept at master.\nAlso I can't believe that  DBA which explicitly sets wal_level is set to \nlogical will use streaming replication without associated replication slot.\n\nAnd certainly it is possible to add GUC which controls such optimization.\n\n-- \n\nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Wed, 21 Aug 2019 13:26:04 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Optimization of vacuum for logical replication" }, { "msg_contents": "Hello\n\n> Also I can't believe that  DBA which explicitly sets wal_level is set to\n> logical will use streaming replication without associated replication slot.\n\nI am.\n\n> Yes, it is possible to have physical replica withotu replication slot.\n> But it is not safe, because there is always a risk that lag between\n> master and replica becomes larger than size of WAL kept at master.\n\nJust an example: replica for manual queries, QA purposes or for something else that is not an important part of the system.\nIf I use replication slots - my risk is out-of-space on primary and therefore shutdown of primary. With downtime for application.\nIf I use wal_keep_segments instead - I have some limited (and usually stable) amount of WAL but risk to have outdated replica.\n\nI prefer to have an outdated replica but primary is more safe. Its OK for me to just take fresh pg_basebackup from another replica.\nAnd application want to use logical replication so wal_level = logical.\n\nIf we not want support such usecase - we need explicitly forbid replication without replication slots.\n\nregards, Sergei\n\n\n", "msg_date": "Wed, 21 Aug 2019 14:07:51 +0300", "msg_from": "Sergei Kornilov <sk@zsrv.org>", "msg_from_op": false, "msg_subject": "Re: Optimization of vacuum for logical replication" }, { "msg_contents": "Am Mittwoch, den 21.08.2019, 13:26 +0300 schrieb Konstantin Knizhnik:\n> Yes, it is possible to have physical replica withotu replication\n> slot.\n> But it is not safe, because there is always a risk that lag between \n> master and replica becomes larger than size of WAL kept at master.\n\nSure, but that doesn't mean use cases for this aren't real.\n\n> Also I can't believe that DBA which explicitly sets wal_level is set\n> to \n> logical will use streaming replication without associated replication\n> slot.\n\nWell, i know people doing exactly this, for various reasons (short\nliving replicas, logical replicated table sets for reports, ...). The\nfact that they can have loosely coupled replicas with either physical\nor logical replication is a feature they'd really miss....\n\n\tBernd\n\n\n\n", "msg_date": "Wed, 21 Aug 2019 13:45:27 +0200", "msg_from": "Bernd Helmle <mailings@oopsware.de>", "msg_from_op": false, "msg_subject": "Re: Optimization of vacuum for logical replication" }, { "msg_contents": "\n\nOn 21.08.2019 14:45, Bernd Helmle wrote:\n> Am Mittwoch, den 21.08.2019, 13:26 +0300 schrieb Konstantin Knizhnik:\n>> Yes, it is possible to have physical replica withotu replication\n>> slot.\n>> But it is not safe, because there is always a risk that lag between\n>> master and replica becomes larger than size of WAL kept at master.\n> Sure, but that doesn't mean use cases for this aren't real.\n>\n>> Also I can't believe that DBA which explicitly sets wal_level is set\n>> to\n>> logical will use streaming replication without associated replication\n>> slot.\n> Well, i know people doing exactly this, for various reasons (short\n> living replicas, logical replicated table sets for reports, ...). The\n> fact that they can have loosely coupled replicas with either physical\n> or logical replication is a feature they'd really miss....\n>\n> \tBernd\n>\n\nOk, you convinced me that there are cases when people want to combine \nlogical replication with streaming replication without slot.\nBut is it acceptable to have GUC variable (disabled by default) which \nallows to use this optimizations?\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Wed, 21 Aug 2019 18:06:52 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Optimization of vacuum for logical replication" }, { "msg_contents": "Hello.\n\nAt Wed, 21 Aug 2019 18:06:52 +0300, Konstantin Knizhnik <k.knizhnik@postgrespro.ru> wrote in <968fc591-51d3-fd74-8a55-40aa770baa3a@postgrespro.ru>\n> Ok, you convinced me that there are cases when people want to combine\n> logical replication with streaming replication without slot.\n> But is it acceptable to have GUC variable (disabled by default) which\n> allows to use this optimizations?\n\nThe odds are quite high. Couldn't we introduce a new wal_level\nvalue instead?\n\nwal_level = logical_only\n\n\nI think this thread shows that logical replication no longer is a\nsuperset(?) of physical replication. I thougt that we might be\nable to change wal_level from scalar to bitmap but it breaks\nbackward compatibility..\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Thu, 22 Aug 2019 12:13:23 +0900 (Tokyo Standard Time)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Optimization of vacuum for logical replication" }, { "msg_contents": "\n\nOn 22.08.2019 6:13, Kyotaro Horiguchi wrote:\n> Hello.\n>\n> At Wed, 21 Aug 2019 18:06:52 +0300, Konstantin Knizhnik <k.knizhnik@postgrespro.ru> wrote in <968fc591-51d3-fd74-8a55-40aa770baa3a@postgrespro.ru>\n>> Ok, you convinced me that there are cases when people want to combine\n>> logical replication with streaming replication without slot.\n>> But is it acceptable to have GUC variable (disabled by default) which\n>> allows to use this optimizations?\n> The odds are quite high. Couldn't we introduce a new wal_level\n> value instead?\n>\n> wal_level = logical_only\n>\n>\n> I think this thread shows that logical replication no longer is a\n> superset(?) of physical replication. I thougt that we might be\n> able to change wal_level from scalar to bitmap but it breaks\n> backward compatibility..\n>\n> regards.\n>\nI think that introducing new wal_level is good idea.\nThere are a lot of other places (except vacuum) where we insert in the \nlog information which is not needed for logical decoding.\nInstead of changing all places in code where this information is \ninserted, we can filter it at xlog level (xlog.c).\nMy only concern is how much incompatibilities will be caused by \nintroducing new wal level.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Thu, 22 Aug 2019 10:06:56 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Optimization of vacuum for logical replication" }, { "msg_contents": "On 22.08.2019 6:13, Kyotaro Horiguchi wrote:\n> Hello.\n>\n> At Wed, 21 Aug 2019 18:06:52 +0300, Konstantin Knizhnik <k.knizhnik@postgrespro.ru> wrote in <968fc591-51d3-fd74-8a55-40aa770baa3a@postgrespro.ru>\n>> Ok, you convinced me that there are cases when people want to combine\n>> logical replication with streaming replication without slot.\n>> But is it acceptable to have GUC variable (disabled by default) which\n>> allows to use this optimizations?\n> The odds are quite high. Couldn't we introduce a new wal_level\n> value instead?\n>\n> wal_level = logical_only\n>\n>\n> I think this thread shows that logical replication no longer is a\n> superset(?) of physical replication. I thougt that we might be\n> able to change wal_level from scalar to bitmap but it breaks\n> backward compatibility..\n>\n> regards.\n>\n\nI can propose the following patch introducing new level logical_only.\nI will be please to receive comments concerning adding new wal_level and \npossible problems caused by it.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 23 Aug 2019 14:37:28 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Optimization of vacuum for logical replication" } ]
[ { "msg_contents": "given the following example:\npostgres=# create table t2 as select generate_series(1, 100000) as a,\n generate_series(1, 100000) as b;\nSELECT 100000\npostgres=# create index t2_idx on t2(a);\nCREATE INDEX\npostgres=# set enable_seqscan = 0;\nSET\npostgres=# select * from t2 where a in (1, 100000);\n a | b\n--------+--------\n 1 | 1\n 100000 | 100000\n(2 rows)\n\n\nI can see the plan stores the \"1 and 100000\" information in\nIndexScan->indexqual, which is an SCALARARRAYOPEXPR expression.\n\nsuppose the executor should scan 1 first, If all the tuples for 1 has\nbeen scanned, then **it should be reset to 100000** and scan again.\n however I can't find out the code for that. looks index_rescan is not for\nthis. am I miss something?\n\nthanks\n\ngiven the following example:postgres=# create table t2 as select generate_series(1, 100000) as a,  generate_series(1, 100000) as b;SELECT 100000postgres=# create index t2_idx on t2(a);CREATE INDEXpostgres=# set enable_seqscan = 0;SETpostgres=# select * from t2 where a in (1, 100000);   a    |   b--------+--------      1 |      1 100000 | 100000(2 rows)I can see the plan stores the \"1 and 100000\" information in  IndexScan->indexqual, which is an SCALARARRAYOPEXPR expression. suppose the executor  should scan 1 first,  If all the tuples for 1 has been scanned,  then **it should be reset to 100000**  and scan again.   however I can't find out the code for that.  looks index_rescan is not for this.   am I miss something?thanks", "msg_date": "Wed, 21 Aug 2019 20:58:47 +0800", "msg_from": "Alex <zhihui.fan1213@gmail.com>", "msg_from_op": true, "msg_subject": "when the IndexScan reset to the next ScanKey for in operator" }, { "msg_contents": "Hi,\n\nAt Wed, 21 Aug 2019 20:58:47 +0800, Alex <zhihui.fan1213@gmail.com> wrote in <CAKU4AWoUnnZE5oz71+pPu=xSHQBeDM649NKMuOxfhATWAzx22g@mail.gmail.com>\n> postgres=# select * from t2 where a in (1, 100000);\n...\n> I can see the plan stores the \"1 and 100000\" information in\n> IndexScan->indexqual, which is an SCALARARRAYOPEXPR expression.\n...\n> suppose the executor should scan 1 first, If all the tuples for 1 has\n> been scanned, then **it should be reset to 100000** and scan again.\n> however I can't find out the code for that. looks index_rescan is not for\n> this. am I miss something?\n\nPerhaps _bt_advance_array_keys() and btgettuple() would be what\nyou are seeking for.\n\n> /* ... otherwise see if we have more array keys to deal with */\n> } while (so->numArrayKeys && _bt_advance_array_keys(scan, dir));\n\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Thu, 22 Aug 2019 18:13:46 +0900 (Tokyo Standard Time)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: when the IndexScan reset to the next ScanKey for in operator" }, { "msg_contents": "On Wed, Aug 21, 2019 at 6:24 AM Alex <zhihui.fan1213@gmail.com> wrote:\n> suppose the executor should scan 1 first, If all the tuples for 1 has been scanned, then **it should be reset to 100000** and scan again.\n\nYou might find my nbtree index scan test patch useful:\n\nhttps://postgr.es/m/CAH2-WzmRT_0YbHF05axQb2OiTUQiQAkr0Lznntj8X3KADKZ-5g@mail.gmail.com\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Thu, 22 Aug 2019 22:14:03 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: when the IndexScan reset to the next ScanKey for in operator" } ]
[ { "msg_contents": "Hi Hackers,\n\nI have been looking into adding parallel backup feature in pg_basebackup.\nCurrently pg_basebackup sends BASE_BACKUP command for taking full backup,\nserver scans the PGDATA and sends the files to pg_basebackup. In general,\nserver takes the following steps on BASE_BACKUP command:\n\n- do pg_start_backup\n- scans PGDATA, creates and send header containing information of\ntablespaces.\n- sends each tablespace to pg_basebackup.\n- and then do pg_stop_backup\n\nAll these steps are executed sequentially by a single process. The idea I\nam working on is to separate these steps into multiple commands in\nreplication grammer. Add worker processes to the pg_basebackup where they\ncan copy the contents of PGDATA in parallel.\n\nThe command line interface syntax would be like:\npg_basebackup --jobs=WORKERS\n\n\nReplication commands:\n\n- BASE_BACKUP [PARALLEL] - returns a list of files in PGDATA\nIf the parallel option is there, then it will only do pg_start_backup,\nscans PGDATA and sends a list of file names.\n\n- SEND_FILES_CONTENTS (file1, file2,...) - returns the files in given list.\npg_basebackup will then send back a list of filenames in this command. This\ncommands will be send by each worker and that worker will be getting the\nsaid files.\n\n- STOP_BACKUP\nwhen all workers finish then, pg_basebackup will send STOP_BACKUP command.\n\nThe pg_basebackup can start by sending \"BASE_BACKUP PARALLEL\" command and\ngetting a list of filenames from the server in response. It should then\ndivide this list as per --jobs parameter. (This division can be based on\nfile sizes). Each of the worker process will issue a SEND_FILES_CONTENTS\n(file1, file2,...) command. In response, the server will send the files\nmentioned in the list back to the requesting worker process.\n\nOnce all the files are copied, then pg_basebackup will send the STOP_BACKUP\ncommand. Similar idea has been been discussed by Robert, on the incremental\nbackup thread a while ago. This is similar to that but instead of\nSTART_BACKUP and SEND_FILE_LIST, I have combined them into BASE_BACKUP\nPARALLEL.\n\nI have done a basic proof of concenpt (POC), which is also attached. I\nwould appreciate some input on this. So far, I am simply dividing the list\nequally and assigning them to worker processes. I intend to fine tune this\nby taking into consideration file sizes. Further to add tar format support,\nI am considering that each worker process, processes all files belonging to\na tablespace in its list (i.e. creates and copies tar file), before it\nprocesses the next tablespace. As a result, this will create tar files that\nare disjointed with respect tablespace data. For example:\n\nSay, tablespace t1 has 20 files and we have 5 worker processes and\ntablespace t2 has 10. Ignoring all other factors for the sake of this\nexample, each worker process will get a group of 4 files of t1 and 2 files\nof t2. Each process will create 2 tar files, one for t1 containing 4 files\nand another for t2 containing 2 files.\n\n\nRegards,\nAsif", "msg_date": "Wed, 21 Aug 2019 18:47:04 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif\n\nInteresting proposal. Bulk of the work in a backup is transferring files\nfrom source data directory to destination. Your patch is breaking this\ntask down in multiple sets of files and transferring each set in parallel.\nThis seems correct, however, your patch is also creating a new process to\nhandle each set. Is that necessary? I think we should try to achieve this\nusing multiple asynchronous libpq connections from a single basebackup\nprocess. That is to use PQconnectStartParams() interface instead of\nPQconnectdbParams(), wich is currently used by basebackup. On the server\nside, it may still result in multiple backend processes per connection, and\nan attempt should be made to avoid that as well, but it seems complicated.\n\nWhat do you think?\n\nAsim\n\nHi AsifInteresting proposal.  Bulk of the work in a backup is transferring files from source data directory to destination.  Your patch is breaking this task down in multiple sets of files and transferring each set in parallel.  This seems correct, however, your patch is also creating a new process to handle each set.  Is that necessary?  I think we should try to achieve this using multiple asynchronous libpq connections from a single basebackup process.  That is to use PQconnectStartParams() interface instead of PQconnectdbParams(), wich is currently used by basebackup.  On the server side, it may still result in multiple backend processes per connection, and an attempt should be made to avoid that as well, but it seems complicated.What do you think?Asim", "msg_date": "Fri, 23 Aug 2019 15:47:51 +0530", "msg_from": "Asim R P <apraveen@pivotal.io>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Fri, Aug 23, 2019 at 3:18 PM Asim R P <apraveen@pivotal.io> wrote:\n\n> Hi Asif\n>\n> Interesting proposal. Bulk of the work in a backup is transferring files\n> from source data directory to destination. Your patch is breaking this\n> task down in multiple sets of files and transferring each set in parallel.\n> This seems correct, however, your patch is also creating a new process to\n> handle each set. Is that necessary? I think we should try to achieve this\n> using multiple asynchronous libpq connections from a single basebackup\n> process. That is to use PQconnectStartParams() interface instead of\n> PQconnectdbParams(), wich is currently used by basebackup. On the server\n> side, it may still result in multiple backend processes per connection, and\n> an attempt should be made to avoid that as well, but it seems complicated.\n>\n> What do you think?\n>\n> The main question is what we really want to solve here. What is the\nbottleneck? and which HW want to saturate?. Why I am saying that because\nthere are multiple H/W involve while taking the backup (Network/CPU/Disk).\nIf we\nalready saturated the disk then there is no need to add parallelism because\nwe will be blocked on disk I/O anyway. I implemented the parallel backup\nin a sperate\napplication and has wonderful results. I just skim through the code and have\nsome reservation that creating a separate process only for copying data is\noverkill.\nThere are two options, one is non-blocking calls or you can have some\nworker threads.\nBut before doing that need to see the pg_basebackup bottleneck, after that,\nwe\ncan see what is the best way to solve that. Some numbers may help to\nunderstand the\nactual benefit.\n\n\n-- \nIbrar Ahmed\n\nOn Fri, Aug 23, 2019 at 3:18 PM Asim R P <apraveen@pivotal.io> wrote:Hi AsifInteresting proposal.  Bulk of the work in a backup is transferring files from source data directory to destination.  Your patch is breaking this task down in multiple sets of files and transferring each set in parallel.  This seems correct, however, your patch is also creating a new process to handle each set.  Is that necessary?  I think we should try to achieve this using multiple asynchronous libpq connections from a single basebackup process.  That is to use PQconnectStartParams() interface instead of PQconnectdbParams(), wich is currently used by basebackup.  On the server side, it may still result in multiple backend processes per connection, and an attempt should be made to avoid that as well, but it seems complicated.What do you think?The main question is what we really want to solve here. What is thebottleneck? and which HW want to saturate?. Why I am saying that becausethere are multiple H/W involve while taking the backup (Network/CPU/Disk). If wealready saturated the disk then there is no need to add parallelism becausewe will be blocked on disk I/O anyway.  I implemented the parallel backup in a sperateapplication and has wonderful results. I just skim through the code and havesome reservation that creating a separate process only for copying data is overkill.There are two options, one is non-blocking calls or you can have some worker threads.But before doing that need to see the pg_basebackup bottleneck, after that, wecan see what is the best way to solve that. Some numbers may help to understand theactual benefit.-- Ibrar Ahmed", "msg_date": "Fri, 23 Aug 2019 18:03:10 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Fri, Aug 23, 2019 at 3:18 PM Asim R P <apraveen@pivotal.io> wrote:\n\n> Hi Asif\n>\n> Interesting proposal. Bulk of the work in a backup is transferring files\n> from source data directory to destination. Your patch is breaking this\n> task down in multiple sets of files and transferring each set in parallel.\n> This seems correct, however, your patch is also creating a new process to\n> handle each set. Is that necessary? I think we should try to achieve this\n> using multiple asynchronous libpq connections from a single basebackup\n> process. That is to use PQconnectStartParams() interface instead of\n> PQconnectdbParams(), wich is currently used by basebackup. On the server\n> side, it may still result in multiple backend processes per connection, and\n> an attempt should be made to avoid that as well, but it seems complicated.\n>\n> What do you think?\n>\n> Asim\n>\n\nThanks Asim for the feedback. This is a good suggestion. The main idea I\nwanted to discuss is the design where we can open multiple backend\nconnections to get the data instead of a single connection.\nOn the client side we can have multiple approaches, One is to use\nasynchronous APIs ( as suggested by you) and other could be to decide\nbetween multi-process and multi-thread. The main point was we can extract\nlot of performance benefit by using the multiple connections and I built\nthis POC to float the idea of how the parallel backup can work, since the\ncore logic of getting the files using multiple connections will remain the\nsame, wether we use asynchronous, multi-process or multi-threaded.\n\nI am going to address the division of files to be distributed evenly among\nmultiple workers based on file sizes, that would allow to get some concrete\nnumbers as well as it will also us to gauge some benefits between async and\nmultiprocess/thread approach on client side.\n\nRegards,\nAsif\n\nOn Fri, Aug 23, 2019 at 3:18 PM Asim R P <apraveen@pivotal.io> wrote:Hi AsifInteresting proposal.  Bulk of the work in a backup is transferring files from source data directory to destination.  Your patch is breaking this task down in multiple sets of files and transferring each set in parallel.  This seems correct, however, your patch is also creating a new process to handle each set.  Is that necessary?  I think we should try to achieve this using multiple asynchronous libpq connections from a single basebackup process.  That is to use PQconnectStartParams() interface instead of PQconnectdbParams(), wich is currently used by basebackup.  On the server side, it may still result in multiple backend processes per connection, and an attempt should be made to avoid that as well, but it seems complicated.What do you think?AsimThanks Asim for the feedback. This is a good suggestion. The main idea I wanted to discuss is the design where we can open multiple backend connections to get the data instead of a single connection.On the client side we can have multiple approaches, One is to use asynchronous APIs ( as suggested by you) and other could be to decide between multi-process and multi-thread. The main point was we can extract lot of performance benefit by using the multiple connections and I built this POC to float the idea of how the parallel backup can work, since the core logic of getting the files using multiple connections will remain the same, wether we use asynchronous, multi-process or multi-threaded.I am going to address the division of files to be distributed evenly among multiple workers based on file sizes, that would allow to get some concrete numbers as well as it will also us to gauge some benefits between async and multiprocess/thread approach on client side.Regards,Asif", "msg_date": "Fri, 23 Aug 2019 21:04:07 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Greetings,\n\n* Asif Rehman (asifr.rehman@gmail.com) wrote:\n> On Fri, Aug 23, 2019 at 3:18 PM Asim R P <apraveen@pivotal.io> wrote:\n> > Interesting proposal. Bulk of the work in a backup is transferring files\n> > from source data directory to destination. Your patch is breaking this\n> > task down in multiple sets of files and transferring each set in parallel.\n> > This seems correct, however, your patch is also creating a new process to\n> > handle each set. Is that necessary? I think we should try to achieve this\n> > using multiple asynchronous libpq connections from a single basebackup\n> > process. That is to use PQconnectStartParams() interface instead of\n> > PQconnectdbParams(), wich is currently used by basebackup. On the server\n> > side, it may still result in multiple backend processes per connection, and\n> > an attempt should be made to avoid that as well, but it seems complicated.\n> \n> Thanks Asim for the feedback. This is a good suggestion. The main idea I\n> wanted to discuss is the design where we can open multiple backend\n> connections to get the data instead of a single connection.\n> On the client side we can have multiple approaches, One is to use\n> asynchronous APIs ( as suggested by you) and other could be to decide\n> between multi-process and multi-thread. The main point was we can extract\n> lot of performance benefit by using the multiple connections and I built\n> this POC to float the idea of how the parallel backup can work, since the\n> core logic of getting the files using multiple connections will remain the\n> same, wether we use asynchronous, multi-process or multi-threaded.\n> \n> I am going to address the division of files to be distributed evenly among\n> multiple workers based on file sizes, that would allow to get some concrete\n> numbers as well as it will also us to gauge some benefits between async and\n> multiprocess/thread approach on client side.\n\nI would expect you to quickly want to support compression on the server\nside, before the data is sent across the network, and possibly\nencryption, and so it'd likely make sense to just have independent\nprocesses and connections through which to do that.\n\nThanks,\n\nStephen", "msg_date": "Fri, 23 Aug 2019 13:26:38 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Fri, Aug 23, 2019 at 10:26 PM Stephen Frost <sfrost@snowman.net> wrote:\n\n> Greetings,\n>\n> * Asif Rehman (asifr.rehman@gmail.com) wrote:\n> > On Fri, Aug 23, 2019 at 3:18 PM Asim R P <apraveen@pivotal.io> wrote:\n> > > Interesting proposal. Bulk of the work in a backup is transferring\n> files\n> > > from source data directory to destination. Your patch is breaking this\n> > > task down in multiple sets of files and transferring each set in\n> parallel.\n> > > This seems correct, however, your patch is also creating a new process\n> to\n> > > handle each set. Is that necessary? I think we should try to achieve\n> this\n> > > using multiple asynchronous libpq connections from a single basebackup\n> > > process. That is to use PQconnectStartParams() interface instead of\n> > > PQconnectdbParams(), wich is currently used by basebackup. On the\n> server\n> > > side, it may still result in multiple backend processes per\n> connection, and\n> > > an attempt should be made to avoid that as well, but it seems\n> complicated.\n> >\n> > Thanks Asim for the feedback. This is a good suggestion. The main idea I\n> > wanted to discuss is the design where we can open multiple backend\n> > connections to get the data instead of a single connection.\n> > On the client side we can have multiple approaches, One is to use\n> > asynchronous APIs ( as suggested by you) and other could be to decide\n> > between multi-process and multi-thread. The main point was we can extract\n> > lot of performance benefit by using the multiple connections and I built\n> > this POC to float the idea of how the parallel backup can work, since the\n> > core logic of getting the files using multiple connections will remain\n> the\n> > same, wether we use asynchronous, multi-process or multi-threaded.\n> >\n> > I am going to address the division of files to be distributed evenly\n> among\n> > multiple workers based on file sizes, that would allow to get some\n> concrete\n> > numbers as well as it will also us to gauge some benefits between async\n> and\n> > multiprocess/thread approach on client side.\n>\n> I would expect you to quickly want to support compression on the server\n> side, before the data is sent across the network, and possibly\n> encryption, and so it'd likely make sense to just have independent\n> processes and connections through which to do that.\n>\n> +1 for compression and encryption, but I think parallelism will give us\nthe benefit with and without the compression.\n\nThanks,\n>\n> Stephen\n>\n\n\n-- \nIbrar Ahmed\n\nOn Fri, Aug 23, 2019 at 10:26 PM Stephen Frost <sfrost@snowman.net> wrote:Greetings,\n\n* Asif Rehman (asifr.rehman@gmail.com) wrote:\n> On Fri, Aug 23, 2019 at 3:18 PM Asim R P <apraveen@pivotal.io> wrote:\n> > Interesting proposal.  Bulk of the work in a backup is transferring files\n> > from source data directory to destination.  Your patch is breaking this\n> > task down in multiple sets of files and transferring each set in parallel.\n> > This seems correct, however, your patch is also creating a new process to\n> > handle each set.  Is that necessary?  I think we should try to achieve this\n> > using multiple asynchronous libpq connections from a single basebackup\n> > process.  That is to use PQconnectStartParams() interface instead of\n> > PQconnectdbParams(), wich is currently used by basebackup.  On the server\n> > side, it may still result in multiple backend processes per connection, and\n> > an attempt should be made to avoid that as well, but it seems complicated.\n> \n> Thanks Asim for the feedback. This is a good suggestion. The main idea I\n> wanted to discuss is the design where we can open multiple backend\n> connections to get the data instead of a single connection.\n> On the client side we can have multiple approaches, One is to use\n> asynchronous APIs ( as suggested by you) and other could be to decide\n> between multi-process and multi-thread. The main point was we can extract\n> lot of performance benefit by using the multiple connections and I built\n> this POC to float the idea of how the parallel backup can work, since the\n> core logic of getting the files using multiple connections will remain the\n> same, wether we use asynchronous, multi-process or multi-threaded.\n> \n> I am going to address the division of files to be distributed evenly among\n> multiple workers based on file sizes, that would allow to get some concrete\n> numbers as well as it will also us to gauge some benefits between async and\n> multiprocess/thread approach on client side.\n\nI would expect you to quickly want to support compression on the server\nside, before the data is sent across the network, and possibly\nencryption, and so it'd likely make sense to just have independent\nprocesses and connections through which to do that.+1 for compression and encryption, but I think parallelism will give us the benefit with and without the compression.\nThanks,\n\nStephen\n-- Ibrar Ahmed", "msg_date": "Fri, 23 Aug 2019 22:50:09 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Fri, 23 Aug 2019 at 10:26 PM, Stephen Frost <sfrost@snowman.net> wrote:\n\n> Greetings,\n>\n> * Asif Rehman (asifr.rehman@gmail.com) wrote:\n> > On Fri, Aug 23, 2019 at 3:18 PM Asim R P <apraveen@pivotal.io> wrote:\n> > > Interesting proposal. Bulk of the work in a backup is transferring\n> files\n> > > from source data directory to destination. Your patch is breaking this\n> > > task down in multiple sets of files and transferring each set in\n> parallel.\n> > > This seems correct, however, your patch is also creating a new process\n> to\n> > > handle each set. Is that necessary? I think we should try to achieve\n> this\n> > > using multiple asynchronous libpq connections from a single basebackup\n> > > process. That is to use PQconnectStartParams() interface instead of\n> > > PQconnectdbParams(), wich is currently used by basebackup. On the\n> server\n> > > side, it may still result in multiple backend processes per\n> connection, and\n> > > an attempt should be made to avoid that as well, but it seems\n> complicated.\n> >\n> > Thanks Asim for the feedback. This is a good suggestion. The main idea I\n> > wanted to discuss is the design where we can open multiple backend\n> > connections to get the data instead of a single connection.\n> > On the client side we can have multiple approaches, One is to use\n> > asynchronous APIs ( as suggested by you) and other could be to decide\n> > between multi-process and multi-thread. The main point was we can extract\n> > lot of performance benefit by using the multiple connections and I built\n> > this POC to float the idea of how the parallel backup can work, since the\n> > core logic of getting the files using multiple connections will remain\n> the\n> > same, wether we use asynchronous, multi-process or multi-threaded.\n> >\n> > I am going to address the division of files to be distributed evenly\n> among\n> > multiple workers based on file sizes, that would allow to get some\n> concrete\n> > numbers as well as it will also us to gauge some benefits between async\n> and\n> > multiprocess/thread approach on client side.\n>\n> I would expect you to quickly want to support compression on the server\n> side, before the data is sent across the network, and possibly\n> encryption, and so it'd likely make sense to just have independent\n> processes and connections through which to do that.\n\n\nIt would be interesting to see the benefits of compression (before the data\nis transferred over the network) on top of parallelism. Since there is also\nsome overhead associated with performing the compression. I agree with your\nsuggestion of trying to add parallelism first and then try compression\nbefore the data is sent across the network.\n\n\n>\n> Thanks,\n>\n> Stephen\n>\n\nOn Fri, 23 Aug 2019 at 10:26 PM, Stephen Frost <sfrost@snowman.net> wrote:Greetings,\n\n* Asif Rehman (asifr.rehman@gmail.com) wrote:\n> On Fri, Aug 23, 2019 at 3:18 PM Asim R P <apraveen@pivotal.io> wrote:\n> > Interesting proposal.  Bulk of the work in a backup is transferring files\n> > from source data directory to destination.  Your patch is breaking this\n> > task down in multiple sets of files and transferring each set in parallel.\n> > This seems correct, however, your patch is also creating a new process to\n> > handle each set.  Is that necessary?  I think we should try to achieve this\n> > using multiple asynchronous libpq connections from a single basebackup\n> > process.  That is to use PQconnectStartParams() interface instead of\n> > PQconnectdbParams(), wich is currently used by basebackup.  On the server\n> > side, it may still result in multiple backend processes per connection, and\n> > an attempt should be made to avoid that as well, but it seems complicated.\n> \n> Thanks Asim for the feedback. This is a good suggestion. The main idea I\n> wanted to discuss is the design where we can open multiple backend\n> connections to get the data instead of a single connection.\n> On the client side we can have multiple approaches, One is to use\n> asynchronous APIs ( as suggested by you) and other could be to decide\n> between multi-process and multi-thread. The main point was we can extract\n> lot of performance benefit by using the multiple connections and I built\n> this POC to float the idea of how the parallel backup can work, since the\n> core logic of getting the files using multiple connections will remain the\n> same, wether we use asynchronous, multi-process or multi-threaded.\n> \n> I am going to address the division of files to be distributed evenly among\n> multiple workers based on file sizes, that would allow to get some concrete\n> numbers as well as it will also us to gauge some benefits between async and\n> multiprocess/thread approach on client side.\n\nI would expect you to quickly want to support compression on the server\nside, before the data is sent across the network, and possibly\nencryption, and so it'd likely make sense to just have independent\nprocesses and connections through which to do that.It would be interesting to see the benefits of compression (before the data is transferred over the network) on top of parallelism. Since there is also some overhead associated with performing the compression. I agree with your suggestion of trying to add parallelism first and then try compression before the data is sent across the network.\n\nThanks,\n\nStephen", "msg_date": "Sat, 24 Aug 2019 00:15:32 +0500", "msg_from": "Ahsan Hadi <ahsan.hadi@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Greetings,\n\n* Ahsan Hadi (ahsan.hadi@gmail.com) wrote:\n> On Fri, 23 Aug 2019 at 10:26 PM, Stephen Frost <sfrost@snowman.net> wrote:\n> > I would expect you to quickly want to support compression on the server\n> > side, before the data is sent across the network, and possibly\n> > encryption, and so it'd likely make sense to just have independent\n> > processes and connections through which to do that.\n> \n> It would be interesting to see the benefits of compression (before the data\n> is transferred over the network) on top of parallelism. Since there is also\n> some overhead associated with performing the compression. I agree with your\n> suggestion of trying to add parallelism first and then try compression\n> before the data is sent across the network.\n\nYou're welcome to take a look at pgbackrest for insight and to play with\nregarding compression-before-transfer, how best to split up the files\nand order them, encryption, et al. We've put quite a bit of effort into\nfiguring all of that out.\n\nThanks!\n\nStephen", "msg_date": "Fri, 23 Aug 2019 15:42:54 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, Aug 21, 2019 at 9:53 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> - BASE_BACKUP [PARALLEL] - returns a list of files in PGDATA\n> If the parallel option is there, then it will only do pg_start_backup, scans PGDATA and sends a list of file names.\n\nSo IIUC, this would mean that BASE_BACKUP without PARALLEL returns\ntarfiles, and BASE_BACKUP with PARALLEL returns a result set with a\nlist of file names. I don't think that's a good approach. It's too\nconfusing to have one replication command that returns totally\ndifferent things depending on whether some option is given.\n\n> - SEND_FILES_CONTENTS (file1, file2,...) - returns the files in given list.\n> pg_basebackup will then send back a list of filenames in this command. This commands will be send by each worker and that worker will be getting the said files.\n\nSeems reasonable, but I think you should just pass one file name and\nuse the command multiple times, once per file.\n\n> - STOP_BACKUP\n> when all workers finish then, pg_basebackup will send STOP_BACKUP command.\n\nThis also seems reasonable, but surely the matching command should\nthen be called START_BACKUP, not BASEBACKUP PARALLEL.\n\n> I have done a basic proof of concenpt (POC), which is also attached. I would appreciate some input on this. So far, I am simply dividing the list equally and assigning them to worker processes. I intend to fine tune this by taking into consideration file sizes. Further to add tar format support, I am considering that each worker process, processes all files belonging to a tablespace in its list (i.e. creates and copies tar file), before it processes the next tablespace. As a result, this will create tar files that are disjointed with respect tablespace data. For example:\n\nInstead of doing this, I suggest that you should just maintain a list\nof all the files that need to be fetched and have each worker pull a\nfile from the head of the list and fetch it when it finishes receiving\nthe previous file. That way, if some connections go faster or slower\nthan others, the distribution of work ends up fairly even. If you\ninstead pre-distribute the work, you're guessing what's going to\nhappen in the future instead of just waiting to see what actually does\nhappen. Guessing isn't intrinsically bad, but guessing when you could\nbe sure of doing the right thing *is* bad.\n\nIf you want to be really fancy, you could start by sorting the files\nin descending order of size, so that big files are fetched before\nsmall ones. Since the largest possible file is 1GB and any database\nwhere this feature is important is probably hundreds or thousands of\nGB, this may not be very important. I suggest not worrying about it\nfor v1.\n\n> Say, tablespace t1 has 20 files and we have 5 worker processes and tablespace t2 has 10. Ignoring all other factors for the sake of this example, each worker process will get a group of 4 files of t1 and 2 files of t2. Each process will create 2 tar files, one for t1 containing 4 files and another for t2 containing 2 files.\n\nThis is one of several possible approaches. If we're doing a\nplain-format backup in parallel, we can just write each file where it\nneeds to go and call it good. But, with a tar-format backup, what\nshould we do? I can see three options:\n\n1. Error! Tar format parallel backups are not supported.\n\n2. Write multiple tar files. The user might reasonably expect that\nthey're going to end up with the same files at the end of the backup\nregardless of whether they do it in parallel. A user with this\nexpectation will be disappointed.\n\n3. Write one tar file. In this design, the workers have to take turns\nwriting to the tar file, so you need some synchronization around that.\nPerhaps you'd have N threads that read and buffer a file, and N+1\nbuffers. Then you have one additional thread that reads the complete\nfiles from the buffers and writes them to the tar file. There's\nobviously some possibility that the writer won't be able to keep up\nand writing the backup will therefore be slower than it would be with\napproach (2).\n\nThere's probably also a possibility that approach (2) would thrash the\ndisk head back and forth between multiple files that are all being\nwritten at the same time, and approach (3) will therefore win by not\nthrashing the disk head. But, since spinning media are becoming less\nand less popular and are likely to have multiple disk heads under the\nhood when they are used, this is probably not too likely.\n\nI think your choice to go with approach (2) is probably reasonable,\nbut I'm not sure whether everyone will agree.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 24 Sep 2019 13:53:03 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Robert,\n\nThanks for the feedback. Please see the comments below:\n\nOn Tue, Sep 24, 2019 at 10:53 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Wed, Aug 21, 2019 at 9:53 AM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n> > - BASE_BACKUP [PARALLEL] - returns a list of files in PGDATA\n> > If the parallel option is there, then it will only do pg_start_backup,\n> scans PGDATA and sends a list of file names.\n>\n> So IIUC, this would mean that BASE_BACKUP without PARALLEL returns\n> tarfiles, and BASE_BACKUP with PARALLEL returns a result set with a\n> list of file names. I don't think that's a good approach. It's too\n> confusing to have one replication command that returns totally\n> different things depending on whether some option is given.\n>\n\nSure. I will add a separate command (START_BACKUP) for parallel.\n\n\n> > - SEND_FILES_CONTENTS (file1, file2,...) - returns the files in given\n> list.\n> > pg_basebackup will then send back a list of filenames in this command.\n> This commands will be send by each worker and that worker will be getting\n> the said files.\n>\n> Seems reasonable, but I think you should just pass one file name and\n> use the command multiple times, once per file.\n>\n\nI considered this approach initially, however, I adopted the current\nstrategy to avoid multiple round trips between the server and clients and\nsave on query processing time by issuing a single command rather than\nmultiple ones. Further fetching multiple files at once will also aid in\nsupporting the tar format by utilising the existing ReceiveTarFile()\nfunction and will be able to create a tarball for per tablespace per worker.\n\n\n>\n> > - STOP_BACKUP\n> > when all workers finish then, pg_basebackup will send STOP_BACKUP\n> command.\n>\n> This also seems reasonable, but surely the matching command should\n> then be called START_BACKUP, not BASEBACKUP PARALLEL.\n>\n> > I have done a basic proof of concenpt (POC), which is also attached. I\n> would appreciate some input on this. So far, I am simply dividing the list\n> equally and assigning them to worker processes. I intend to fine tune this\n> by taking into consideration file sizes. Further to add tar format support,\n> I am considering that each worker process, processes all files belonging to\n> a tablespace in its list (i.e. creates and copies tar file), before it\n> processes the next tablespace. As a result, this will create tar files that\n> are disjointed with respect tablespace data. For example:\n>\n> Instead of doing this, I suggest that you should just maintain a list\n> of all the files that need to be fetched and have each worker pull a\n> file from the head of the list and fetch it when it finishes receiving\n> the previous file. That way, if some connections go faster or slower\n> than others, the distribution of work ends up fairly even. If you\n> instead pre-distribute the work, you're guessing what's going to\n> happen in the future instead of just waiting to see what actually does\n> happen. Guessing isn't intrinsically bad, but guessing when you could\n> be sure of doing the right thing *is* bad.\n>\n> If you want to be really fancy, you could start by sorting the files\n> in descending order of size, so that big files are fetched before\n> small ones. Since the largest possible file is 1GB and any database\n> where this feature is important is probably hundreds or thousands of\n> GB, this may not be very important. I suggest not worrying about it\n> for v1.\n>\n\nIdeally, I would like to support the tar format as well, which would be\nmuch easier to implement when fetching multiple files at once since that\nwould enable using the existent functionality to be used without much\nchange.\n\nYour idea of sorting the files in descending order of size seems very\nappealing. I think we can do this and have the file divided among the\nworkers one by one i.e. the first file in the list goes to worker 1, the\nsecond to process 2, and so on and so forth.\n\n\n>\n> > Say, tablespace t1 has 20 files and we have 5 worker processes and\n> tablespace t2 has 10. Ignoring all other factors for the sake of this\n> example, each worker process will get a group of 4 files of t1 and 2 files\n> of t2. Each process will create 2 tar files, one for t1 containing 4 files\n> and another for t2 containing 2 files.\n>\n> This is one of several possible approaches. If we're doing a\n> plain-format backup in parallel, we can just write each file where it\n> needs to go and call it good. But, with a tar-format backup, what\n> should we do? I can see three options:\n>\n> 1. Error! Tar format parallel backups are not supported.\n>\n> 2. Write multiple tar files. The user might reasonably expect that\n> they're going to end up with the same files at the end of the backup\n> regardless of whether they do it in parallel. A user with this\n> expectation will be disappointed.\n>\n> 3. Write one tar file. In this design, the workers have to take turns\n> writing to the tar file, so you need some synchronization around that.\n> Perhaps you'd have N threads that read and buffer a file, and N+1\n> buffers. Then you have one additional thread that reads the complete\n> files from the buffers and writes them to the tar file. There's\n> obviously some possibility that the writer won't be able to keep up\n> and writing the backup will therefore be slower than it would be with\n> approach (2).\n>\n> There's probably also a possibility that approach (2) would thrash the\n> disk head back and forth between multiple files that are all being\n> written at the same time, and approach (3) will therefore win by not\n> thrashing the disk head. But, since spinning media are becoming less\n> and less popular and are likely to have multiple disk heads under the\n> hood when they are used, this is probably not too likely.\n>\n> I think your choice to go with approach (2) is probably reasonable,\n> but I'm not sure whether everyone will agree.\n>\n\nYes for the tar format support, approach (2) is what I had in\nmind. Currently I'm working on the implementation and will share the patch\nin a couple of days.\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nHi Robert,Thanks for the feedback. Please see the comments below:On Tue, Sep 24, 2019 at 10:53 PM Robert Haas <robertmhaas@gmail.com> wrote:On Wed, Aug 21, 2019 at 9:53 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> - BASE_BACKUP [PARALLEL] - returns a list of files in PGDATA\n> If the parallel option is there, then it will only do pg_start_backup, scans PGDATA and sends a list of file names.\n\nSo IIUC, this would mean that BASE_BACKUP without PARALLEL returns\ntarfiles, and BASE_BACKUP with PARALLEL returns a result set with a\nlist of file names. I don't think that's a good approach. It's too\nconfusing to have one replication command that returns totally\ndifferent things depending on whether some option is given.Sure. I will add a separate command (START_BACKUP)  for parallel.\n\n> - SEND_FILES_CONTENTS (file1, file2,...) - returns the files in given list.\n> pg_basebackup will then send back a list of filenames in this command. This commands will be send by each worker and that worker will be getting the said files.\n\nSeems reasonable, but I think you should just pass one file name and\nuse the command multiple times, once per file.I considered this approach initially,  however, I adopted the current strategy to avoid multiple round trips between the server and clients and save on query processing time by issuing a single command rather than multiple ones. Further fetching multiple files at once will also aid in supporting the tar format by utilising the existing ReceiveTarFile() function and will be able to create a tarball for per tablespace per worker.  \n\n> - STOP_BACKUP\n> when all workers finish then, pg_basebackup will send STOP_BACKUP command.\n\nThis also seems reasonable, but surely the matching command should\nthen be called START_BACKUP, not BASEBACKUP PARALLEL.\n\n> I have done a basic proof of concenpt (POC), which is also attached. I would appreciate some input on this. So far, I am simply dividing the list equally and assigning them to worker processes. I intend to fine tune this by taking into consideration file sizes. Further to add tar format support, I am considering that each worker process, processes all files belonging to a tablespace in its list (i.e. creates and copies tar file), before it processes the next tablespace. As a result, this will create tar files that are disjointed with respect tablespace data. For example:\n\nInstead of doing this, I suggest that you should just maintain a list\nof all the files that need to be fetched and have each worker pull a\nfile from the head of the list and fetch it when it finishes receiving\nthe previous file.  That way, if some connections go faster or slower\nthan others, the distribution of work ends up fairly even.  If you\ninstead pre-distribute the work, you're guessing what's going to\nhappen in the future instead of just waiting to see what actually does\nhappen. Guessing isn't intrinsically bad, but guessing when you could\nbe sure of doing the right thing *is* bad.\n\nIf you want to be really fancy, you could start by sorting the files\nin descending order of size, so that big files are fetched before\nsmall ones.  Since the largest possible file is 1GB and any database\nwhere this feature is important is probably hundreds or thousands of\nGB, this may not be very important. I suggest not worrying about it\nfor v1.Ideally, I would like to support the tar format as well, which would be much easier to implement when fetching multiple files at once since that would enable using the existent functionality to be used without much change.Your idea of sorting the files in descending order of size seems very appealing. I think we can do this and have the file divided among the workers one by one i.e. the first file in the list goes to worker 1, the second to process 2, and so on and so forth. \n\n> Say, tablespace t1 has 20 files and we have 5 worker processes and tablespace t2 has 10. Ignoring all other factors for the sake of this example, each worker process will get a group of 4 files of t1 and 2 files of t2. Each process will create 2 tar files, one for t1 containing 4 files and another for t2 containing 2 files.\n\nThis is one of several possible approaches. If we're doing a\nplain-format backup in parallel, we can just write each file where it\nneeds to go and call it good. But, with a tar-format backup, what\nshould we do? I can see three options:\n\n1. Error! Tar format parallel backups are not supported.\n\n2. Write multiple tar files. The user might reasonably expect that\nthey're going to end up with the same files at the end of the backup\nregardless of whether they do it in parallel. A user with this\nexpectation will be disappointed.\n\n3. Write one tar file. In this design, the workers have to take turns\nwriting to the tar file, so you need some synchronization around that.\nPerhaps you'd have N threads that read and buffer a file, and N+1\nbuffers.  Then you have one additional thread that reads the complete\nfiles from the buffers and writes them to the tar file. There's\nobviously some possibility that the writer won't be able to keep up\nand writing the backup will therefore be slower than it would be with\napproach (2).\n\nThere's probably also a possibility that approach (2) would thrash the\ndisk head back and forth between multiple files that are all being\nwritten at the same time, and approach (3) will therefore win by not\nthrashing the disk head. But, since spinning media are becoming less\nand less popular and are likely to have multiple disk heads under the\nhood when they are used, this is probably not too likely.\n\nI think your choice to go with approach (2) is probably reasonable,\nbut I'm not sure whether everyone will agree.Yes for the tar format support, approach (2) is what I had in mind. Currently I'm working on the implementation and will share the patch in a couple of days.--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Fri, 27 Sep 2019 21:00:01 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif,\n\nI was looking at the patch and tried comipling it. However, got few errors\nand warnings.\n\nFixed those in the attached patch.\n\nOn Fri, Sep 27, 2019 at 9:30 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n> Hi Robert,\n>\n> Thanks for the feedback. Please see the comments below:\n>\n> On Tue, Sep 24, 2019 at 10:53 PM Robert Haas <robertmhaas@gmail.com>\n> wrote:\n>\n>> On Wed, Aug 21, 2019 at 9:53 AM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>> > - BASE_BACKUP [PARALLEL] - returns a list of files in PGDATA\n>> > If the parallel option is there, then it will only do pg_start_backup,\n>> scans PGDATA and sends a list of file names.\n>>\n>> So IIUC, this would mean that BASE_BACKUP without PARALLEL returns\n>> tarfiles, and BASE_BACKUP with PARALLEL returns a result set with a\n>> list of file names. I don't think that's a good approach. It's too\n>> confusing to have one replication command that returns totally\n>> different things depending on whether some option is given.\n>>\n>\n> Sure. I will add a separate command (START_BACKUP) for parallel.\n>\n>\n>> > - SEND_FILES_CONTENTS (file1, file2,...) - returns the files in given\n>> list.\n>> > pg_basebackup will then send back a list of filenames in this command.\n>> This commands will be send by each worker and that worker will be getting\n>> the said files.\n>>\n>> Seems reasonable, but I think you should just pass one file name and\n>> use the command multiple times, once per file.\n>>\n>\n> I considered this approach initially, however, I adopted the current\n> strategy to avoid multiple round trips between the server and clients and\n> save on query processing time by issuing a single command rather than\n> multiple ones. Further fetching multiple files at once will also aid in\n> supporting the tar format by utilising the existing ReceiveTarFile()\n> function and will be able to create a tarball for per tablespace per worker.\n>\n>\n>>\n>> > - STOP_BACKUP\n>> > when all workers finish then, pg_basebackup will send STOP_BACKUP\n>> command.\n>>\n>> This also seems reasonable, but surely the matching command should\n>> then be called START_BACKUP, not BASEBACKUP PARALLEL.\n>>\n>> > I have done a basic proof of concenpt (POC), which is also attached. I\n>> would appreciate some input on this. So far, I am simply dividing the list\n>> equally and assigning them to worker processes. I intend to fine tune this\n>> by taking into consideration file sizes. Further to add tar format support,\n>> I am considering that each worker process, processes all files belonging to\n>> a tablespace in its list (i.e. creates and copies tar file), before it\n>> processes the next tablespace. As a result, this will create tar files that\n>> are disjointed with respect tablespace data. For example:\n>>\n>> Instead of doing this, I suggest that you should just maintain a list\n>> of all the files that need to be fetched and have each worker pull a\n>> file from the head of the list and fetch it when it finishes receiving\n>> the previous file. That way, if some connections go faster or slower\n>> than others, the distribution of work ends up fairly even. If you\n>> instead pre-distribute the work, you're guessing what's going to\n>> happen in the future instead of just waiting to see what actually does\n>> happen. Guessing isn't intrinsically bad, but guessing when you could\n>> be sure of doing the right thing *is* bad.\n>>\n>> If you want to be really fancy, you could start by sorting the files\n>> in descending order of size, so that big files are fetched before\n>> small ones. Since the largest possible file is 1GB and any database\n>> where this feature is important is probably hundreds or thousands of\n>> GB, this may not be very important. I suggest not worrying about it\n>> for v1.\n>>\n>\n> Ideally, I would like to support the tar format as well, which would be\n> much easier to implement when fetching multiple files at once since that\n> would enable using the existent functionality to be used without much\n> change.\n>\n> Your idea of sorting the files in descending order of size seems very\n> appealing. I think we can do this and have the file divided among the\n> workers one by one i.e. the first file in the list goes to worker 1, the\n> second to process 2, and so on and so forth.\n>\n>\n>>\n>> > Say, tablespace t1 has 20 files and we have 5 worker processes and\n>> tablespace t2 has 10. Ignoring all other factors for the sake of this\n>> example, each worker process will get a group of 4 files of t1 and 2 files\n>> of t2. Each process will create 2 tar files, one for t1 containing 4 files\n>> and another for t2 containing 2 files.\n>>\n>> This is one of several possible approaches. If we're doing a\n>> plain-format backup in parallel, we can just write each file where it\n>> needs to go and call it good. But, with a tar-format backup, what\n>> should we do? I can see three options:\n>>\n>> 1. Error! Tar format parallel backups are not supported.\n>>\n>> 2. Write multiple tar files. The user might reasonably expect that\n>> they're going to end up with the same files at the end of the backup\n>> regardless of whether they do it in parallel. A user with this\n>> expectation will be disappointed.\n>>\n>> 3. Write one tar file. In this design, the workers have to take turns\n>> writing to the tar file, so you need some synchronization around that.\n>> Perhaps you'd have N threads that read and buffer a file, and N+1\n>> buffers. Then you have one additional thread that reads the complete\n>> files from the buffers and writes them to the tar file. There's\n>> obviously some possibility that the writer won't be able to keep up\n>> and writing the backup will therefore be slower than it would be with\n>> approach (2).\n>>\n>> There's probably also a possibility that approach (2) would thrash the\n>> disk head back and forth between multiple files that are all being\n>> written at the same time, and approach (3) will therefore win by not\n>> thrashing the disk head. But, since spinning media are becoming less\n>> and less popular and are likely to have multiple disk heads under the\n>> hood when they are used, this is probably not too likely.\n>>\n>> I think your choice to go with approach (2) is probably reasonable,\n>> but I'm not sure whether everyone will agree.\n>>\n>\n> Yes for the tar format support, approach (2) is what I had in\n> mind. Currently I'm working on the implementation and will share the patch\n> in a couple of days.\n>\n>\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n\n\n-- \nJeevan Chalke\nAssociate Database Architect & Team Lead, Product Development\nEnterpriseDB Corporation\nThe Enterprise PostgreSQL Company", "msg_date": "Thu, 3 Oct 2019 17:17:31 +0530", "msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Fri, Sep 27, 2019 at 12:00 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>> > - SEND_FILES_CONTENTS (file1, file2,...) - returns the files in given list.\n>> > pg_basebackup will then send back a list of filenames in this command. This commands will be send by each worker and that worker will be getting the said files.\n>>\n>> Seems reasonable, but I think you should just pass one file name and\n>> use the command multiple times, once per file.\n>\n> I considered this approach initially, however, I adopted the current strategy to avoid multiple round trips between the server and clients and save on query processing time by issuing a single command rather than multiple ones. Further fetching multiple files at once will also aid in supporting the tar format by utilising the existing ReceiveTarFile() function and will be able to create a tarball for per tablespace per worker.\n\nI think that sending multiple filenames on a line could save some time\nwhen there are lots of very small files, because then the round-trip\noverhead could be significant.\n\nHowever, if you've got mostly big files, I think this is going to be a\nloser. It'll be fine if you're able to divide the work exactly evenly,\nbut that's pretty hard to do, because some workers may succeed in\ncopying the data faster than others for a variety of reasons: some\ndata is in memory, some data has to be read from disk, different data\nmay need to be read from different disks that run at different speeds,\nnot all the network connections may run at the same speed. Remember\nthat the backup's not done until the last worker finishes, and so\nthere may well be a significant advantage in terms of overall speed in\nputting some energy into making sure that they finish as close to each\nother in time as possible.\n\nTo put that another way, the first time all the workers except one get\ndone while the last one still has 10GB of data to copy, somebody's\ngoing to be unhappy.\n\n> Ideally, I would like to support the tar format as well, which would be much easier to implement when fetching multiple files at once since that would enable using the existent functionality to be used without much change.\n\nI think we should just have the client generate the tarfile. It'll\nrequire duplicating some code, but it's not actually that much code or\nthat complicated from what I can see.\n\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 3 Oct 2019 09:39:56 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Oct 3, 2019 at 6:40 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Fri, Sep 27, 2019 at 12:00 PM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n> >> > - SEND_FILES_CONTENTS (file1, file2,...) - returns the files in given\n> list.\n> >> > pg_basebackup will then send back a list of filenames in this\n> command. This commands will be send by each worker and that worker will be\n> getting the said files.\n> >>\n> >> Seems reasonable, but I think you should just pass one file name and\n> >> use the command multiple times, once per file.\n> >\n> > I considered this approach initially, however, I adopted the current\n> strategy to avoid multiple round trips between the server and clients and\n> save on query processing time by issuing a single command rather than\n> multiple ones. Further fetching multiple files at once will also aid in\n> supporting the tar format by utilising the existing ReceiveTarFile()\n> function and will be able to create a tarball for per tablespace per worker.\n>\n> I think that sending multiple filenames on a line could save some time\n> when there are lots of very small files, because then the round-trip\n> overhead could be significant.\n>\n> However, if you've got mostly big files, I think this is going to be a\n> loser. It'll be fine if you're able to divide the work exactly evenly,\n> but that's pretty hard to do, because some workers may succeed in\n> copying the data faster than others for a variety of reasons: some\n> data is in memory, some data has to be read from disk, different data\n> may need to be read from different disks that run at different speeds,\n> not all the network connections may run at the same speed. Remember\n> that the backup's not done until the last worker finishes, and so\n> there may well be a significant advantage in terms of overall speed in\n> putting some energy into making sure that they finish as close to each\n> other in time as possible.\n>\n> To put that another way, the first time all the workers except one get\n> done while the last one still has 10GB of data to copy, somebody's\n> going to be unhappy.\n>\n\nI have updated the patch (see the attached patch) to include tablespace\nsupport, tar format support and all other backup base backup options to\nwork in parallel mode as well. As previously suggested, I have removed\nBASE_BACKUP [PARALLEL] and have added START_BACKUP instead to start the\nbackup. The tar format will write multiple tar files depending upon the\nnumber of workers specified. Also made all commands\n(START_BACKUP/SEND_FILES_CONTENT/STOP_BACKUP) to accept the\nbase_backup_opt_list. This way the command-line options can also be\nprovided to these commands. Since the command-line options don't change\nonce the backup initiates, I went this way instead of storing them in\nshared state.\n\nThe START_BACKUP command will now return a sorted list of files in\ndescending order based on file sizes. This way, the larger files will be on\ntop of the list. hence these files will be assigned to workers one by one,\nmaking it so that the larger files will be copied before other files.\n\nBased on my understanding your main concern is that the files won't be\ndistributed fairly i.e one worker might get a big file and take more time\nwhile others get done early with smaller files? In this approach I have\ncreated a list of files in descending order based on there sizes so all the\nbig size files will come at the top. The maximum file size in PG is 1GB so\nif we have four workers who are picking up file from the list one by one,\nthe worst case scenario is that one worker gets a file of 1GB to process\nwhile others get files of smaller size. However with this approach of\ndescending files based on size and handing it out to workers one by one,\nthere is a very high likelihood of workers getting work evenly. does this\naddress your concerns?\n\nFurthermore the patch also includes the regression test. As t/\n010_pg_basebackup.pl test-case is testing base backup comprehensively, so I\nhave duplicated it to \"t/040_pg_basebackup_parallel.pl\" and added parallel\noption in all of its tests, to make sure parallel mode works expectantly.\nThe one thing that differs from base backup is the file checksum reporting.\nIn parallel mode, the total number of checksum failures are not reported\ncorrectly however it will abort the backup whenever a checksum failure\noccurs. This is because processes are not maintaining any shared state. I\nassume that it's not much important to report total number of failures vs\nnoticing the failure and aborting.\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Fri, 4 Oct 2019 16:01:55 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Fri, Oct 4, 2019 at 7:02 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> Based on my understanding your main concern is that the files won't be distributed fairly i.e one worker might get a big file and take more time while others get done early with smaller files? In this approach I have created a list of files in descending order based on there sizes so all the big size files will come at the top. The maximum file size in PG is 1GB so if we have four workers who are picking up file from the list one by one, the worst case scenario is that one worker gets a file of 1GB to process while others get files of smaller size. However with this approach of descending files based on size and handing it out to workers one by one, there is a very high likelihood of workers getting work evenly. does this address your concerns?\n\nSomewhat, but I'm not sure it's good enough. There are lots of reasons\nwhy two processes that are started at the same time with the same\namount of work might not finish at the same time.\n\nI'm also not particularly excited about having the server do the\nsorting based on file size. Seems like that ought to be the client's\njob, if the client needs the sorting.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 4 Oct 2019 08:07:42 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Thanks Asif for the patch. I am opting this for a review. Patch is\nbit big, so here are very initial comments to make the review process\neasier.\n\n1) Patch seems doing lot of code shuffling, I think it would be easy\nto review if you can break the clean up patch separately.\n\nExample:\na: setup_throttle\nb: include_wal_files\n\n2) As I can see this patch basically have three major phase.\n\na) Introducing new commands like START_BACKUP, SEND_FILES_CONTENT and\nSTOP_BACKUP.\nb) Implementation of actual parallel backup.\nc) Testcase\n\nI would suggest, if you can break out in three as a separate patch that\nwould be nice. It will benefit in reviewing the patch.\n\n3) In your patch you are preparing the backup manifest (file which\ngiving the information about the data files). Robert Haas, submitted\nthe backup manifests patch on another thread [1], and I think we\nshould use that patch to get the backup manifests for parallel backup.\n\nFurther, I will continue to review patch but meanwhile if you can\nbreak the patches - so that review process be easier.\n\n[1]\nhttps://www.postgresql.org/message-id/CA+TgmoZV8dw1H2bzZ9xkKwdrk8+XYa+DC9H=F7heO2zna5T6qg@mail.gmail.com\n\nThanks,\n\nOn Fri, Oct 4, 2019 at 4:32 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Thu, Oct 3, 2019 at 6:40 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n>> On Fri, Sep 27, 2019 at 12:00 PM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>> >> > - SEND_FILES_CONTENTS (file1, file2,...) - returns the files in\n>> given list.\n>> >> > pg_basebackup will then send back a list of filenames in this\n>> command. This commands will be send by each worker and that worker will be\n>> getting the said files.\n>> >>\n>> >> Seems reasonable, but I think you should just pass one file name and\n>> >> use the command multiple times, once per file.\n>> >\n>> > I considered this approach initially, however, I adopted the current\n>> strategy to avoid multiple round trips between the server and clients and\n>> save on query processing time by issuing a single command rather than\n>> multiple ones. Further fetching multiple files at once will also aid in\n>> supporting the tar format by utilising the existing ReceiveTarFile()\n>> function and will be able to create a tarball for per tablespace per worker.\n>>\n>> I think that sending multiple filenames on a line could save some time\n>> when there are lots of very small files, because then the round-trip\n>> overhead could be significant.\n>>\n>> However, if you've got mostly big files, I think this is going to be a\n>> loser. It'll be fine if you're able to divide the work exactly evenly,\n>> but that's pretty hard to do, because some workers may succeed in\n>> copying the data faster than others for a variety of reasons: some\n>> data is in memory, some data has to be read from disk, different data\n>> may need to be read from different disks that run at different speeds,\n>> not all the network connections may run at the same speed. Remember\n>> that the backup's not done until the last worker finishes, and so\n>> there may well be a significant advantage in terms of overall speed in\n>> putting some energy into making sure that they finish as close to each\n>> other in time as possible.\n>>\n>> To put that another way, the first time all the workers except one get\n>> done while the last one still has 10GB of data to copy, somebody's\n>> going to be unhappy.\n>>\n>\n> I have updated the patch (see the attached patch) to include tablespace\n> support, tar format support and all other backup base backup options to\n> work in parallel mode as well. As previously suggested, I have removed\n> BASE_BACKUP [PARALLEL] and have added START_BACKUP instead to start the\n> backup. The tar format will write multiple tar files depending upon the\n> number of workers specified. Also made all commands\n> (START_BACKUP/SEND_FILES_CONTENT/STOP_BACKUP) to accept the\n> base_backup_opt_list. This way the command-line options can also be\n> provided to these commands. Since the command-line options don't change\n> once the backup initiates, I went this way instead of storing them in\n> shared state.\n>\n> The START_BACKUP command will now return a sorted list of files in\n> descending order based on file sizes. This way, the larger files will be on\n> top of the list. hence these files will be assigned to workers one by one,\n> making it so that the larger files will be copied before other files.\n>\n> Based on my understanding your main concern is that the files won't be\n> distributed fairly i.e one worker might get a big file and take more time\n> while others get done early with smaller files? In this approach I have\n> created a list of files in descending order based on there sizes so all the\n> big size files will come at the top. The maximum file size in PG is 1GB so\n> if we have four workers who are picking up file from the list one by one,\n> the worst case scenario is that one worker gets a file of 1GB to process\n> while others get files of smaller size. However with this approach of\n> descending files based on size and handing it out to workers one by one,\n> there is a very high likelihood of workers getting work evenly. does this\n> address your concerns?\n>\n> Furthermore the patch also includes the regression test. As t/\n> 010_pg_basebackup.pl test-case is testing base backup comprehensively, so\n> I have duplicated it to \"t/040_pg_basebackup_parallel.pl\" and added\n> parallel option in all of its tests, to make sure parallel mode works\n> expectantly. The one thing that differs from base backup is the file\n> checksum reporting. In parallel mode, the total number of checksum failures\n> are not reported correctly however it will abort the backup whenever a\n> checksum failure occurs. This is because processes are not maintaining any\n> shared state. I assume that it's not much important to report total number\n> of failures vs noticing the failure and aborting.\n>\n>\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\n-- \nRushabh Lathia\n\nThanks Asif for the patch.  I am opting this for a review.  Patch isbit big, so here are very initial comments to make the review processeasier.1) Patch seems doing lot of code shuffling, I think it would be easyto review if you can break the clean up patch separately.Example:a: setup_throttleb: include_wal_files2) As I can see this patch basically have three major phase.a) Introducing new commands like START_BACKUP, SEND_FILES_CONTENT andSTOP_BACKUP.b) Implementation of actual parallel backup.c) TestcaseI would suggest, if you can break out in three as a separate patch thatwould be nice.  It will benefit in reviewing the patch.3) In your patch you are preparing the backup manifest (file whichgiving the information about the data files). Robert Haas, submittedthe backup manifests patch on another thread [1], and I think weshould use that patch to get the backup manifests for parallel backup.Further, I will continue to review patch but meanwhile if you canbreak the patches - so that review process be easier.[1] https://www.postgresql.org/message-id/CA+TgmoZV8dw1H2bzZ9xkKwdrk8+XYa+DC9H=F7heO2zna5T6qg@mail.gmail.comThanks,On Fri, Oct 4, 2019 at 4:32 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Thu, Oct 3, 2019 at 6:40 PM Robert Haas <robertmhaas@gmail.com> wrote:On Fri, Sep 27, 2019 at 12:00 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>> > - SEND_FILES_CONTENTS (file1, file2,...) - returns the files in given list.\n>> > pg_basebackup will then send back a list of filenames in this command. This commands will be send by each worker and that worker will be getting the said files.\n>>\n>> Seems reasonable, but I think you should just pass one file name and\n>> use the command multiple times, once per file.\n>\n> I considered this approach initially,  however, I adopted the current strategy to avoid multiple round trips between the server and clients and save on query processing time by issuing a single command rather than multiple ones. Further fetching multiple files at once will also aid in supporting the tar format by utilising the existing ReceiveTarFile() function and will be able to create a tarball for per tablespace per worker.\n\nI think that sending multiple filenames on a line could save some time\nwhen there are lots of very small files, because then the round-trip\noverhead could be significant.\n\nHowever, if you've got mostly big files, I think this is going to be a\nloser. It'll be fine if you're able to divide the work exactly evenly,\nbut that's pretty hard to do, because some workers may succeed in\ncopying the data faster than others for a variety of reasons: some\ndata is in memory, some data has to be read from disk, different data\nmay need to be read from different disks that run at different speeds,\nnot all the network connections may run at the same speed. Remember\nthat the backup's not done until the last worker finishes, and so\nthere may well be a significant advantage in terms of overall speed in\nputting some energy into making sure that they finish as close to each\nother in time as possible.\n\nTo put that another way, the first time all the workers except one get\ndone while the last one still has 10GB of data to copy, somebody's\ngoing to be unhappy.I have updated the patch (see the attached patch) to include tablespace support, tar format support and all other backup base backup options to work in parallel mode as well. As previously suggested, I have removed BASE_BACKUP [PARALLEL] and have added START_BACKUP instead to start the backup. The tar format will write multiple tar files depending upon the number of workers specified. Also made all commands (START_BACKUP/SEND_FILES_CONTENT/STOP_BACKUP) to accept the base_backup_opt_list. This way the command-line options can also be provided to these commands. Since the command-line options don't change once the backup initiates, I went this way instead of storing them in shared state.The START_BACKUP command will now return a sorted list of files in descending order based on file sizes. This way, the larger files will be on top of the list. hence these files will be assigned to workers one by one, making it so that the larger files will be copied before other files.Based on my understanding your main concern is that the files won't be distributed fairly i.e one worker might get a big file and take more time while others get done early with smaller files? In this approach I have created a list of files in descending order based on there sizes so all the big size files will come at the top. The maximum file size in PG is 1GB so if we have four workers who are picking up file from the list one by one, the worst case scenario is that one worker gets a file of 1GB to process while others get files of smaller size. However with this approach of descending files based on size and handing it out to workers one by one, there is a very high likelihood of workers getting work evenly. does this address your concerns?Furthermore the patch also includes the regression test. As t/010_pg_basebackup.pl test-case is testing base backup comprehensively, so I have duplicated it to \"t/040_pg_basebackup_parallel.pl\" and added parallel option in all of its tests, to make sure parallel mode works expectantly. The one thing that differs from base backup is the file checksum reporting. In parallel mode, the total number of checksum failures are not reported correctly however it will abort the backup whenever a checksum failure occurs. This is because processes are not maintaining any shared state. I assume that it's not much important to report total number of failures vs noticing the failure and aborting.--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- Rushabh Lathia", "msg_date": "Mon, 7 Oct 2019 14:22:36 +0530", "msg_from": "Rushabh Lathia <rushabh.lathia@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Oct 7, 2019 at 1:52 PM Rushabh Lathia <rushabh.lathia@gmail.com>\nwrote:\n\n> Thanks Asif for the patch. I am opting this for a review. Patch is\n> bit big, so here are very initial comments to make the review process\n> easier.\n>\n\nThanks Rushabh for reviewing the patch.\n\n\n> 1) Patch seems doing lot of code shuffling, I think it would be easy\n> to review if you can break the clean up patch separately.\n>\n> Example:\n> a: setup_throttle\n> b: include_wal_files\n>\n> 2) As I can see this patch basically have three major phase.\n>\n> a) Introducing new commands like START_BACKUP, SEND_FILES_CONTENT and\n> STOP_BACKUP.\n> b) Implementation of actual parallel backup.\n> c) Testcase\n>\n> I would suggest, if you can break out in three as a separate patch that\n> would be nice. It will benefit in reviewing the patch.\n>\n\nSure, why not. I will break them into multiple patches.\n\n\n>\n> 3) In your patch you are preparing the backup manifest (file which\n> giving the information about the data files). Robert Haas, submitted\n> the backup manifests patch on another thread [1], and I think we\n> should use that patch to get the backup manifests for parallel backup.\n>\n\nSure. Though the backup manifest patch calculates and includes the checksum\nof backup files and is done\nwhile the file is being transferred to the frontend-end. The manifest file\nitself is copied at the\nvery end of the backup. In parallel backup, I need the list of filenames\nbefore file contents are transferred, in\norder to divide them into multiple workers. For that, the manifest file has\nto be available when START_BACKUP\n is called.\n\nThat means, backup manifest should support its creation while excluding the\nchecksum during START_BACKUP().\nI also need the directory information as well for two reasons:\n\n- In plain format, base path has to exist before we can write the file. we\ncan extract the base path from the file\nbut doing that for all files does not seem a good idea.\n- base backup does not include the content of some directories but those\ndirectories although empty, are still\nexpected in PGDATA.\n\nI can make these changes part of parallel backup (which would be on top of\nbackup manifest patch) or\nthese changes can be done as part of manifest patch and then parallel can\nuse them.\n\nRobert what do you suggest?\n\n\n-- \nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nOn Mon, Oct 7, 2019 at 1:52 PM Rushabh Lathia <rushabh.lathia@gmail.com> wrote:Thanks Asif for the patch.  I am opting this for a review.  Patch isbit big, so here are very initial comments to make the review processeasier.Thanks Rushabh for reviewing the patch.1) Patch seems doing lot of code shuffling, I think it would be easyto review if you can break the clean up patch separately.Example:a: setup_throttleb: include_wal_files2) As I can see this patch basically have three major phase.a) Introducing new commands like START_BACKUP, SEND_FILES_CONTENT andSTOP_BACKUP.b) Implementation of actual parallel backup.c) TestcaseI would suggest, if you can break out in three as a separate patch thatwould be nice.  It will benefit in reviewing the patch.Sure, why not. I will break them into multiple patches. 3) In your patch you are preparing the backup manifest (file whichgiving the information about the data files). Robert Haas, submittedthe backup manifests patch on another thread [1], and I think weshould use that patch to get the backup manifests for parallel backup.Sure. Though the backup manifest patch calculates and includes the checksum of backup files and is donewhile the file is being transferred to the frontend-end. The manifest file itself is copied at thevery end of the backup. In parallel backup, I need the list of filenames before file contents are transferred, inorder to divide them into multiple workers. For that, the manifest file has to be available when START_BACKUP is called. That means, backup manifest should support its creation while excluding the checksum during START_BACKUP().I also need the directory information as well for two reasons:- In plain format, base path has to exist before we can write the file. we can extract the base path from the filebut doing that for all files does not seem a good idea.- base backup does not include the content of some directories but those directories although empty, are stillexpected in PGDATA.I can make these changes part of parallel backup (which would be on top of backup manifest patch) orthese changes can be done as part of manifest patch and then parallel can use them. Robert what do you suggest?-- Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Mon, 7 Oct 2019 17:48:12 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Oct 7, 2019 at 8:48 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> Sure. Though the backup manifest patch calculates and includes the checksum of backup files and is done\n> while the file is being transferred to the frontend-end. The manifest file itself is copied at the\n> very end of the backup. In parallel backup, I need the list of filenames before file contents are transferred, in\n> order to divide them into multiple workers. For that, the manifest file has to be available when START_BACKUP\n> is called.\n>\n> That means, backup manifest should support its creation while excluding the checksum during START_BACKUP().\n> I also need the directory information as well for two reasons:\n>\n> - In plain format, base path has to exist before we can write the file. we can extract the base path from the file\n> but doing that for all files does not seem a good idea.\n> - base backup does not include the content of some directories but those directories although empty, are still\n> expected in PGDATA.\n>\n> I can make these changes part of parallel backup (which would be on top of backup manifest patch) or\n> these changes can be done as part of manifest patch and then parallel can use them.\n>\n> Robert what do you suggest?\n\nI think we should probably not use backup manifests here, actually. I\ninitially thought that would be a good idea, but after further thought\nit seems like it just complicates the code to no real benefit. I\nsuggest that the START_BACKUP command just return a result set, like a\nquery, with perhaps four columns: file name, file type ('d' for\ndirectory or 'f' for file), file size, file mtime. pg_basebackup will\nignore the mtime, but some other tools might find that useful\ninformation.\n\nI wonder if we should also split START_BACKUP (which should enter\nnon-exclusive backup mode) from GET_FILE_LIST, in case some other\nclient program wants to use one of those but not the other. I think\nthat's probably a good idea, but not sure.\n\nI still think that the files should be requested one at a time, not a\nhuge long list in a single command.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Mon, 7 Oct 2019 09:05:34 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Oct 7, 2019 at 6:05 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Mon, Oct 7, 2019 at 8:48 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> > Sure. Though the backup manifest patch calculates and includes the\n> checksum of backup files and is done\n> > while the file is being transferred to the frontend-end. The manifest\n> file itself is copied at the\n> > very end of the backup. In parallel backup, I need the list of filenames\n> before file contents are transferred, in\n> > order to divide them into multiple workers. For that, the manifest file\n> has to be available when START_BACKUP\n> > is called.\n> >\n> > That means, backup manifest should support its creation while excluding\n> the checksum during START_BACKUP().\n> > I also need the directory information as well for two reasons:\n> >\n> > - In plain format, base path has to exist before we can write the file.\n> we can extract the base path from the file\n> > but doing that for all files does not seem a good idea.\n> > - base backup does not include the content of some directories but those\n> directories although empty, are still\n> > expected in PGDATA.\n> >\n> > I can make these changes part of parallel backup (which would be on top\n> of backup manifest patch) or\n> > these changes can be done as part of manifest patch and then parallel\n> can use them.\n> >\n> > Robert what do you suggest?\n>\n> I think we should probably not use backup manifests here, actually. I\n> initially thought that would be a good idea, but after further thought\n> it seems like it just complicates the code to no real benefit.\n\n\nOkay.\n\n\n> I\n> suggest that the START_BACKUP command just return a result set, like a\n> query, with perhaps four columns: file name, file type ('d' for\n> directory or 'f' for file), file size, file mtime. pg_basebackup will\n> ignore the mtime, but some other tools might find that useful\n> information.\n>\nyes current patch already returns the result set. will add the additional\ninformation.\n\n\n> I wonder if we should also split START_BACKUP (which should enter\n> non-exclusive backup mode) from GET_FILE_LIST, in case some other\n> client program wants to use one of those but not the other. I think\n> that's probably a good idea, but not sure.\n>\n\nCurrently pg_basebackup does not enter in exclusive backup mode and other\ntools have to\nuse pg_start_backup() and pg_stop_backup() functions to achieve that. Since\nwe are breaking\nbackup into multiple command, I believe it would be a good idea to have\nthis option. I will include\nit in next revision of this patch.\n\n\n>\n> I still think that the files should be requested one at a time, not a\n> huge long list in a single command.\n>\nsure, will make the change.\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nOn Mon, Oct 7, 2019 at 6:05 PM Robert Haas <robertmhaas@gmail.com> wrote:On Mon, Oct 7, 2019 at 8:48 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> Sure. Though the backup manifest patch calculates and includes the checksum of backup files and is done\n> while the file is being transferred to the frontend-end. The manifest file itself is copied at the\n> very end of the backup. In parallel backup, I need the list of filenames before file contents are transferred, in\n> order to divide them into multiple workers. For that, the manifest file has to be available when START_BACKUP\n>  is called.\n>\n> That means, backup manifest should support its creation while excluding the checksum during START_BACKUP().\n> I also need the directory information as well for two reasons:\n>\n> - In plain format, base path has to exist before we can write the file. we can extract the base path from the file\n> but doing that for all files does not seem a good idea.\n> - base backup does not include the content of some directories but those directories although empty, are still\n> expected in PGDATA.\n>\n> I can make these changes part of parallel backup (which would be on top of backup manifest patch) or\n> these changes can be done as part of manifest patch and then parallel can use them.\n>\n> Robert what do you suggest?\n\nI think we should probably not use backup manifests here, actually. I\ninitially thought that would be a good idea, but after further thought\nit seems like it just complicates the code to no real benefit.Okay.   I\nsuggest that the START_BACKUP command just return a result set, like a\nquery, with perhaps four columns: file name, file type ('d' for\ndirectory or 'f' for file), file size, file mtime. pg_basebackup will\nignore the mtime, but some other tools might find that useful\ninformation.yes current patch already returns the result set. will add the additional information.\n\nI wonder if we should also split START_BACKUP (which should enter\nnon-exclusive backup mode) from GET_FILE_LIST, in case some other\nclient program wants to use one of those but not the other.  I think\nthat's probably a good idea, but not sure.Currently pg_basebackup does not enter in exclusive backup mode and other tools have touse pg_start_backup() and pg_stop_backup() functions to achieve that. Since we are breakingbackup into multiple command, I believe it would be a good idea to have this option. I will includeit in next revision of this patch. \n\nI still think that the files should be requested one at a time, not a\nhuge long list in a single command.sure, will make the change.--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Mon, 7 Oct 2019 18:35:19 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Oct 7, 2019 at 6:06 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Mon, Oct 7, 2019 at 8:48 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> > Sure. Though the backup manifest patch calculates and includes the\n> checksum of backup files and is done\n> > while the file is being transferred to the frontend-end. The manifest\n> file itself is copied at the\n> > very end of the backup. In parallel backup, I need the list of filenames\n> before file contents are transferred, in\n> > order to divide them into multiple workers. For that, the manifest file\n> has to be available when START_BACKUP\n> > is called.\n> >\n> > That means, backup manifest should support its creation while excluding\n> the checksum during START_BACKUP().\n> > I also need the directory information as well for two reasons:\n> >\n> > - In plain format, base path has to exist before we can write the file.\n> we can extract the base path from the file\n> > but doing that for all files does not seem a good idea.\n> > - base backup does not include the content of some directories but those\n> directories although empty, are still\n> > expected in PGDATA.\n> >\n> > I can make these changes part of parallel backup (which would be on top\n> of backup manifest patch) or\n> > these changes can be done as part of manifest patch and then parallel\n> can use them.\n> >\n> > Robert what do you suggest?\n>\n> I think we should probably not use backup manifests here, actually. I\n> initially thought that would be a good idea, but after further thought\n> it seems like it just complicates the code to no real benefit. I\n> suggest that the START_BACKUP command just return a result set, like a\n> query, with perhaps four columns: file name, file type ('d' for\n> directory or 'f' for file), file size, file mtime. pg_basebackup will\n> ignore the mtime, but some other tools might find that useful\n> information.\n>\n> I wonder if we should also split START_BACKUP (which should enter\n> non-exclusive backup mode) from GET_FILE_LIST, in case some other\n> client program wants to use one of those but not the other. I think\n> that's probably a good idea, but not sure.\n>\n> I still think that the files should be requested one at a time, not a\n> huge long list in a single command.\n>\n\nWhat about have an API to get the single file or list of files? We will use\na single file in\nour application and other tools can get the benefit of list of files.\n\n>\n> --\n> Robert Haas\n> EnterpriseDB: http://www.enterprisedb.com\n> The Enterprise PostgreSQL Company\n>\n>\n>\n\n-- \nIbrar Ahmed\n\nOn Mon, Oct 7, 2019 at 6:06 PM Robert Haas <robertmhaas@gmail.com> wrote:On Mon, Oct 7, 2019 at 8:48 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> Sure. Though the backup manifest patch calculates and includes the checksum of backup files and is done\n> while the file is being transferred to the frontend-end. The manifest file itself is copied at the\n> very end of the backup. In parallel backup, I need the list of filenames before file contents are transferred, in\n> order to divide them into multiple workers. For that, the manifest file has to be available when START_BACKUP\n>  is called.\n>\n> That means, backup manifest should support its creation while excluding the checksum during START_BACKUP().\n> I also need the directory information as well for two reasons:\n>\n> - In plain format, base path has to exist before we can write the file. we can extract the base path from the file\n> but doing that for all files does not seem a good idea.\n> - base backup does not include the content of some directories but those directories although empty, are still\n> expected in PGDATA.\n>\n> I can make these changes part of parallel backup (which would be on top of backup manifest patch) or\n> these changes can be done as part of manifest patch and then parallel can use them.\n>\n> Robert what do you suggest?\n\nI think we should probably not use backup manifests here, actually. I\ninitially thought that would be a good idea, but after further thought\nit seems like it just complicates the code to no real benefit.  I\nsuggest that the START_BACKUP command just return a result set, like a\nquery, with perhaps four columns: file name, file type ('d' for\ndirectory or 'f' for file), file size, file mtime. pg_basebackup will\nignore the mtime, but some other tools might find that useful\ninformation.\n\nI wonder if we should also split START_BACKUP (which should enter\nnon-exclusive backup mode) from GET_FILE_LIST, in case some other\nclient program wants to use one of those but not the other.  I think\nthat's probably a good idea, but not sure.\n\nI still think that the files should be requested one at a time, not a\nhuge long list in a single command.What about have an API to get the single file or list of files? We will use a single file inour application and other tools can get the benefit of list of files.  \n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n-- Ibrar Ahmed", "msg_date": "Mon, 7 Oct 2019 18:43:22 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Oct 7, 2019 at 9:43 AM Ibrar Ahmed <ibrar.ahmad@gmail.com> wrote:\n> What about have an API to get the single file or list of files? We will use a single file in\n> our application and other tools can get the benefit of list of files.\n\nThat sounds a bit speculative to me. Who is to say that anyone will\nfind that useful? I mean, I think it's fine and good to build the\nfunctionality that we need in a way that maximizes the likelihood that\nother tools can reuse that functionality, and I think we should do\nthat. But I don't think it's smart to build functionality that we\ndon't really need in the hope that somebody else will find it useful\nunless we're pretty sure that they actually will. I don't see that as\nbeing the case here; YMMV.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Mon, 7 Oct 2019 09:47:29 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Oct 7, 2019 at 6:35 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Mon, Oct 7, 2019 at 6:05 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n>> On Mon, Oct 7, 2019 at 8:48 AM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>> > Sure. Though the backup manifest patch calculates and includes the\n>> checksum of backup files and is done\n>> > while the file is being transferred to the frontend-end. The manifest\n>> file itself is copied at the\n>> > very end of the backup. In parallel backup, I need the list of\n>> filenames before file contents are transferred, in\n>> > order to divide them into multiple workers. For that, the manifest file\n>> has to be available when START_BACKUP\n>> > is called.\n>> >\n>> > That means, backup manifest should support its creation while excluding\n>> the checksum during START_BACKUP().\n>> > I also need the directory information as well for two reasons:\n>> >\n>> > - In plain format, base path has to exist before we can write the file.\n>> we can extract the base path from the file\n>> > but doing that for all files does not seem a good idea.\n>> > - base backup does not include the content of some directories but\n>> those directories although empty, are still\n>> > expected in PGDATA.\n>> >\n>> > I can make these changes part of parallel backup (which would be on top\n>> of backup manifest patch) or\n>> > these changes can be done as part of manifest patch and then parallel\n>> can use them.\n>> >\n>> > Robert what do you suggest?\n>>\n>> I think we should probably not use backup manifests here, actually. I\n>> initially thought that would be a good idea, but after further thought\n>> it seems like it just complicates the code to no real benefit.\n>\n>\n> Okay.\n>\n>\n>> I\n>> suggest that the START_BACKUP command just return a result set, like a\n>> query, with perhaps four columns: file name, file type ('d' for\n>> directory or 'f' for file), file size, file mtime. pg_basebackup will\n>> ignore the mtime, but some other tools might find that useful\n>> information.\n>>\n> yes current patch already returns the result set. will add the additional\n> information.\n>\n>\n>> I wonder if we should also split START_BACKUP (which should enter\n>> non-exclusive backup mode) from GET_FILE_LIST, in case some other\n>> client program wants to use one of those but not the other. I think\n>> that's probably a good idea, but not sure.\n>>\n>\n> Currently pg_basebackup does not enter in exclusive backup mode and other\n> tools have to\n> use pg_start_backup() and pg_stop_backup() functions to achieve that.\n> Since we are breaking\n> backup into multiple command, I believe it would be a good idea to have\n> this option. I will include\n> it in next revision of this patch.\n>\n>\n>>\n>> I still think that the files should be requested one at a time, not a\n>> huge long list in a single command.\n>>\n> sure, will make the change.\n>\n>\n>\n\nI have refactored the functionality into multiple smaller patches in order\nto make the review process easier. I have divided the code into backend\nchanges and pg_basebackup changes. The\nbackend replication system now supports the following commands:\n\n- START_BACKUP\n- SEND_FILE_LIST\n- SEND_FILES_CONTENT\n- STOP_BACKUP\n\nThe START_BACKUP will not return the list of files, instead SEND_FILE_LIST\nis used for that. The START_BACKUP\nnow calls pg_start_backup and returns starting WAL position, tablespace\nheader information and content of backup label file.\nInitially I was using tmp files to store the backup_label content but that\nturns out to be bad idea, because there can be multiple\nnon-exclusive backups running. The backup label information is needed by\nstop_backup so pg_basebackup will send it as part\nof STOP_BACKUP.\n\nThe SEND_FILE_LIST will return the list of files. It will be returned as\nresultset having four columns (filename, type, size, mtime).\nThe SEND_FILES_CONTENT can now return the single file or multiple files as\nrequired. There is not much change required to\nsupport both, so I believe it will be much useable this way if other tools\nwant to utilise it.\n\nAs per suggestion from Robert, I am currently working on making changes in\npg_basebackup to fetch files one by one. However that's not complete and\nthe attach patch\nis still using the old method of multi-file fetching to test the backend\ncommands. I will send an updated patch which will contain the changes on\nfetching file one by one.\n\nI wanted to share the backend patch to get some feedback in the mean time.\n\nThanks,\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Wed, 16 Oct 2019 18:19:10 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "I quickly tried to have a look at your 0001-refactor patch.\nHere are some comments:\n\n1. The patch fails to compile.\n\nSorry if I am missing something, but am not able to understand why in new\nfunction collectTablespaces() you have added an extra parameter NULL while\ncalling sendTablespace(), it fails the compilation :\n\n+ ti->size = infotbssize ? sendTablespace(fullpath, true, NULL) : -1;\n\n\ngcc -Wall -Wmissing-prototypes -Wpointer-arith\n-Wdeclaration-after-statement -Werror=vla -Wendif-labels\n-Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv\n-Wno-unused-command-line-argument -g -g -O0 -Wall -Werror\n-I../../../../src/include -c -o xlog.o xlog.c -MMD -MP -MF .deps/xlog.Po\nxlog.c:12253:59: error: too many arguments to function call, expected 2,\nhave 3\n ti->size = infotbssize ? sendTablespace(fullpath, true,\nNULL) : -1;\n ~~~~~~~~~~~~~~ ^~~~\n\n2. I think the patch needs to run via pg_indent. It does not follow 80\ncolumn\nwidth.\ne.g.\n\n+void\n+collectTablespaces(List **tablespaces, StringInfo tblspcmapfile, bool\ninfotbssize, bool needtblspcmapfile)\n+{\n\n3.\nThe comments in re-factored code appear to be redundant. example:\nFollowing comment:\n /* Setup and activate network throttling, if client requested it */\nappears thrice in the code, before calling setup_throttle(), in the\nprologue of\nthe function setup_throttle(), and above the if() in that function.\nSimilarly - the comment:\n/* Collect information about all tablespaces */\nin collectTablespaces().\n\n4.\nIn function include_wal_files() why is the parameter TimeLineID i.e. endtli\nneeded. I don't see it being used in the function at all. I think you can\nsafely\nget rid of it.\n\n+include_wal_files(XLogRecPtr endptr, TimeLineID endtli)\n\nRegards,\nJeevan Ladhe\n\nOn Wed, Oct 16, 2019 at 6:49 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Mon, Oct 7, 2019 at 6:35 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>\n>>\n>>\n>> On Mon, Oct 7, 2019 at 6:05 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>>\n>>> On Mon, Oct 7, 2019 at 8:48 AM Asif Rehman <asifr.rehman@gmail.com>\n>>> wrote:\n>>> > Sure. Though the backup manifest patch calculates and includes the\n>>> checksum of backup files and is done\n>>> > while the file is being transferred to the frontend-end. The manifest\n>>> file itself is copied at the\n>>> > very end of the backup. In parallel backup, I need the list of\n>>> filenames before file contents are transferred, in\n>>> > order to divide them into multiple workers. For that, the manifest\n>>> file has to be available when START_BACKUP\n>>> > is called.\n>>> >\n>>> > That means, backup manifest should support its creation while\n>>> excluding the checksum during START_BACKUP().\n>>> > I also need the directory information as well for two reasons:\n>>> >\n>>> > - In plain format, base path has to exist before we can write the\n>>> file. we can extract the base path from the file\n>>> > but doing that for all files does not seem a good idea.\n>>> > - base backup does not include the content of some directories but\n>>> those directories although empty, are still\n>>> > expected in PGDATA.\n>>> >\n>>> > I can make these changes part of parallel backup (which would be on\n>>> top of backup manifest patch) or\n>>> > these changes can be done as part of manifest patch and then parallel\n>>> can use them.\n>>> >\n>>> > Robert what do you suggest?\n>>>\n>>> I think we should probably not use backup manifests here, actually. I\n>>> initially thought that would be a good idea, but after further thought\n>>> it seems like it just complicates the code to no real benefit.\n>>\n>>\n>> Okay.\n>>\n>>\n>>> I\n>>> suggest that the START_BACKUP command just return a result set, like a\n>>> query, with perhaps four columns: file name, file type ('d' for\n>>> directory or 'f' for file), file size, file mtime. pg_basebackup will\n>>> ignore the mtime, but some other tools might find that useful\n>>> information.\n>>>\n>> yes current patch already returns the result set. will add the additional\n>> information.\n>>\n>>\n>>> I wonder if we should also split START_BACKUP (which should enter\n>>> non-exclusive backup mode) from GET_FILE_LIST, in case some other\n>>> client program wants to use one of those but not the other. I think\n>>> that's probably a good idea, but not sure.\n>>>\n>>\n>> Currently pg_basebackup does not enter in exclusive backup mode and other\n>> tools have to\n>> use pg_start_backup() and pg_stop_backup() functions to achieve that.\n>> Since we are breaking\n>> backup into multiple command, I believe it would be a good idea to have\n>> this option. I will include\n>> it in next revision of this patch.\n>>\n>>\n>>>\n>>> I still think that the files should be requested one at a time, not a\n>>> huge long list in a single command.\n>>>\n>> sure, will make the change.\n>>\n>>\n>>\n>\n> I have refactored the functionality into multiple smaller patches in order\n> to make the review process easier. I have divided the code into backend\n> changes and pg_basebackup changes. The\n> backend replication system now supports the following commands:\n>\n> - START_BACKUP\n> - SEND_FILE_LIST\n> - SEND_FILES_CONTENT\n> - STOP_BACKUP\n>\n> The START_BACKUP will not return the list of files, instead SEND_FILE_LIST\n> is used for that. The START_BACKUP\n> now calls pg_start_backup and returns starting WAL position, tablespace\n> header information and content of backup label file.\n> Initially I was using tmp files to store the backup_label content but that\n> turns out to be bad idea, because there can be multiple\n> non-exclusive backups running. The backup label information is needed by\n> stop_backup so pg_basebackup will send it as part\n> of STOP_BACKUP.\n>\n> The SEND_FILE_LIST will return the list of files. It will be returned as\n> resultset having four columns (filename, type, size, mtime).\n> The SEND_FILES_CONTENT can now return the single file or multiple files as\n> required. There is not much change required to\n> support both, so I believe it will be much useable this way if other tools\n> want to utilise it.\n>\n> As per suggestion from Robert, I am currently working on making changes in\n> pg_basebackup to fetch files one by one. However that's not complete and\n> the attach patch\n> is still using the old method of multi-file fetching to test the backend\n> commands. I will send an updated patch which will contain the changes on\n> fetching file one by one.\n>\n> I wanted to share the backend patch to get some feedback in the mean time.\n>\n> Thanks,\n>\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\nI quickly tried to have a look at your 0001-refactor patch.Here are some comments:1. The patch fails to compile.Sorry if I am missing something, but am not able to understand why in newfunction collectTablespaces() you have added an extra parameter NULL whilecalling sendTablespace(), it fails the compilation :+ ti->size = infotbssize ? sendTablespace(fullpath, true, NULL) : -1;gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -Wno-unused-command-line-argument -g -g -O0 -Wall -Werror -I../../../../src/include    -c -o xlog.o xlog.c -MMD -MP -MF .deps/xlog.Poxlog.c:12253:59: error: too many arguments to function call, expected 2, have 3                ti->size = infotbssize ? sendTablespace(fullpath, true, NULL) : -1;                                         ~~~~~~~~~~~~~~                 ^~~~2. I think the patch needs to run via pg_indent. It does not follow 80 columnwidth.e.g.+void+collectTablespaces(List **tablespaces, StringInfo tblspcmapfile, bool infotbssize, bool needtblspcmapfile)+{3.The comments in re-factored code appear to be redundant. example:Following comment: /* Setup and activate network throttling, if client requested it */appears thrice in the code, before calling setup_throttle(), in the prologue ofthe function setup_throttle(), and above the if() in that function.Similarly - the comment:/* Collect information about all tablespaces */in collectTablespaces().4.In function include_wal_files() why is the parameter TimeLineID i.e. endtlineeded. I don't see it being used in the function at all. I think you can safelyget rid of it.+include_wal_files(XLogRecPtr endptr, TimeLineID endtli)Regards,Jeevan LadheOn Wed, Oct 16, 2019 at 6:49 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Mon, Oct 7, 2019 at 6:35 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Mon, Oct 7, 2019 at 6:05 PM Robert Haas <robertmhaas@gmail.com> wrote:On Mon, Oct 7, 2019 at 8:48 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> Sure. Though the backup manifest patch calculates and includes the checksum of backup files and is done\n> while the file is being transferred to the frontend-end. The manifest file itself is copied at the\n> very end of the backup. In parallel backup, I need the list of filenames before file contents are transferred, in\n> order to divide them into multiple workers. For that, the manifest file has to be available when START_BACKUP\n>  is called.\n>\n> That means, backup manifest should support its creation while excluding the checksum during START_BACKUP().\n> I also need the directory information as well for two reasons:\n>\n> - In plain format, base path has to exist before we can write the file. we can extract the base path from the file\n> but doing that for all files does not seem a good idea.\n> - base backup does not include the content of some directories but those directories although empty, are still\n> expected in PGDATA.\n>\n> I can make these changes part of parallel backup (which would be on top of backup manifest patch) or\n> these changes can be done as part of manifest patch and then parallel can use them.\n>\n> Robert what do you suggest?\n\nI think we should probably not use backup manifests here, actually. I\ninitially thought that would be a good idea, but after further thought\nit seems like it just complicates the code to no real benefit.Okay.   I\nsuggest that the START_BACKUP command just return a result set, like a\nquery, with perhaps four columns: file name, file type ('d' for\ndirectory or 'f' for file), file size, file mtime. pg_basebackup will\nignore the mtime, but some other tools might find that useful\ninformation.yes current patch already returns the result set. will add the additional information.\n\nI wonder if we should also split START_BACKUP (which should enter\nnon-exclusive backup mode) from GET_FILE_LIST, in case some other\nclient program wants to use one of those but not the other.  I think\nthat's probably a good idea, but not sure.Currently pg_basebackup does not enter in exclusive backup mode and other tools have touse pg_start_backup() and pg_stop_backup() functions to achieve that. Since we are breakingbackup into multiple command, I believe it would be a good idea to have this option. I will includeit in next revision of this patch. \n\nI still think that the files should be requested one at a time, not a\nhuge long list in a single command.sure, will make the change.I have refactored the functionality into multiple smaller patches in order to make the review process easier. I have divided the code into backend changes and pg_basebackup changes. Thebackend replication system now supports the following commands:- START_BACKUP- SEND_FILE_LIST- SEND_FILES_CONTENT- STOP_BACKUPThe START_BACKUP will not return the list of files, instead SEND_FILE_LIST is used for that. The START_BACKUPnow calls pg_start_backup and returns starting WAL position, tablespace header information and content of backup label file.Initially I was using tmp files to store the backup_label content but that turns out to be bad idea, because there can be multiplenon-exclusive backups running. The backup label information is needed by stop_backup so pg_basebackup will send it as partof STOP_BACKUP.The SEND_FILE_LIST will return the list of files. It will be returned as resultset having four columns (filename, type, size, mtime). The SEND_FILES_CONTENT can now return the single file or multiple files as required. There is not much change required tosupport both, so I believe it will be much useable this way if other tools want to utilise it.As per suggestion from Robert, I am currently working on making changes in pg_basebackup to fetch files one by one. However that's not complete and the attach patchis still using the old method of multi-file fetching to test the backend commands. I will send an updated patch which will contain the changes on fetching file one by one. I wanted to share the backend patch to get some feedback in the mean time.Thanks,--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Thu, 17 Oct 2019 02:02:56 +0530", "msg_from": "Jeevan Ladhe <jeevan.ladhe@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Oct 17, 2019 at 1:33 AM Jeevan Ladhe <jeevan.ladhe@enterprisedb.com>\nwrote:\n\n> I quickly tried to have a look at your 0001-refactor patch.\n> Here are some comments:\n>\n> 1. The patch fails to compile.\n>\n> Sorry if I am missing something, but am not able to understand why in new\n> function collectTablespaces() you have added an extra parameter NULL while\n> calling sendTablespace(), it fails the compilation :\n>\n> + ti->size = infotbssize ? sendTablespace(fullpath, true, NULL) : -1;\n>\n>\n> gcc -Wall -Wmissing-prototypes -Wpointer-arith\n> -Wdeclaration-after-statement -Werror=vla -Wendif-labels\n> -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv\n> -Wno-unused-command-line-argument -g -g -O0 -Wall -Werror\n> -I../../../../src/include -c -o xlog.o xlog.c -MMD -MP -MF .deps/xlog.Po\n> xlog.c:12253:59: error: too many arguments to function call, expected 2,\n> have 3\n> ti->size = infotbssize ? sendTablespace(fullpath, true,\n> NULL) : -1;\n> ~~~~~~~~~~~~~~\n> ^~~~\n>\n> 2. I think the patch needs to run via pg_indent. It does not follow 80\n> column\n> width.\n> e.g.\n>\n> +void\n> +collectTablespaces(List **tablespaces, StringInfo tblspcmapfile, bool\n> infotbssize, bool needtblspcmapfile)\n> +{\n>\n> 3.\n> The comments in re-factored code appear to be redundant. example:\n> Following comment:\n> /* Setup and activate network throttling, if client requested it */\n> appears thrice in the code, before calling setup_throttle(), in the\n> prologue of\n> the function setup_throttle(), and above the if() in that function.\n> Similarly - the comment:\n> /* Collect information about all tablespaces */\n> in collectTablespaces().\n>\n> 4.\n> In function include_wal_files() why is the parameter TimeLineID i.e. endtli\n> needed. I don't see it being used in the function at all. I think you can\n> safely\n> get rid of it.\n>\n> +include_wal_files(XLogRecPtr endptr, TimeLineID endtli)\n>\n>\nThanks Jeevan. Some changes that should be part of 2nd patch were left in\nthe 1st. I have fixed that and the above mentioned issues as well.\nAttached are the updated patches.\n\nThanks,\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Thu, 17 Oct 2019 10:21:15 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Oct 17, 2019 at 10:51 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n> Attached are the updated patches.\n>\n\nI had a quick look over these changes and they look good overall.\nHowever, here are my few review comments I caught while glancing the patches\n0002 and 0003.\n\n\n--- 0002 patch\n\n1.\nCan lsn option be renamed to start-wal-location? This will be more clear\ntoo.\n\n2.\n+typedef struct\n+{\n+ char name[MAXPGPATH];\n+ char type;\n+ int32 size;\n+ time_t mtime;\n+} BackupFile;\n\nI think it will be good if we keep this structure in a common place so that\nthe client can also use it.\n\n3.\n+ SEND_FILE_LIST,\n+ SEND_FILES_CONTENT,\nCan above two commands renamed to SEND_BACKUP_MANIFEST and SEND_BACKUP_FILE\nrespectively?\nThe reason behind the first name change is, we are not getting only file\nlists\nhere instead we are getting a few more details with that too. And for\nothers,\nit will be inline with START_BACKUP/STOP_BACKUP/SEND_BACKUP_MANIFEST.\n\n4.\nTypos:\nnon-exlusive => non-exclusive\nretured => returned\noptionaly => optionally\nnessery => necessary\ntotoal => total\n\n\n--- 0003 patch\n\n1.\n+static int\n+simple_list_length(SimpleStringList *list)\n+{\n+ int len = 0;\n+ SimpleStringListCell *cell;\n+\n+ for (cell = list->head; cell; cell = cell->next, len++)\n+ ;\n+\n+ return len;\n+}\n\nI think it will be good if it goes to simple_list.c. That will help in other\nusages as well.\n\n2.\nPlease revert these unnecessary changes:\n\n@@ -1475,6 +1575,7 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res,\nint rownum)\n */\n snprintf(filename, sizeof(filename), \"%s/%s\", current_path,\n copybuf);\n+\n if (filename[strlen(filename) - 1] == '/')\n {\n /*\n\n@@ -1528,8 +1622,8 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res,\nint rownum)\n * can map them too.)\n */\n filename[strlen(filename) - 1] = '\\0'; /* Remove\ntrailing slash */\n-\n mapped_tblspc_path =\nget_tablespace_mapping(&copybuf[157]);\n+\n if (symlink(mapped_tblspc_path, filename) != 0)\n {\n pg_log_error(\"could not create symbolic link from\n\\\"%s\\\" to \\\"%s\\\": %m\",\n\n3.\nTypos:\nretrive => retrieve\ntakecare => take care\ntablespae => tablespace\n\n4.\nParallelBackupEnd() function does not do anything for parallelism. Will it\nbe\nbetter to just rename it as EndBackup()?\n\n5.\nTo pass a tablespace path to the server in SEND_FILES_CONTENT, you are\nreusing\na LABEL option, that seems odd. How about adding a new option for that?\n\n6.\nIt will be good if we have some comments explaining what the function is\nactually doing in its prologue. For functions like:\nGetBackupFilesList()\nReceiveFiles()\ncreate_workers_and_fetch()\n\n\nThanks\n\n\n>\n> Thanks,\n>\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\n-- \nJeevan Chalke\nAssociate Database Architect & Team Lead, Product Development\nEnterpriseDB Corporation\nThe Enterprise PostgreSQL Company\n\nOn Thu, Oct 17, 2019 at 10:51 AM Asif Rehman <asifr.rehman@gmail.com> wrote:Attached are the updated patches.I had a quick look over these changes and they look good overall.However, here are my few review comments I caught while glancing the patches0002 and 0003.--- 0002 patch1.Can lsn option be renamed to start-wal-location? This will be more clear too.2.+typedef struct+{+    char        name[MAXPGPATH];+    char        type;+    int32        size;+    time_t        mtime;+} BackupFile;I think it will be good if we keep this structure in a common place so thatthe client can also use it.3.+    SEND_FILE_LIST,+    SEND_FILES_CONTENT,Can above two commands renamed to SEND_BACKUP_MANIFEST and SEND_BACKUP_FILErespectively?The reason behind the first name change is, we are not getting only file listshere instead we are getting a few more details with that too. And for others,it will be inline with START_BACKUP/STOP_BACKUP/SEND_BACKUP_MANIFEST.4.Typos:non-exlusive => non-exclusiveretured => returnedoptionaly => optionallynessery => necessarytotoal => total--- 0003 patch1.+static int+simple_list_length(SimpleStringList *list)+{+    int            len = 0;+    SimpleStringListCell *cell;++    for (cell = list->head; cell; cell = cell->next, len++)+        ;++    return len;+}I think it will be good if it goes to simple_list.c. That will help in otherusages as well.2.Please revert these unnecessary changes:@@ -1475,6 +1575,7 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)              */             snprintf(filename, sizeof(filename), \"%s/%s\", current_path,                      copybuf);+             if (filename[strlen(filename) - 1] == '/')             {                 /*@@ -1528,8 +1622,8 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)                      * can map them too.)                      */                     filename[strlen(filename) - 1] = '\\0';    /* Remove trailing slash */-                     mapped_tblspc_path = get_tablespace_mapping(&copybuf[157]);+                     if (symlink(mapped_tblspc_path, filename) != 0)                     {                         pg_log_error(\"could not create symbolic link from \\\"%s\\\" to \\\"%s\\\": %m\",3.Typos:retrive => retrievetakecare => take caretablespae => tablespace4.ParallelBackupEnd() function does not do anything for parallelism. Will it bebetter to just rename it as EndBackup()?5.To pass a tablespace path to the server in SEND_FILES_CONTENT, you are reusinga LABEL option, that seems odd. How about adding a new option for that?6.It will be good if we have some comments explaining what the function isactually doing in its prologue. For functions like:GetBackupFilesList()ReceiveFiles()create_workers_and_fetch()Thanks Thanks,--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- Jeevan ChalkeAssociate Database Architect & Team Lead, Product DevelopmentEnterpriseDB CorporationThe Enterprise PostgreSQL Company", "msg_date": "Fri, 18 Oct 2019 16:41:53 +0530", "msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Fri, Oct 18, 2019 at 4:12 PM Jeevan Chalke <\njeevan.chalke@enterprisedb.com> wrote:\n\n>\n>\n> On Thu, Oct 17, 2019 at 10:51 AM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n>\n>>\n>> Attached are the updated patches.\n>>\n>\n> I had a quick look over these changes and they look good overall.\n> However, here are my few review comments I caught while glancing the\n> patches\n> 0002 and 0003.\n>\n>\n> --- 0002 patch\n>\n> 1.\n> Can lsn option be renamed to start-wal-location? This will be more clear\n> too.\n>\n> 2.\n> +typedef struct\n> +{\n> + char name[MAXPGPATH];\n> + char type;\n> + int32 size;\n> + time_t mtime;\n> +} BackupFile;\n>\n> I think it will be good if we keep this structure in a common place so that\n> the client can also use it.\n>\n> 3.\n> + SEND_FILE_LIST,\n> + SEND_FILES_CONTENT,\n> Can above two commands renamed to SEND_BACKUP_MANIFEST and SEND_BACKUP_FILE\n> respectively?\n> The reason behind the first name change is, we are not getting only file\n> lists\n> here instead we are getting a few more details with that too. And for\n> others,\n> it will be inline with START_BACKUP/STOP_BACKUP/SEND_BACKUP_MANIFEST.\n>\n> 4.\n> Typos:\n> non-exlusive => non-exclusive\n> retured => returned\n> optionaly => optionally\n> nessery => necessary\n> totoal => total\n>\n>\n> --- 0003 patch\n>\n> 1.\n> +static int\n> +simple_list_length(SimpleStringList *list)\n> +{\n> + int len = 0;\n> + SimpleStringListCell *cell;\n> +\n> + for (cell = list->head; cell; cell = cell->next, len++)\n> + ;\n> +\n> + return len;\n> +}\n>\n> I think it will be good if it goes to simple_list.c. That will help in\n> other\n> usages as well.\n>\n> 2.\n> Please revert these unnecessary changes:\n>\n> @@ -1475,6 +1575,7 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res,\n> int rownum)\n> */\n> snprintf(filename, sizeof(filename), \"%s/%s\", current_path,\n> copybuf);\n> +\n> if (filename[strlen(filename) - 1] == '/')\n> {\n> /*\n>\n> @@ -1528,8 +1622,8 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res,\n> int rownum)\n> * can map them too.)\n> */\n> filename[strlen(filename) - 1] = '\\0'; /* Remove\n> trailing slash */\n> -\n> mapped_tblspc_path =\n> get_tablespace_mapping(&copybuf[157]);\n> +\n> if (symlink(mapped_tblspc_path, filename) != 0)\n> {\n> pg_log_error(\"could not create symbolic link from\n> \\\"%s\\\" to \\\"%s\\\": %m\",\n>\n> 3.\n> Typos:\n> retrive => retrieve\n> takecare => take care\n> tablespae => tablespace\n>\n> 4.\n> ParallelBackupEnd() function does not do anything for parallelism. Will it\n> be\n> better to just rename it as EndBackup()?\n>\n> 5.\n> To pass a tablespace path to the server in SEND_FILES_CONTENT, you are\n> reusing\n> a LABEL option, that seems odd. How about adding a new option for that?\n>\n> 6.\n> It will be good if we have some comments explaining what the function is\n> actually doing in its prologue. For functions like:\n> GetBackupFilesList()\n> ReceiveFiles()\n> create_workers_and_fetch()\n>\n>\n> Thanks\n>\n>\n>>\n>> Thanks,\n>>\n>> --\n>> Asif Rehman\n>> Highgo Software (Canada/China/Pakistan)\n>> URL : www.highgo.ca\n>>\n>>\n>\n> --\n> Jeevan Chalke\n> Associate Database Architect & Team Lead, Product Development\n> EnterpriseDB Corporation\n> The Enterprise PostgreSQL Company\n>\n>\nI had a detailed discussion with Robert Haas at PostgreConf Europe about\nparallel backup.\nWe discussed the current state of the patch and what needs to be done to\nget the patch committed.\n\n- The current patch uses a process to implement parallelism. There are many\nreasons we need to use threads instead of processes. To start with, as this\nis a client utility it makes\nmore sense to use threads. The data needs to be shared amongst different\nthreads and the main process,\nhandling that is simpler as compared to interprocess communication.\n\n- Fetching a single file or multiple files was also discussed. We concluded\nin our discussion that we\nneed to benchmark to see if disk I/O is a bottleneck or not and if parallel\nwriting gives us\nany benefit. This benchmark needs to be done on different hardware and\ndifferent\nnetwork to identify which are the real bottlenecks. In general, we agreed\nthat we could start with fetching\none file at a time but that will be revisited after the benchmarks are done.\n\n- There is also an ongoing debate in this thread that we should have one\nsingle tar file for all files or one\nTAR file per thread. I really want to have a single tar file because the\nmain purpose of the TAR file is to\nreduce the management of multiple files, but in case of one file per\nthread, we end up with many tar\nfiles. Therefore we need to have one master thread which is responsible for\nwriting on tar file and all\nthe other threads will receive the data from the network and stream to the\nmaster thread. This also\nsupports the idea of using a thread-based model rather than a process-based\napproach because it\nrequires too much data sharing between processes. If we cannot achieve\nthis, then we can disable the\nTAR option for parallel backup in the first version.\n\n- In the case of data sharing, we need to try to avoid unnecessary locking\nand more suitable algorithm to\nsolve the reader-writer problem is required.\n\n-- \nIbrar Ahmed\n\nOn Fri, Oct 18, 2019 at 4:12 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:On Thu, Oct 17, 2019 at 10:51 AM Asif Rehman <asifr.rehman@gmail.com> wrote:Attached are the updated patches.I had a quick look over these changes and they look good overall.However, here are my few review comments I caught while glancing the patches0002 and 0003.--- 0002 patch1.Can lsn option be renamed to start-wal-location? This will be more clear too.2.+typedef struct+{+    char        name[MAXPGPATH];+    char        type;+    int32        size;+    time_t        mtime;+} BackupFile;I think it will be good if we keep this structure in a common place so thatthe client can also use it.3.+    SEND_FILE_LIST,+    SEND_FILES_CONTENT,Can above two commands renamed to SEND_BACKUP_MANIFEST and SEND_BACKUP_FILErespectively?The reason behind the first name change is, we are not getting only file listshere instead we are getting a few more details with that too. And for others,it will be inline with START_BACKUP/STOP_BACKUP/SEND_BACKUP_MANIFEST.4.Typos:non-exlusive => non-exclusiveretured => returnedoptionaly => optionallynessery => necessarytotoal => total--- 0003 patch1.+static int+simple_list_length(SimpleStringList *list)+{+    int            len = 0;+    SimpleStringListCell *cell;++    for (cell = list->head; cell; cell = cell->next, len++)+        ;++    return len;+}I think it will be good if it goes to simple_list.c. That will help in otherusages as well.2.Please revert these unnecessary changes:@@ -1475,6 +1575,7 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)              */             snprintf(filename, sizeof(filename), \"%s/%s\", current_path,                      copybuf);+             if (filename[strlen(filename) - 1] == '/')             {                 /*@@ -1528,8 +1622,8 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)                      * can map them too.)                      */                     filename[strlen(filename) - 1] = '\\0';    /* Remove trailing slash */-                     mapped_tblspc_path = get_tablespace_mapping(&copybuf[157]);+                     if (symlink(mapped_tblspc_path, filename) != 0)                     {                         pg_log_error(\"could not create symbolic link from \\\"%s\\\" to \\\"%s\\\": %m\",3.Typos:retrive => retrievetakecare => take caretablespae => tablespace4.ParallelBackupEnd() function does not do anything for parallelism. Will it bebetter to just rename it as EndBackup()?5.To pass a tablespace path to the server in SEND_FILES_CONTENT, you are reusinga LABEL option, that seems odd. How about adding a new option for that?6.It will be good if we have some comments explaining what the function isactually doing in its prologue. For functions like:GetBackupFilesList()ReceiveFiles()create_workers_and_fetch()Thanks Thanks,--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- Jeevan ChalkeAssociate Database Architect & Team Lead, Product DevelopmentEnterpriseDB CorporationThe Enterprise PostgreSQL Company\nI had a detailed discussion with Robert Haas at PostgreConf Europe about parallel backup.We discussed the current state of the patch and what needs to be done to get the patch committed.- The current patch uses a process to implement parallelism. There are manyreasons we need to use threads instead of processes. To start with, as this is a client utility it makesmore sense to use threads. The data needs to be shared amongst different threads and the main process,handling that is simpler as compared to interprocess communication.- Fetching a single file or multiple files was also discussed. We concluded in our discussion that weneed to benchmark to see if disk I/O is a bottleneck or not and if parallel writing gives usany benefit. This benchmark needs to be done on different hardware and differentnetwork to identify which are the real bottlenecks. In general, we agreed that we could start with fetchingone file at a time but that will be revisited after the benchmarks are done.- There is also an ongoing debate in this thread that we should have one single tar file for all files or oneTAR file per thread. I really want to have a single tar file because the main purpose of the TAR file is toreduce the management of multiple files, but in case of one file per thread, we end up with many tarfiles. Therefore we need to have one master thread which is responsible for writing on tar file and allthe other threads will receive the data from the network and stream to the master thread. This alsosupports the idea of using a thread-based model rather than a process-based approach because itrequires too much data sharing between processes. If we cannot achieve this, then we can disable theTAR option for parallel backup in the first version.- In the case of data sharing, we need to try to avoid unnecessary locking and more suitable algorithm tosolve the reader-writer problem is required.-- Ibrar Ahmed", "msg_date": "Thu, 24 Oct 2019 15:19:08 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Oct 24, 2019 at 3:21 PM Ibrar Ahmed <ibrar.ahmad@gmail.com> wrote:\n\n>\n>\n> On Fri, Oct 18, 2019 at 4:12 PM Jeevan Chalke <\n> jeevan.chalke@enterprisedb.com> wrote:\n>\n>>\n>>\n>> On Thu, Oct 17, 2019 at 10:51 AM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>>\n>>>\n>>> Attached are the updated patches.\n>>>\n>>\n>> I had a quick look over these changes and they look good overall.\n>> However, here are my few review comments I caught while glancing the\n>> patches\n>> 0002 and 0003.\n>>\n>>\n>> --- 0002 patch\n>>\n>> 1.\n>> Can lsn option be renamed to start-wal-location? This will be more clear\n>> too.\n>>\n>> 2.\n>> +typedef struct\n>> +{\n>> + char name[MAXPGPATH];\n>> + char type;\n>> + int32 size;\n>> + time_t mtime;\n>> +} BackupFile;\n>>\n>> I think it will be good if we keep this structure in a common place so\n>> that\n>> the client can also use it.\n>>\n>> 3.\n>> + SEND_FILE_LIST,\n>> + SEND_FILES_CONTENT,\n>> Can above two commands renamed to SEND_BACKUP_MANIFEST and\n>> SEND_BACKUP_FILE\n>> respectively?\n>> The reason behind the first name change is, we are not getting only file\n>> lists\n>> here instead we are getting a few more details with that too. And for\n>> others,\n>> it will be inline with START_BACKUP/STOP_BACKUP/SEND_BACKUP_MANIFEST.\n>>\n>> 4.\n>> Typos:\n>> non-exlusive => non-exclusive\n>> retured => returned\n>> optionaly => optionally\n>> nessery => necessary\n>> totoal => total\n>>\n>>\n>> --- 0003 patch\n>>\n>> 1.\n>> +static int\n>> +simple_list_length(SimpleStringList *list)\n>> +{\n>> + int len = 0;\n>> + SimpleStringListCell *cell;\n>> +\n>> + for (cell = list->head; cell; cell = cell->next, len++)\n>> + ;\n>> +\n>> + return len;\n>> +}\n>>\n>> I think it will be good if it goes to simple_list.c. That will help in\n>> other\n>> usages as well.\n>>\n>> 2.\n>> Please revert these unnecessary changes:\n>>\n>> @@ -1475,6 +1575,7 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult\n>> *res, int rownum)\n>> */\n>> snprintf(filename, sizeof(filename), \"%s/%s\", current_path,\n>> copybuf);\n>> +\n>> if (filename[strlen(filename) - 1] == '/')\n>> {\n>> /*\n>>\n>> @@ -1528,8 +1622,8 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult\n>> *res, int rownum)\n>> * can map them too.)\n>> */\n>> filename[strlen(filename) - 1] = '\\0'; /* Remove\n>> trailing slash */\n>> -\n>> mapped_tblspc_path =\n>> get_tablespace_mapping(&copybuf[157]);\n>> +\n>> if (symlink(mapped_tblspc_path, filename) != 0)\n>> {\n>> pg_log_error(\"could not create symbolic link\n>> from \\\"%s\\\" to \\\"%s\\\": %m\",\n>>\n>> 3.\n>> Typos:\n>> retrive => retrieve\n>> takecare => take care\n>> tablespae => tablespace\n>>\n>> 4.\n>> ParallelBackupEnd() function does not do anything for parallelism. Will\n>> it be\n>> better to just rename it as EndBackup()?\n>>\n>> 5.\n>> To pass a tablespace path to the server in SEND_FILES_CONTENT, you are\n>> reusing\n>> a LABEL option, that seems odd. How about adding a new option for that?\n>>\n>> 6.\n>> It will be good if we have some comments explaining what the function is\n>> actually doing in its prologue. For functions like:\n>> GetBackupFilesList()\n>> ReceiveFiles()\n>> create_workers_and_fetch()\n>>\n>>\n>> Thanks\n>>\n>>\n>>>\n>>> Thanks,\n>>>\n>>> --\n>>> Asif Rehman\n>>> Highgo Software (Canada/China/Pakistan)\n>>> URL : www.highgo.ca\n>>>\n>>>\n>>\n>> --\n>> Jeevan Chalke\n>> Associate Database Architect & Team Lead, Product Development\n>> EnterpriseDB Corporation\n>> The Enterprise PostgreSQL Company\n>>\n>>\n> I had a detailed discussion with Robert Haas at PostgreConf Europe about\n> parallel backup.\n> We discussed the current state of the patch and what needs to be done to\n> get the patch committed.\n>\n> - The current patch uses a process to implement parallelism. There are many\n> reasons we need to use threads instead of processes. To start with, as\n> this is a client utility it makes\n> more sense to use threads. The data needs to be shared amongst different\n> threads and the main process,\n> handling that is simpler as compared to interprocess communication.\n>\n\nYes I agree. I have already converted the code to use threads instead of\nprocesses. This avoids the overhead\nof interprocess communication.\n\nWith a single file fetching strategy, this requires communication between\ncompeting threads/processes. To handle\nthat in a multiprocess application, it requires IPC. The current approach\nof multiple threads instead of processes\navoids this overhead.\n\n\n> - Fetching a single file or multiple files was also discussed. We\n> concluded in our discussion that we\n> need to benchmark to see if disk I/O is a bottleneck or not and if\n> parallel writing gives us\n> any benefit. This benchmark needs to be done on different hardware and\n> different\n> network to identify which are the real bottlenecks. In general, we agreed\n> that we could start with fetching\n> one file at a time but that will be revisited after the benchmarks are\n> done.\n>\n\nI'll share the updated patch in the next couple of days. After that, I'll\nwork on benchmarking that in\ndifferent environments that I have.\n\n\n>\n> - There is also an ongoing debate in this thread that we should have one\n> single tar file for all files or one\n> TAR file per thread. I really want to have a single tar file because the\n> main purpose of the TAR file is to\n> reduce the management of multiple files, but in case of one file per\n> thread, we end up with many tar\n> files. Therefore we need to have one master thread which is responsible\n> for writing on tar file and all\n> the other threads will receive the data from the network and stream to the\n> master thread. This also\n> supports the idea of using a thread-based model rather than a\n> process-based approach because it\n> requires too much data sharing between processes. If we cannot achieve\n> this, then we can disable the\n> TAR option for parallel backup in the first version.\n>\n\nI am in favour of disabling the tar format for the first version of\nparallel backup.\n\n\n> - In the case of data sharing, we need to try to avoid unnecessary locking\n> and more suitable algorithm to\n> solve the reader-writer problem is required.\n>\n> --\n> Ibrar Ahmed\n>\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nOn Thu, Oct 24, 2019 at 3:21 PM Ibrar Ahmed <ibrar.ahmad@gmail.com> wrote:On Fri, Oct 18, 2019 at 4:12 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:On Thu, Oct 17, 2019 at 10:51 AM Asif Rehman <asifr.rehman@gmail.com> wrote:Attached are the updated patches.I had a quick look over these changes and they look good overall.However, here are my few review comments I caught while glancing the patches0002 and 0003.--- 0002 patch1.Can lsn option be renamed to start-wal-location? This will be more clear too.2.+typedef struct+{+    char        name[MAXPGPATH];+    char        type;+    int32        size;+    time_t        mtime;+} BackupFile;I think it will be good if we keep this structure in a common place so thatthe client can also use it.3.+    SEND_FILE_LIST,+    SEND_FILES_CONTENT,Can above two commands renamed to SEND_BACKUP_MANIFEST and SEND_BACKUP_FILErespectively?The reason behind the first name change is, we are not getting only file listshere instead we are getting a few more details with that too. And for others,it will be inline with START_BACKUP/STOP_BACKUP/SEND_BACKUP_MANIFEST.4.Typos:non-exlusive => non-exclusiveretured => returnedoptionaly => optionallynessery => necessarytotoal => total--- 0003 patch1.+static int+simple_list_length(SimpleStringList *list)+{+    int            len = 0;+    SimpleStringListCell *cell;++    for (cell = list->head; cell; cell = cell->next, len++)+        ;++    return len;+}I think it will be good if it goes to simple_list.c. That will help in otherusages as well.2.Please revert these unnecessary changes:@@ -1475,6 +1575,7 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)              */             snprintf(filename, sizeof(filename), \"%s/%s\", current_path,                      copybuf);+             if (filename[strlen(filename) - 1] == '/')             {                 /*@@ -1528,8 +1622,8 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)                      * can map them too.)                      */                     filename[strlen(filename) - 1] = '\\0';    /* Remove trailing slash */-                     mapped_tblspc_path = get_tablespace_mapping(&copybuf[157]);+                     if (symlink(mapped_tblspc_path, filename) != 0)                     {                         pg_log_error(\"could not create symbolic link from \\\"%s\\\" to \\\"%s\\\": %m\",3.Typos:retrive => retrievetakecare => take caretablespae => tablespace4.ParallelBackupEnd() function does not do anything for parallelism. Will it bebetter to just rename it as EndBackup()?5.To pass a tablespace path to the server in SEND_FILES_CONTENT, you are reusinga LABEL option, that seems odd. How about adding a new option for that?6.It will be good if we have some comments explaining what the function isactually doing in its prologue. For functions like:GetBackupFilesList()ReceiveFiles()create_workers_and_fetch()Thanks Thanks,--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- Jeevan ChalkeAssociate Database Architect & Team Lead, Product DevelopmentEnterpriseDB CorporationThe Enterprise PostgreSQL Company\nI had a detailed discussion with Robert Haas at PostgreConf Europe about parallel backup.We discussed the current state of the patch and what needs to be done to get the patch committed.- The current patch uses a process to implement parallelism. There are manyreasons we need to use threads instead of processes. To start with, as this is a client utility it makesmore sense to use threads. The data needs to be shared amongst different threads and the main process,handling that is simpler as compared to interprocess communication.Yes I agree. I have already converted the code to use threads instead of processes. This avoids the overhead of interprocess communication. With a single file fetching strategy, this requires communication between competing threads/processes. To handlethat in a multiprocess application, it requires IPC. The current approach of multiple threads instead of processes avoids this overhead.- Fetching a single file or multiple files was also discussed. We concluded in our discussion that weneed to benchmark to see if disk I/O is a bottleneck or not and if parallel writing gives usany benefit. This benchmark needs to be done on different hardware and differentnetwork to identify which are the real bottlenecks. In general, we agreed that we could start with fetchingone file at a time but that will be revisited after the benchmarks are done.I'll share the updated patch in the next couple of days. After that, I'll work on benchmarking that indifferent environments that I have. - There is also an ongoing debate in this thread that we should have one single tar file for all files or oneTAR file per thread. I really want to have a single tar file because the main purpose of the TAR file is toreduce the management of multiple files, but in case of one file per thread, we end up with many tarfiles. Therefore we need to have one master thread which is responsible for writing on tar file and allthe other threads will receive the data from the network and stream to the master thread. This alsosupports the idea of using a thread-based model rather than a process-based approach because itrequires too much data sharing between processes. If we cannot achieve this, then we can disable theTAR option for parallel backup in the first version.I am in favour of disabling the tar format for the first version of parallel backup.- In the case of data sharing, we need to try to avoid unnecessary locking and more suitable algorithm tosolve the reader-writer problem is required.-- Ibrar Ahmed\n--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Thu, 24 Oct 2019 16:24:41 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Oct 24, 2019 at 4:24 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Thu, Oct 24, 2019 at 3:21 PM Ibrar Ahmed <ibrar.ahmad@gmail.com> wrote:\n>\n>>\n>>\n>> On Fri, Oct 18, 2019 at 4:12 PM Jeevan Chalke <\n>> jeevan.chalke@enterprisedb.com> wrote:\n>>\n>>>\n>>>\n>>> On Thu, Oct 17, 2019 at 10:51 AM Asif Rehman <asifr.rehman@gmail.com>\n>>> wrote:\n>>>\n>>>>\n>>>> Attached are the updated patches.\n>>>>\n>>>\n>>> I had a quick look over these changes and they look good overall.\n>>> However, here are my few review comments I caught while glancing the\n>>> patches\n>>> 0002 and 0003.\n>>>\n>>>\n>>> --- 0002 patch\n>>>\n>>> 1.\n>>> Can lsn option be renamed to start-wal-location? This will be more clear\n>>> too.\n>>>\n>>> 2.\n>>> +typedef struct\n>>> +{\n>>> + char name[MAXPGPATH];\n>>> + char type;\n>>> + int32 size;\n>>> + time_t mtime;\n>>> +} BackupFile;\n>>>\n>>> I think it will be good if we keep this structure in a common place so\n>>> that\n>>> the client can also use it.\n>>>\n>>> 3.\n>>> + SEND_FILE_LIST,\n>>> + SEND_FILES_CONTENT,\n>>> Can above two commands renamed to SEND_BACKUP_MANIFEST and\n>>> SEND_BACKUP_FILE\n>>> respectively?\n>>> The reason behind the first name change is, we are not getting only file\n>>> lists\n>>> here instead we are getting a few more details with that too. And for\n>>> others,\n>>> it will be inline with START_BACKUP/STOP_BACKUP/SEND_BACKUP_MANIFEST.\n>>>\n>>> 4.\n>>> Typos:\n>>> non-exlusive => non-exclusive\n>>> retured => returned\n>>> optionaly => optionally\n>>> nessery => necessary\n>>> totoal => total\n>>>\n>>>\n>>> --- 0003 patch\n>>>\n>>> 1.\n>>> +static int\n>>> +simple_list_length(SimpleStringList *list)\n>>> +{\n>>> + int len = 0;\n>>> + SimpleStringListCell *cell;\n>>> +\n>>> + for (cell = list->head; cell; cell = cell->next, len++)\n>>> + ;\n>>> +\n>>> + return len;\n>>> +}\n>>>\n>>> I think it will be good if it goes to simple_list.c. That will help in\n>>> other\n>>> usages as well.\n>>>\n>>> 2.\n>>> Please revert these unnecessary changes:\n>>>\n>>> @@ -1475,6 +1575,7 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult\n>>> *res, int rownum)\n>>> */\n>>> snprintf(filename, sizeof(filename), \"%s/%s\", current_path,\n>>> copybuf);\n>>> +\n>>> if (filename[strlen(filename) - 1] == '/')\n>>> {\n>>> /*\n>>>\n>>> @@ -1528,8 +1622,8 @@ ReceiveAndUnpackTarFile(PGconn *conn, PGresult\n>>> *res, int rownum)\n>>> * can map them too.)\n>>> */\n>>> filename[strlen(filename) - 1] = '\\0'; /* Remove\n>>> trailing slash */\n>>> -\n>>> mapped_tblspc_path =\n>>> get_tablespace_mapping(&copybuf[157]);\n>>> +\n>>> if (symlink(mapped_tblspc_path, filename) != 0)\n>>> {\n>>> pg_log_error(\"could not create symbolic link\n>>> from \\\"%s\\\" to \\\"%s\\\": %m\",\n>>>\n>>> 3.\n>>> Typos:\n>>> retrive => retrieve\n>>> takecare => take care\n>>> tablespae => tablespace\n>>>\n>>> 4.\n>>> ParallelBackupEnd() function does not do anything for parallelism. Will\n>>> it be\n>>> better to just rename it as EndBackup()?\n>>>\n>>> 5.\n>>> To pass a tablespace path to the server in SEND_FILES_CONTENT, you are\n>>> reusing\n>>> a LABEL option, that seems odd. How about adding a new option for that?\n>>>\n>>> 6.\n>>> It will be good if we have some comments explaining what the function is\n>>> actually doing in its prologue. For functions like:\n>>> GetBackupFilesList()\n>>> ReceiveFiles()\n>>> create_workers_and_fetch()\n>>>\n>>>\n>>> Thanks\n>>>\n>>>\n>>>>\n>>>> Thanks,\n>>>>\n>>>> --\n>>>> Asif Rehman\n>>>> Highgo Software (Canada/China/Pakistan)\n>>>> URL : www.highgo.ca\n>>>>\n>>>>\n>>>\n>>> --\n>>> Jeevan Chalke\n>>> Associate Database Architect & Team Lead, Product Development\n>>> EnterpriseDB Corporation\n>>> The Enterprise PostgreSQL Company\n>>>\n>>>\n>> I had a detailed discussion with Robert Haas at PostgreConf Europe about\n>> parallel backup.\n>> We discussed the current state of the patch and what needs to be done to\n>> get the patch committed.\n>>\n>> - The current patch uses a process to implement parallelism. There are\n>> many\n>> reasons we need to use threads instead of processes. To start with, as\n>> this is a client utility it makes\n>> more sense to use threads. The data needs to be shared amongst different\n>> threads and the main process,\n>> handling that is simpler as compared to interprocess communication.\n>>\n>\n> Yes I agree. I have already converted the code to use threads instead of\n> processes. This avoids the overhead\n> of interprocess communication.\n>\n> With a single file fetching strategy, this requires communication between\n> competing threads/processes. To handle\n> that in a multiprocess application, it requires IPC. The current approach\n> of multiple threads instead of processes\n> avoids this overhead.\n>\n>\n>> - Fetching a single file or multiple files was also discussed. We\n>> concluded in our discussion that we\n>> need to benchmark to see if disk I/O is a bottleneck or not and if\n>> parallel writing gives us\n>> any benefit. This benchmark needs to be done on different hardware and\n>> different\n>> network to identify which are the real bottlenecks. In general, we agreed\n>> that we could start with fetching\n>> one file at a time but that will be revisited after the benchmarks are\n>> done.\n>>\n>\n> I'll share the updated patch in the next couple of days. After that, I'll\n> work on benchmarking that in\n> different environments that I have.\n>\n>\n>>\n>> - There is also an ongoing debate in this thread that we should have one\n>> single tar file for all files or one\n>> TAR file per thread. I really want to have a single tar file because the\n>> main purpose of the TAR file is to\n>> reduce the management of multiple files, but in case of one file per\n>> thread, we end up with many tar\n>> files. Therefore we need to have one master thread which is responsible\n>> for writing on tar file and all\n>> the other threads will receive the data from the network and stream to\n>> the master thread. This also\n>> supports the idea of using a thread-based model rather than a\n>> process-based approach because it\n>> requires too much data sharing between processes. If we cannot achieve\n>> this, then we can disable the\n>> TAR option for parallel backup in the first version.\n>>\n>\n> I am in favour of disabling the tar format for the first version of\n> parallel backup.\n>\n>\n>> - In the case of data sharing, we need to try to avoid unnecessary\n>> locking and more suitable algorithm to\n>> solve the reader-writer problem is required.\n>>\n>> --\n>> Ibrar Ahmed\n>>\n>\n>\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\nI have updated the patch to include the changes suggested by Jeevan. This\npatch also implements the thread workers instead of\nprocesses and fetches a single file at a time. The tar format has been\ndisabled for first version of parallel backup.\n\nConversion from the previous process based application to the current\nthread based one required slight modification in data structure,\naddition of a few new functions and progress reporting functionality.\n\nThe core data structure remains in tact where table space based file\nlisting is maintained, however, we are now maintaining a list of all\nfiles (maintaining pointers to FileInfo structure; so no duplication of\ndata), so that we can sequentially access these without adding too\nmuch processing in critical section. The current scope of the critical\nsection for thread workers is limited to incrementing the file index\nwithin the list of files.\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Mon, 28 Oct 2019 19:03:33 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Oct 28, 2019 at 10:03 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> I have updated the patch to include the changes suggested by Jeevan. This patch also implements the thread workers instead of\n> processes and fetches a single file at a time. The tar format has been disabled for first version of parallel backup.\n\nLooking at 0001-0003:\n\nIt's not clear to me what the purpose of the start WAL location is\nsupposed to be. As far as I can see, SendBackupFiles() stores it in a\nvariable which is then used for exactly nothing, and nothing else uses\nit. It seems like that would be part of a potential incremental\nbackup feature, but I don't see what it's got to do with parallel full\nbackup.\n\nThe tablespace_path option appears entirely unused, and I don't know\nwhy that should be necessary here, either.\n\nSTORE_BACKUPFILE() seems like maybe it should be a function rather\nthan a macro, and also probably be renamed, because it doesn't store\nfiles and the argument's not necessarily a file.\n\nSendBackupManifest() does not send a backup manifest in the sense\ncontemplated by the email thread on that subject. It sends a file\nlist. That seems like the right idea - IMHO, anyway - but you need to\ndo a thorough renaming.\n\nI think it would be fine to decide that this facility won't support\nexclusive-mode backup.\n\nI don't think much of having both sendDir() and sendDir_(). The latter\nname is inconsistent with any naming convention we have, and there\nseems to be no reason not to just add an argument to sendDir() and\nchange the callers.\n\nI think we should rename - perhaps as a preparatory patch - the\nsizeonly flag to dryrun, or something like that.\n\nThe resource cleanup does not look right. You've included calls to\nPG_ENSURE_ERROR_CLEANUP(base_backup_cleanup, 0) in both StartBackup()\nand StopBackup(), but what happens if there is an error or even a\nclean shutdown of the connection in between? I think that there needs\nto be some change here to ensure that a walsender will always call\nbase_backup_cleanup() when it exits; I think that'd probably remove\nthe need for any PG_ENSURE_ERROR_CLEANUP calls at all, including ones\nwe have already. This might also be something that could be done as a\nseparate, prepatory refactoring patch.\n\n--\nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Mon, 28 Oct 2019 11:28:49 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Oct 28, 2019 at 8:29 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Mon, Oct 28, 2019 at 10:03 AM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n> > I have updated the patch to include the changes suggested by Jeevan.\n> This patch also implements the thread workers instead of\n> > processes and fetches a single file at a time. The tar format has been\n> disabled for first version of parallel backup.\n>\n> Looking at 0001-0003:\n>\n> It's not clear to me what the purpose of the start WAL location is\n> supposed to be. As far as I can see, SendBackupFiles() stores it in a\n> variable which is then used for exactly nothing, and nothing else uses\n> it. It seems like that would be part of a potential incremental\n> backup feature, but I don't see what it's got to do with parallel full\n> backup.\n>\n\n'startptr' is used by sendFile() during checksum verification. Since\nSendBackupFiles() is using sendFIle we have to set a valid WAL location.\n\n\n> The tablespace_path option appears entirely unused, and I don't know\n> why that should be necessary here, either.\n>\n\nThis is to calculate the basepathlen. We need to exclude the tablespace\nlocation (or\nbase path) from the filename before it is sent to the client with sendFile\ncall. I added\nthis option primarily to avoid performing string manipulation on filename\nto extract the\ntablespace location and then calculate the basepathlen.\n\nAlternatively we can do it by extracting the base path from the received\nfilename. What\ndo you suggest?\n\n\n>\n> STORE_BACKUPFILE() seems like maybe it should be a function rather\n> than a macro, and also probably be renamed, because it doesn't store\n> files and the argument's not necessarily a file.\n>\nSure.\n\n\n>\n> SendBackupManifest() does not send a backup manifest in the sense\n> contemplated by the email thread on that subject. It sends a file\n> list. That seems like the right idea - IMHO, anyway - but you need to\n> do a thorough renaming.\n>\n\nI'm considering the following command names:\nSTART_BACKUP\n- Starts the backup process\n\nSEND_BACKUP_FILELIST (Instead of SEND_BACKUP_MANIFEST)\n- Sends the list of all files (along with file information such as\nfilename, file type (directory/file/link),\nfile size and file mtime for each file) to be backed up.\n\nSEND_BACKUP_FILES\n- Sends one or more files to the client.\n\nSTOP_BACKUP\n- Stops the backup process.\n\nI'll update the function names accordingly after your confirmation. Of\ncourse, suggestions for\nbetter names are welcome.\n\n\n>\n> I think it would be fine to decide that this facility won't support\n> exclusive-mode backup.\n>\n\nSure. Will drop this patch.\n\n\n>\n> I don't think much of having both sendDir() and sendDir_(). The latter\n> name is inconsistent with any naming convention we have, and there\n> seems to be no reason not to just add an argument to sendDir() and\n> change the callers.\n\n\n> I think we should rename - perhaps as a preparatory patch - the\n> sizeonly flag to dryrun, or something like that.\n>\n\nSure, will take care of it.\n\n\n> The resource cleanup does not look right. You've included calls to\n> PG_ENSURE_ERROR_CLEANUP(base_backup_cleanup, 0) in both StartBackup()\n> and StopBackup(), but what happens if there is an error or even a\n> clean shutdown of the connection in between? I think that there needs\n\nto be some change here to ensure that a walsender will always call\n> base_backup_cleanup() when it exits; I think that'd probably remove\n> the need for any PG_ENSURE_ERROR_CLEANUP calls at all, including ones\n> we have already. This might also be something that could be done as a\n> separate, prepatory refactoring patch.\n>\n\nYou're right. I didn't handle this case properly. I will removed\nPG_ENSURE_ERROR_CLEANUP\ncalls and replace it with before_shmem_exit handler. This way\nwhenever backend process exits,\nbase_backup_cleanup will be called:\n- If it exists before calling the do_pg_stop_backup, base_backup_cleanup\nwill take care of cleanup.\n- otherwise in case of a clean shutdown (after calling do_pg_stop_backup)\nthen base_backup_cleanup\nwill simply return without doing anything.\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nOn Mon, Oct 28, 2019 at 8:29 PM Robert Haas <robertmhaas@gmail.com> wrote:On Mon, Oct 28, 2019 at 10:03 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> I have updated the patch to include the changes suggested by Jeevan. This patch also implements the thread workers instead of\n> processes and fetches a single file at a time. The tar format has been disabled for first version of parallel backup.\n\nLooking at 0001-0003:\n\nIt's not clear to me what the purpose of the start WAL location is\nsupposed to be. As far as I can see, SendBackupFiles() stores it in a\nvariable which is then used for exactly nothing, and nothing else uses\nit.  It seems like that would be part of a potential incremental\nbackup feature, but I don't see what it's got to do with parallel full\nbackup.'startptr' is used by sendFile() during checksum verification. SinceSendBackupFiles() is using sendFIle we have to set a valid WAL location.\n\nThe tablespace_path option appears entirely unused, and I don't know\nwhy that should be necessary here, either.This is to calculate the basepathlen. We need to exclude the tablespace location (or base path) from the filename before it is sent to the client with sendFile call. I addedthis option primarily to avoid performing string manipulation on filename to extract thetablespace location and then calculate the basepathlen.Alternatively we can do it by extracting the base path from the received filename. Whatdo you suggest? \nSTORE_BACKUPFILE() seems like maybe it should be a function rather\nthan a macro, and also probably be renamed, because it doesn't store\nfiles and the argument's not necessarily a file.Sure. \n\nSendBackupManifest() does not send a backup manifest in the sense\ncontemplated by the email thread on that subject.  It sends a file\nlist.  That seems like the right idea - IMHO, anyway - but you need to\ndo a thorough renaming.I'm considering the following command names:START_BACKUP- Starts the backup processSEND_BACKUP_FILELIST (Instead of SEND_BACKUP_MANIFEST)- Sends the list of all files (along with file information such as filename, file type (directory/file/link),file size and file mtime for each file) to be backed up.SEND_BACKUP_FILES- Sends one or more files to the client.STOP_BACKUP- Stops the backup process.I'll update the function names accordingly after your confirmation. Of course, suggestions forbetter names are welcome. \n\nI think it would be fine to decide that this facility won't support\nexclusive-mode backup.Sure. Will drop this patch. \n\nI don't think much of having both sendDir() and sendDir_(). The latter\nname is inconsistent with any naming convention we have, and there\nseems to be no reason not to just add an argument to sendDir() and\nchange the callers. \n\nI think we should rename - perhaps as a preparatory patch - the\nsizeonly flag to dryrun, or something like that.Sure, will take care of it.\n\nThe resource cleanup does not look right.  You've included calls to\nPG_ENSURE_ERROR_CLEANUP(base_backup_cleanup, 0) in both StartBackup()\nand StopBackup(), but what happens if there is an error or even a\nclean shutdown of the connection in between? I think that there needs\nto be some change here to ensure that a walsender will always call\nbase_backup_cleanup() when it exits; I think that'd probably remove\nthe need for any PG_ENSURE_ERROR_CLEANUP calls at all, including ones\nwe have already.  This might also be something that could be done as a\nseparate, prepatory refactoring patch.You're right. I didn't handle this case properly. I will removed PG_ENSURE_ERROR_CLEANUPcalls and replace it with before_shmem_exit handler. This way whenever backend process exits,base_backup_cleanup will be called:- If it exists before calling the do_pg_stop_backup, base_backup_cleanup will take care of cleanup.- otherwise in case of a clean shutdown (after calling do_pg_stop_backup) then base_backup_cleanupwill simply return without doing anything.--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Wed, 30 Oct 2019 19:16:11 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, Oct 30, 2019 at 7:16 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Mon, Oct 28, 2019 at 8:29 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n>> On Mon, Oct 28, 2019 at 10:03 AM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>> > I have updated the patch to include the changes suggested by Jeevan.\n>> This patch also implements the thread workers instead of\n>> > processes and fetches a single file at a time. The tar format has been\n>> disabled for first version of parallel backup.\n>>\n>> Looking at 0001-0003:\n>>\n>> It's not clear to me what the purpose of the start WAL location is\n>> supposed to be. As far as I can see, SendBackupFiles() stores it in a\n>> variable which is then used for exactly nothing, and nothing else uses\n>> it. It seems like that would be part of a potential incremental\n>> backup feature, but I don't see what it's got to do with parallel full\n>> backup.\n>>\n>\n> 'startptr' is used by sendFile() during checksum verification. Since\n> SendBackupFiles() is using sendFIle we have to set a valid WAL location.\n>\n>\n>> The tablespace_path option appears entirely unused, and I don't know\n>> why that should be necessary here, either.\n>>\n>\n> This is to calculate the basepathlen. We need to exclude the tablespace\n> location (or\n> base path) from the filename before it is sent to the client with sendFile\n> call. I added\n> this option primarily to avoid performing string manipulation on filename\n> to extract the\n> tablespace location and then calculate the basepathlen.\n>\n> Alternatively we can do it by extracting the base path from the received\n> filename. What\n> do you suggest?\n>\n>\n>>\n>> STORE_BACKUPFILE() seems like maybe it should be a function rather\n>> than a macro, and also probably be renamed, because it doesn't store\n>> files and the argument's not necessarily a file.\n>>\n> Sure.\n>\n>\n>>\n>> SendBackupManifest() does not send a backup manifest in the sense\n>> contemplated by the email thread on that subject. It sends a file\n>> list. That seems like the right idea - IMHO, anyway - but you need to\n>> do a thorough renaming.\n>>\n>\n> I'm considering the following command names:\n> START_BACKUP\n> - Starts the backup process\n>\n> SEND_BACKUP_FILELIST (Instead of SEND_BACKUP_MANIFEST)\n> - Sends the list of all files (along with file information such as\n> filename, file type (directory/file/link),\n> file size and file mtime for each file) to be backed up.\n>\n> SEND_BACKUP_FILES\n> - Sends one or more files to the client.\n>\n> STOP_BACKUP\n> - Stops the backup process.\n>\n> I'll update the function names accordingly after your confirmation. Of\n> course, suggestions for\n> better names are welcome.\n>\n>\n>>\n>> I think it would be fine to decide that this facility won't support\n>> exclusive-mode backup.\n>>\n>\n> Sure. Will drop this patch.\n>\n>\n>>\n>> I don't think much of having both sendDir() and sendDir_(). The latter\n>> name is inconsistent with any naming convention we have, and there\n>> seems to be no reason not to just add an argument to sendDir() and\n>> change the callers.\n>\n>\n>> I think we should rename - perhaps as a preparatory patch - the\n>> sizeonly flag to dryrun, or something like that.\n>>\n>\n> Sure, will take care of it.\n>\n>\n>> The resource cleanup does not look right. You've included calls to\n>> PG_ENSURE_ERROR_CLEANUP(base_backup_cleanup, 0) in both StartBackup()\n>> and StopBackup(), but what happens if there is an error or even a\n>> clean shutdown of the connection in between? I think that there needs\n>\n> to be some change here to ensure that a walsender will always call\n>> base_backup_cleanup() when it exits; I think that'd probably remove\n>> the need for any PG_ENSURE_ERROR_CLEANUP calls at all, including ones\n>> we have already. This might also be something that could be done as a\n>> separate, prepatory refactoring patch.\n>>\n>\n> You're right. I didn't handle this case properly. I will removed\n> PG_ENSURE_ERROR_CLEANUP\n> calls and replace it with before_shmem_exit handler. This way\n> whenever backend process exits,\n> base_backup_cleanup will be called:\n> - If it exists before calling the do_pg_stop_backup, base_backup_cleanup\n> will take care of cleanup.\n> - otherwise in case of a clean shutdown (after calling do_pg_stop_backup)\n> then base_backup_cleanup\n> will simply return without doing anything.\n>\n>\n>\nThe updated patches are attached.\n\nThanks,\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Fri, 1 Nov 2019 20:26:02 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, Oct 30, 2019 at 10:16 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> 'startptr' is used by sendFile() during checksum verification. Since\n> SendBackupFiles() is using sendFIle we have to set a valid WAL location.\n\nUgh, global variables.\n\nWhy are START_BACKUP, SEND_BACKUP_FILELIST, SEND_BACKUP_FILES, and\nSTOP_BACKUP all using the same base_backup_opt_list production as\nBASE_BACKUP? Presumably most of those options are not applicable to\nmost of those commands, and the productions should therefore be\nseparated.\n\nYou should add docs, too. I wouldn't have to guess what some of this\nstuff was for if you wrote documentation explaining what this stuff\nwas for. :-)\n\n>> The tablespace_path option appears entirely unused, and I don't know\n>> why that should be necessary here, either.\n>\n> This is to calculate the basepathlen. We need to exclude the tablespace location (or\n> base path) from the filename before it is sent to the client with sendFile call. I added\n> this option primarily to avoid performing string manipulation on filename to extract the\n> tablespace location and then calculate the basepathlen.\n>\n> Alternatively we can do it by extracting the base path from the received filename. What\n> do you suggest?\n\nI don't think the server needs any information from the client in\norder to be able to exclude the tablespace location from the pathname.\nWhatever it needs to know, it should be able to figure out, just as it\nwould in a non-parallel backup.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 1 Nov 2019 11:52:51 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Fri, Nov 1, 2019 at 8:53 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Wed, Oct 30, 2019 at 10:16 AM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n> > 'startptr' is used by sendFile() during checksum verification. Since\n> > SendBackupFiles() is using sendFIle we have to set a valid WAL location.\n>\n> Ugh, global variables.\n>\n> Why are START_BACKUP, SEND_BACKUP_FILELIST, SEND_BACKUP_FILES, and\n> STOP_BACKUP all using the same base_backup_opt_list production as\n> BASE_BACKUP? Presumably most of those options are not applicable to\n> most of those commands, and the productions should therefore be\n> separated.\n>\n\nAre you expecting something like the attached patch? Basically I have\nreorganised the grammar\nrules so each command can have the options required by it.\n\nI was feeling a bit reluctant for this change because it may add some\nunwanted grammar rules in\nthe replication grammar. Since these commands are using the same options as\nbase backup, may\nbe we could throw error inside the relevant functions on unwanted options?\n\n\n\n> You should add docs, too. I wouldn't have to guess what some of this\n> stuff was for if you wrote documentation explaining what this stuff\n> was for. :-)\n>\n\nYes I will add it in the next patch.\n\n\n>\n> >> The tablespace_path option appears entirely unused, and I don't know\n> >> why that should be necessary here, either.\n> >\n> > This is to calculate the basepathlen. We need to exclude the tablespace\n> location (or\n> > base path) from the filename before it is sent to the client with\n> sendFile call. I added\n> > this option primarily to avoid performing string manipulation on\n> filename to extract the\n> > tablespace location and then calculate the basepathlen.\n> >\n> > Alternatively we can do it by extracting the base path from the received\n> filename. What\n> > do you suggest?\n>\n> I don't think the server needs any information from the client in\n> order to be able to exclude the tablespace location from the pathname.\n> Whatever it needs to know, it should be able to figure out, just as it\n> would in a non-parallel backup.\n>\n> --\n> Robert Haas\n> EnterpriseDB: http://www.enterprisedb.com\n> The Enterprise PostgreSQL Company\n>\n\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Mon, 4 Nov 2019 18:08:55 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Nov 4, 2019 at 6:08 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Fri, Nov 1, 2019 at 8:53 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n>> On Wed, Oct 30, 2019 at 10:16 AM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>> > 'startptr' is used by sendFile() during checksum verification. Since\n>> > SendBackupFiles() is using sendFIle we have to set a valid WAL location.\n>>\n>> Ugh, global variables.\n>>\n>> Why are START_BACKUP, SEND_BACKUP_FILELIST, SEND_BACKUP_FILES, and\n>> STOP_BACKUP all using the same base_backup_opt_list production as\n>> BASE_BACKUP? Presumably most of those options are not applicable to\n>> most of those commands, and the productions should therefore be\n>> separated.\n>>\n>\n> Are you expecting something like the attached patch? Basically I have\n> reorganised the grammar\n> rules so each command can have the options required by it.\n>\n> I was feeling a bit reluctant for this change because it may add some\n> unwanted grammar rules in\n> the replication grammar. Since these commands are using the same options\n> as base backup, may\n> be we could throw error inside the relevant functions on unwanted options?\n>\n>\n>\n>> You should add docs, too. I wouldn't have to guess what some of this\n>> stuff was for if you wrote documentation explaining what this stuff\n>> was for. :-)\n>>\n>\n> Yes I will add it in the next patch.\n>\n>\n>>\n>> >> The tablespace_path option appears entirely unused, and I don't know\n>> >> why that should be necessary here, either.\n>> >\n>> > This is to calculate the basepathlen. We need to exclude the tablespace\n>> location (or\n>> > base path) from the filename before it is sent to the client with\n>> sendFile call. I added\n>> > this option primarily to avoid performing string manipulation on\n>> filename to extract the\n>> > tablespace location and then calculate the basepathlen.\n>> >\n>> > Alternatively we can do it by extracting the base path from the\n>> received filename. What\n>> > do you suggest?\n>>\n>> I don't think the server needs any information from the client in\n>> order to be able to exclude the tablespace location from the pathname.\n>> Whatever it needs to know, it should be able to figure out, just as it\n>> would in a non-parallel backup.\n>>\n>> --\n>> Robert Haas\n>> EnterpriseDB: http://www.enterprisedb.com\n>> The Enterprise PostgreSQL Company\n>>\n>\n>\nI have updated the replication grammar with some new rules to differentiate\nthe options production\nfor base backup and newly added commands.\n\nI have also created a separate patch to include the documentation changes.\nThe current syntax is as below:\n\n- START_BACKUP [ LABEL 'label' ] [ PROGRESS ] [ FAST ] [ TABLESPACE_MAP ]\n- STOP_BACKUP [ LABEL 'label' ] [ WAL ] [ NOWAIT ]\n- SEND_BACKUP_FILELIST\n- SEND_BACKUP_FILES ( 'FILE' [, ...] ) [ MAX_RATE rate ] [\nNOVERIFY_CHECKSUMS ] [ START_WAL_LOCATION ]\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Tue, 12 Nov 2019 17:07:14 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Nov 12, 2019 at 5:07 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Mon, Nov 4, 2019 at 6:08 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>\n>>\n>>\n>> On Fri, Nov 1, 2019 at 8:53 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>>\n>>> On Wed, Oct 30, 2019 at 10:16 AM Asif Rehman <asifr.rehman@gmail.com>\n>>> wrote:\n>>> > 'startptr' is used by sendFile() during checksum verification. Since\n>>> > SendBackupFiles() is using sendFIle we have to set a valid WAL\n>>> location.\n>>>\n>>> Ugh, global variables.\n>>>\n>>> Why are START_BACKUP, SEND_BACKUP_FILELIST, SEND_BACKUP_FILES, and\n>>> STOP_BACKUP all using the same base_backup_opt_list production as\n>>> BASE_BACKUP? Presumably most of those options are not applicable to\n>>> most of those commands, and the productions should therefore be\n>>> separated.\n>>>\n>>\n>> Are you expecting something like the attached patch? Basically I have\n>> reorganised the grammar\n>> rules so each command can have the options required by it.\n>>\n>> I was feeling a bit reluctant for this change because it may add some\n>> unwanted grammar rules in\n>> the replication grammar. Since these commands are using the same options\n>> as base backup, may\n>> be we could throw error inside the relevant functions on unwanted options?\n>>\n>>\n>>\n>>> You should add docs, too. I wouldn't have to guess what some of this\n>>> stuff was for if you wrote documentation explaining what this stuff\n>>> was for. :-)\n>>>\n>>\n>> Yes I will add it in the next patch.\n>>\n>>\n>>>\n>>> >> The tablespace_path option appears entirely unused, and I don't know\n>>> >> why that should be necessary here, either.\n>>> >\n>>> > This is to calculate the basepathlen. We need to exclude the\n>>> tablespace location (or\n>>> > base path) from the filename before it is sent to the client with\n>>> sendFile call. I added\n>>> > this option primarily to avoid performing string manipulation on\n>>> filename to extract the\n>>> > tablespace location and then calculate the basepathlen.\n>>> >\n>>> > Alternatively we can do it by extracting the base path from the\n>>> received filename. What\n>>> > do you suggest?\n>>>\n>>> I don't think the server needs any information from the client in\n>>> order to be able to exclude the tablespace location from the pathname.\n>>> Whatever it needs to know, it should be able to figure out, just as it\n>>> would in a non-parallel backup.\n>>>\n>>> --\n>>> Robert Haas\n>>> EnterpriseDB: http://www.enterprisedb.com\n>>> The Enterprise PostgreSQL Company\n>>>\n>>\n>>\n> I have updated the replication grammar with some new rules to\n> differentiate the options production\n> for base backup and newly added commands.\n>\n> I have also created a separate patch to include the documentation changes.\n> The current syntax is as below:\n>\n> - START_BACKUP [ LABEL 'label' ] [ PROGRESS ] [ FAST ] [ TABLESPACE_MAP ]\n> - STOP_BACKUP [ LABEL 'label' ] [ WAL ] [ NOWAIT ]\n> - SEND_BACKUP_FILELIST\n> - SEND_BACKUP_FILES ( 'FILE' [, ...] ) [ MAX_RATE rate ] [\n> NOVERIFY_CHECKSUMS ] [ START_WAL_LOCATION ]\n>\n>\nSorry, I sent the wrong patches. Please see the correct version of the\npatches (_v6).\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Wed, 13 Nov 2019 18:34:04 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, Nov 13, 2019 at 7:04 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n> Sorry, I sent the wrong patches. Please see the correct version of the\n> patches (_v6).\n>\n\nReview comments on these patches:\n\n1.\n+ XLogRecPtr wal_location;\n\nLooking at the other field names in basebackup_options structure, let's use\nwallocation instead. Or better startwallocation to be precise.\n\n2.\n+ int32 size;\n\nShould we use size_t here?\n\n3.\nI am still not sure why we need SEND_BACKUP_FILELIST as a separate command.\nCan't we return the file list with START_BACKUP itself?\n\n4.\n+ else if (\n+#ifndef WIN32\n+ S_ISLNK(statbuf.st_mode)\n+#else\n+ pgwin32_is_junction(pathbuf)\n+#endif\n+ )\n+ {\n+ /*\n+ * If symlink, write it as a directory. file symlinks only\nallowed\n+ * in pg_tblspc\n+ */\n+ statbuf.st_mode = S_IFDIR | pg_dir_create_mode;\n+ _tarWriteHeader(pathbuf + basepathlen + 1, NULL, &statbuf,\nfalse);\n+ }\n\nIn normal backup mode, we skip the special file which is not a regular file\nor\na directory or a symlink inside pg_tblspc. But in your patch, above code,\ntreats it as a directory. Should parallel backup too skip such special\nfiles?\n\n5.\nPlease keep header file inclusions in alphabetical order in basebackup.c and\npg_basebackup.c\n\n6.\n+ /*\n+ * build query in form of: SEND_BACKUP_FILES ('base/1/1245/32683',\n+ * 'base/1/1245/32683', ...) [options]\n+ */\n\nPlease update these comments as we fetch one file at a time.\n\n7.\n+backup_file:\n+ SCONST { $$ = (Node *)\nmakeString($1); }\n+ ;\n+\n\nInstead of having this rule with only one constant terminal, we can use\nSCONST directly in backup_files_list. However, I don't see any issue with\nthis approach either, just trying to reduce the rules.\n\n8.\nPlease indent code within 80 char limit at all applicable places.\n\n9.\nPlease fix following typos:\n\nidentifing => identifying\noptionaly => optionally\nstructre => structure\nprogrsss => progress\nRetrive => Retrieve\ndirecotries => directories\n\n\n=====\n\nThe other mail thread related to backup manifest [1], is creating a\nbackup_manifest file and sends that to the client which has optional\nchecksum and other details including filename, file size, mtime, etc.\nThere is a patch on the same thread which is then validating the backup too.\n\nSince this patch too gets a file list from the server and has similar\ndetails (except checksum), can somehow parallel backup use the\nbackup-manifest\ninfrastructure from that patch?\n\nWhen the parallel backup is in use, will there be a backup_manifest file\ncreated too? I am just visualizing what will be the scenario when both these\nfeatures are checked-in.\n\n[1]\nhttps://www.postgresql.org/message-id/CA+TgmoZV8dw1H2bzZ9xkKwdrk8+XYa+DC9H=F7heO2zna5T6qg@mail.gmail.com\n\n\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\nThanks\n-- \nJeevan Chalke\nAssociate Database Architect & Team Lead, Product Development\nEnterpriseDB Corporation\nThe Enterprise PostgreSQL Company\n\nOn Wed, Nov 13, 2019 at 7:04 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Sorry, I sent the wrong patches. Please see the correct version of the patches (_v6).Review comments on these patches:1.+    XLogRecPtr    wal_location;Looking at the other field names in basebackup_options structure, let's usewallocation instead. Or better startwallocation to be precise.2.+    int32        size;Should we use size_t here?3.I am still not sure why we need SEND_BACKUP_FILELIST as a separate command.Can't we return the file list with START_BACKUP itself?4.+        else if (+#ifndef WIN32+                 S_ISLNK(statbuf.st_mode)+#else+                 pgwin32_is_junction(pathbuf)+#endif+            )+        {+            /*+             * If symlink, write it as a directory. file symlinks only allowed+             * in pg_tblspc+             */+            statbuf.st_mode = S_IFDIR | pg_dir_create_mode;+            _tarWriteHeader(pathbuf + basepathlen + 1, NULL, &statbuf, false);+        }In normal backup mode, we skip the special file which is not a regular file ora directory or a symlink inside pg_tblspc. But in your patch, above code,treats it as a directory. Should parallel backup too skip such special files?5.Please keep header file inclusions in alphabetical order in basebackup.c andpg_basebackup.c6.+        /*+         * build query in form of: SEND_BACKUP_FILES ('base/1/1245/32683',+         * 'base/1/1245/32683', ...) [options]+         */Please update these comments as we fetch one file at a time.7.+backup_file:+            SCONST                            { $$ = (Node *) makeString($1); }+            ;+Instead of having this rule with only one constant terminal, we can useSCONST directly in backup_files_list. However, I don't see any issue withthis approach either, just trying to reduce the rules.8.Please indent code within 80 char limit at all applicable places.9.Please fix following typos:identifing => identifyingoptionaly => optionally structre => structure progrsss => progress Retrive => Retrieve direcotries => directories =====The other mail thread related to backup manifest [1], is creating abackup_manifest file and sends that to the client which has optionalchecksum and other details including filename, file size, mtime, etc.There is a patch on the same thread which is then validating the backup too.Since this patch too gets a file list from the server and has similardetails (except checksum), can somehow parallel backup use the backup-manifestinfrastructure from that patch?When the parallel backup is in use, will there be a backup_manifest filecreated too? I am just visualizing what will be the scenario when both thesefeatures are checked-in.[1] https://www.postgresql.org/message-id/CA+TgmoZV8dw1H2bzZ9xkKwdrk8+XYa+DC9H=F7heO2zna5T6qg@mail.gmail.com --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \nThanks-- Jeevan ChalkeAssociate Database Architect & Team Lead, Product DevelopmentEnterpriseDB CorporationThe Enterprise PostgreSQL Company", "msg_date": "Wed, 27 Nov 2019 14:08:31 +0530", "msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, Nov 27, 2019 at 3:38 AM Jeevan Chalke\n<jeevan.chalke@enterprisedb.com> wrote:\n> I am still not sure why we need SEND_BACKUP_FILELIST as a separate command.\n> Can't we return the file list with START_BACKUP itself?\n\nI had the same thought, but I think it's better to keep them separate.\nSomebody might want to use the SEND_BACKUP_FILELIST command for\nsomething other than a backup (I actually think it should be called\njust SEND_FILE_LIST). Somebody might want to start a backup without\ngetting a file list because they're going to copy the files at the FS\nlevel. Somebody might want to get a list of files to process after\nsomebody else has started the backup on another connection. Or maybe\nnobody wants to do any of those things, but it doesn't seem to cost us\nmuch of anything to split the commands, so I think we should.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Wed, 27 Nov 2019 14:57:27 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, Nov 27, 2019 at 1:38 PM Jeevan Chalke <\njeevan.chalke@enterprisedb.com> wrote:\n\n>\n>\n> On Wed, Nov 13, 2019 at 7:04 PM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n>\n>>\n>> Sorry, I sent the wrong patches. Please see the correct version of the\n>> patches (_v6).\n>>\n>\n> Review comments on these patches:\n>\n> 1.\n> + XLogRecPtr wal_location;\n>\n> Looking at the other field names in basebackup_options structure, let's use\n> wallocation instead. Or better startwallocation to be precise.\n>\n> 2.\n> + int32 size;\n>\n> Should we use size_t here?\n>\n> 3.\n> I am still not sure why we need SEND_BACKUP_FILELIST as a separate command.\n> Can't we return the file list with START_BACKUP itself?\n>\n> 4.\n> + else if (\n> +#ifndef WIN32\n> + S_ISLNK(statbuf.st_mode)\n> +#else\n> + pgwin32_is_junction(pathbuf)\n> +#endif\n> + )\n> + {\n> + /*\n> + * If symlink, write it as a directory. file symlinks only\n> allowed\n> + * in pg_tblspc\n> + */\n> + statbuf.st_mode = S_IFDIR | pg_dir_create_mode;\n> + _tarWriteHeader(pathbuf + basepathlen + 1, NULL, &statbuf,\n> false);\n> + }\n>\n> In normal backup mode, we skip the special file which is not a regular\n> file or\n> a directory or a symlink inside pg_tblspc. But in your patch, above code,\n> treats it as a directory. Should parallel backup too skip such special\n> files?\n>\n\nYeah going through the code again, I found it a little bit inconsistent. In\nfact\nSendBackupFiles function is supposed to send the files that were requested\nof\nit. However, currently is performing these tasks:\n\n1) If the requested file were to be a directory, it will return a TAR\ndirectory entry.\n2) If the requested files were to be symlink inside pg_tblspc, it will\nreturn the link path.\n3) and as you pointed out above, if the requested files were a symlink\noutside pg_tblspc\nand inside PGDATA then it will return TAR directory entry.\n\nI think that this function should not take care of any of the above.\nInstead, it should\nbe the client (i.e. pg_basebackup) managing it. The SendBackupFiles should\nonly send the\nregular files and ignore the request of any other kind, be it a directory\nor symlink.\n\nAny thoughts?\n\n\n> 5.\n> Please keep header file inclusions in alphabetical order in basebackup.c\n> and\n> pg_basebackup.c\n>\n> 6.\n> + /*\n> + * build query in form of: SEND_BACKUP_FILES ('base/1/1245/32683',\n> + * 'base/1/1245/32683', ...) [options]\n> + */\n>\n> Please update these comments as we fetch one file at a time.\n>\n> 7.\n> +backup_file:\n> + SCONST { $$ = (Node *)\n> makeString($1); }\n> + ;\n> +\n>\n> Instead of having this rule with only one constant terminal, we can use\n> SCONST directly in backup_files_list. However, I don't see any issue with\n> this approach either, just trying to reduce the rules.\n>\n> 8.\n> Please indent code within 80 char limit at all applicable places.\n>\n> 9.\n> Please fix following typos:\n>\n> identifing => identifying\n> optionaly => optionally\n> structre => structure\n> progrsss => progress\n> Retrive => Retrieve\n> direcotries => directories\n>\n>\n> =====\n>\n> The other mail thread related to backup manifest [1], is creating a\n> backup_manifest file and sends that to the client which has optional\n> checksum and other details including filename, file size, mtime, etc.\n> There is a patch on the same thread which is then validating the backup\n> too.\n>\n> Since this patch too gets a file list from the server and has similar\n> details (except checksum), can somehow parallel backup use the\n> backup-manifest\n> infrastructure from that patch?\n>\n\nThis was discussed earlier in the thread, and as Robert suggested, it would\ncomplicate the\ncode to no real benefit.\n\n\n> When the parallel backup is in use, will there be a backup_manifest file\n> created too? I am just visualizing what will be the scenario when both\n> these\n> features are checked-in.\n>\n\nYes, I think it should. Since the full backup will have a manifest file,\nthere is no\nreason for parallel backup to not support it.\n\nI'll share the updated patch in the next couple of days.\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nOn Wed, Nov 27, 2019 at 1:38 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:On Wed, Nov 13, 2019 at 7:04 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Sorry, I sent the wrong patches. Please see the correct version of the patches (_v6).Review comments on these patches:1.+    XLogRecPtr    wal_location;Looking at the other field names in basebackup_options structure, let's usewallocation instead. Or better startwallocation to be precise.2.+    int32        size;Should we use size_t here?3.I am still not sure why we need SEND_BACKUP_FILELIST as a separate command.Can't we return the file list with START_BACKUP itself?4.+        else if (+#ifndef WIN32+                 S_ISLNK(statbuf.st_mode)+#else+                 pgwin32_is_junction(pathbuf)+#endif+            )+        {+            /*+             * If symlink, write it as a directory. file symlinks only allowed+             * in pg_tblspc+             */+            statbuf.st_mode = S_IFDIR | pg_dir_create_mode;+            _tarWriteHeader(pathbuf + basepathlen + 1, NULL, &statbuf, false);+        }In normal backup mode, we skip the special file which is not a regular file ora directory or a symlink inside pg_tblspc. But in your patch, above code,treats it as a directory. Should parallel backup too skip such special files?Yeah going through the code again, I found it a little bit inconsistent. In factSendBackupFiles function is supposed to send the files that were requested ofit. However, currently is performing these tasks:1) If the requested file were to be a directory, it will return a TAR directory entry.2) If the requested files were to be symlink inside pg_tblspc, it will return the link path.3) and as you pointed out above, if the requested files were a symlink outside pg_tblspc and inside PGDATA then it will return TAR directory entry.I think that this function should not take care of any of the above. Instead, it shouldbe the client (i.e. pg_basebackup) managing it. The SendBackupFiles should only send theregular files and ignore the request of any other kind, be it a directory or symlink.Any thoughts?5.Please keep header file inclusions in alphabetical order in basebackup.c andpg_basebackup.c6.+        /*+         * build query in form of: SEND_BACKUP_FILES ('base/1/1245/32683',+         * 'base/1/1245/32683', ...) [options]+         */Please update these comments as we fetch one file at a time.7.+backup_file:+            SCONST                            { $$ = (Node *) makeString($1); }+            ;+Instead of having this rule with only one constant terminal, we can useSCONST directly in backup_files_list. However, I don't see any issue withthis approach either, just trying to reduce the rules.8.Please indent code within 80 char limit at all applicable places.9.Please fix following typos:identifing => identifyingoptionaly => optionally structre => structure progrsss => progress Retrive => Retrieve direcotries => directories =====The other mail thread related to backup manifest [1], is creating abackup_manifest file and sends that to the client which has optionalchecksum and other details including filename, file size, mtime, etc.There is a patch on the same thread which is then validating the backup too.Since this patch too gets a file list from the server and has similardetails (except checksum), can somehow parallel backup use the backup-manifestinfrastructure from that patch?This was discussed earlier in the thread, and as Robert suggested, it would complicate thecode to no real benefit.When the parallel backup is in use, will there be a backup_manifest filecreated too? I am just visualizing what will be the scenario when both thesefeatures are checked-in.Yes, I think it should. Since the full backup will have a manifest file, there is noreason for parallel backup to not support it.I'll share the updated patch in the next couple of days. --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Tue, 10 Dec 2019 19:33:48 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Nov 28, 2019 at 12:57 AM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Wed, Nov 27, 2019 at 3:38 AM Jeevan Chalke\n> <jeevan.chalke@enterprisedb.com> wrote:\n> > I am still not sure why we need SEND_BACKUP_FILELIST as a separate\n> command.\n> > Can't we return the file list with START_BACKUP itself?\n>\n> I had the same thought, but I think it's better to keep them separate.\n> Somebody might want to use the SEND_BACKUP_FILELIST command for\n> something other than a backup (I actually think it should be called\n> just SEND_FILE_LIST)\n\n\nSure. Thanks for the recommendation. To keep the function names in sync, I\nintend to do following the\nfollowing renamings:\n- SEND_BACKUP_FILES --> SEND_FILES\n- SEND_BACKUP_FILELIST --> SEND_FILE_LIST\n\n. Somebody might want to start a backup without\n> getting a file list because they're going to copy the files at the FS\n> level. Somebody might want to get a list of files to process after\n> somebody else has started the backup on another connection. Or maybe\n> nobody wants to do any of those things, but it doesn't seem to cost us\n> much of anything to split the commands, so I think we should.\n>\n\n+1\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nOn Thu, Nov 28, 2019 at 12:57 AM Robert Haas <robertmhaas@gmail.com> wrote:On Wed, Nov 27, 2019 at 3:38 AM Jeevan Chalke\n<jeevan.chalke@enterprisedb.com> wrote:\n> I am still not sure why we need SEND_BACKUP_FILELIST as a separate command.\n> Can't we return the file list with START_BACKUP itself?\n\nI had the same thought, but I think it's better to keep them separate.\nSomebody might want to use the SEND_BACKUP_FILELIST command for\nsomething other than a backup (I actually think it should be called\njust SEND_FILE_LIST)Sure. Thanks for the recommendation. To keep the function names in sync, I intend to do following the following renamings:- SEND_BACKUP_FILES --> SEND_FILES- SEND_BACKUP_FILELIST -->  SEND_FILE_LIST. Somebody might want to start a backup without\ngetting a file list because they're going to copy the files at the FS\nlevel. Somebody might want to get a list of files to process after\nsomebody else has started the backup on another connection. Or maybe\nnobody wants to do any of those things, but it doesn't seem to cost us\nmuch of anything to split the commands, so I think we should.+1 --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Tue, 10 Dec 2019 19:34:14 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Dec 10, 2019 at 7:34 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Thu, Nov 28, 2019 at 12:57 AM Robert Haas <robertmhaas@gmail.com>\n> wrote:\n>\n>> On Wed, Nov 27, 2019 at 3:38 AM Jeevan Chalke\n>> <jeevan.chalke@enterprisedb.com> wrote:\n>> > I am still not sure why we need SEND_BACKUP_FILELIST as a separate\n>> command.\n>> > Can't we return the file list with START_BACKUP itself?\n>>\n>> I had the same thought, but I think it's better to keep them separate.\n>> Somebody might want to use the SEND_BACKUP_FILELIST command for\n>> something other than a backup (I actually think it should be called\n>> just SEND_FILE_LIST)\n>\n>\n> Sure. Thanks for the recommendation. To keep the function names in sync, I\n> intend to do following the\n> following renamings:\n> - SEND_BACKUP_FILES --> SEND_FILES\n> - SEND_BACKUP_FILELIST --> SEND_FILE_LIST\n>\n> . Somebody might want to start a backup without\n>> getting a file list because they're going to copy the files at the FS\n>> level. Somebody might want to get a list of files to process after\n>> somebody else has started the backup on another connection. Or maybe\n>> nobody wants to do any of those things, but it doesn't seem to cost us\n>> much of anything to split the commands, so I think we should.\n>>\n>\n> +1\n>\n>\nI have updated the patches (v7 attached) and have taken care of all issues\npointed by Jeevan, additionally\nran the pgindent on each patch. Furthermore, Command names have been\nrenamed as suggested and I\nhave simplified the SendFiles function. Client can only request the regular\nfiles, any other kind such as\ndirectories or symlinks will be skipped, the client will be responsible for\ntaking care of such.\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Thu, 12 Dec 2019 20:19:57 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Dec 12, 2019 at 10:20 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> I have updated the patches (v7 attached) and have taken care of all issues pointed by Jeevan, additionally\n> ran the pgindent on each patch. Furthermore, Command names have been renamed as suggested and I\n> have simplified the SendFiles function. Client can only request the regular files, any other kind such as\n> directories or symlinks will be skipped, the client will be responsible for taking care of such.\n\nHi,\n\nPatch 0001 of this series conflicts with my recent commit\n303640199d0436c5e7acdf50b837a027b5726594; that commit was actually\ninspired by some previous study of 0001. That being said, I think 0001\nhas the wrong idea. There's no reason that I can see why it should be\ncorrect to remove the PG_ENSURE_ERROR_CLEANUP calls from\nperform_base_backup(). It's true that if we register a long-lived\nbefore_shmem_exit hook, then the backup will get cleaned up even\nwithout the PG_ENSURE_ERROR_CLEANUP block, but there's also the\nquestion of the warning message. I think that our goal should be to\nemit the warning message about a backup being stopped too early if the\nuser uses either pg_start_backup() or the new START_BACKUP command and\ndoes not end the backup with either pg_stop_backup() or the new\nSTOP_BACKUP command -- but not if a single command that both starts\nand ends a backup, like BASE_BACKUP, is interrupted. To accomplish\nthat goal in the wake of 303640199d0436c5e7acdf50b837a027b5726594, we\nneed to temporarily register do_pg_abort_backup() as a\nbefore_shmem_exit() handler using PG_ENSURE_ERROR_CLEANUP() during\ncommands like BASE_BACKUP() -- and for things like pg_start_backup()\nor the new START_BACKUP command, we just need to add a single call to\nregister_persistent_abort_backup_handler().\n\nSo I think you can drop 0001, and then in the patch that actually\nintroduces START_BACKUP, add the call to\nregister_persistent_abort_backup_handler() before calling\ndo_pg_start_backup(). Also in that patch, also adjust the warning text\nthat do_pg_abort_backup() emits to be more generic e.g. \"aborting\nbackup due to backend exiting while a non-exclusive backup is in\nprogress\".\n\n0003 creates three new functions, moving code from\ndo_pg_start_backup() to a new function collectTablespaces() and from\nperform_base_backup() to new functions setup_throttle() and\ninclude_wal_files(). I'm skeptical about all of these changes. One\ngeneral nitpick is that the way these function names are capitalized\nand punctuated does not seem to have been chosen very consistently;\nhow about name_like_this() throughout? A bit more substantively:\n\n- collectTablespaces() is factored out of do_pg_start_backup() so that\nit can also be used by SendFileList(), but that means that a client is\ngoing to invoke START_BACKUP, indirectly calling collectTablespaces(),\nand then immediately afterward the client is probably going to call\nSEND_FILE_LIST, which will again call collectTablespaces(). That does\nnot appear to be super-great. For one thing, it's duplicate work,\nalthough because SendFileList() is going to pass infotbssize as false,\nit's not a lot of duplicated work. Also, what happens if the two calls\nto collectTablespaces() return different answers due to concurrent\nCREATE/DROP TABLESPACE commands? Maybe it would all work out fine, but\nit seems like there is at least the possibility of bugs if different\nparts of the backup have different notions of what tablespaces exist.\n\n- setup_throttle() is factored out of perform_base_backup() so that it\ncan be called in StartBackup() and StopBackup() and SendFiles(). This\nseems extremely odd. Why does it make any sense to give the user an\noption to activate throttling when *ending* a backup? Why does it make\nsense to give the user a chance to enable throttling *both* at the\nstartup of a backup *and also* for each individual file. If we're\ngoing to support throttling here, it seems like it should be either a\nbackup-level property or a file-level property, not both.\n\n- include_wal_files() is factored out of perform_base_backup() so that\nit can be called by StopBackup(). This seems like a poor design\ndecision. The idea behind the BASE_BACKUP command is that you run that\none command, and the server sends you everything. The idea in this new\nway of doing business is that the client requests the individual files\nit wants -- except for the WAL files, which are for some reason not\nrequested individually but sent all together as part of the\nSTOP_BACKUP response. It seems like it would be more consistent if the\nclient were to decide which WAL files it needs and request them one by\none, just as we do with other files.\n\nI think there's a common theme to all of these complaints, which is\nthat you haven't done enough to move things that are the\nresponsibility of the backend in the BASE_BACKUP model to the frontend\nin this model. I started wondering, for example, whether it might not\nbe better to have the client rather than the server construct the\ntablespace_map file. After all, the client needs to get the list of\nfiles anyway (hence SEND_FILE_LIST) and if it's got that then it knows\nalmost enough to construct the tablespace map. The only additional\nthing it needs is the full pathname to which the link points. But, it\nseems that we could fairly easily extend SEND_FILE_LIST to send, for\nfiles that are symbolic links, the target of the link, using a new\ncolumn. Or alternatively, using a separate command, so that instead of\njust sending a single SEND_FILE_LIST command, the client might first\nask for a tablespace list and then might ask for a list of files\nwithin each tablespace (e.g. LIST_TABLESPACES, then LIST_FILES <oid>\nfor each tablespace, with 0 for the main tablespace, perhaps). I'm not\nsure which way is better.\n\nSimilarly, for throttling, I have a hard time understanding how what\nyou've got here is going to work reasonably. It looks like each client\nis just going to request whatever MAX_RATE the user specifies, but the\nresult of that will be that the actual transfer rate is probably a\nmultiple of the specified rate, approximately equal to the specified\nrate times the number of clients. That's probably not what the user\nwants. You could take the specified rate and divide it by the number\nof workers, but limiting each of 4 workers to a quarter of the rate\nwill probably lead to a combined rate of less than than the specified\nrate, because if one worker doesn't use all of the bandwidth to which\nit's entitled, or even exits earlier than the others, the other\nworkers don't get to go any faster as a result. Another problem is\nthat, in the current approach, throttling applies overall to the\nentire backup, but in this approach, it is applied separately to each\nSEND_FILE command. In the current approach, if one file finishes a\nlittle faster or slower than anticipated, the next file in the tarball\nwill be sent a little slower or faster to compensate. But in this\napproach, each SEND_FILES command is throttled separately, so this\nproperty is lost. Furthermore, while BASEBACKUP sends data\ncontinuously, this approach naturally involves pauses between\ncommands. If files are large, that won't matter much, but if they're\nsmall and numerous, it will tend to cause the actual transfer rate to\nbe less than the throttling rate.\n\nOne potential way to solve this problem is... move it to the client\nside. Instead of making it the server's job not to send data too fast,\nmake it the client's job not to receive data too fast. Let the server\nbackends write as fast as they want, and on the pg_basebackup side,\nhave the threads coordinate with each other so that they don't read\ndata faster than the configured rate. That's not quite the same thing,\nthough, because the server can get ahead by the size of the client's\nreceive buffers plus whatever data is on the wire. I don't know\nwhether that's a big enough problem to be worth caring about. If it\nis, then I think we need some server infrastructure to \"group\nthrottle\" a group of cooperating backends.\n\nA general comment about 0004 is that it seems like you've proceeded by\ntaking the code from perform_base_backup() and spreading it across\nseveral different functions without, necessarily, as much thought as\nis needed there. For instance, StartBackup() looks like just the\nbeginning of perform_base_backup(). But, why shouldn't it instead look\nlike pg_start_backup() -- in fact, a simplified version that only\nhandles the non-exclusive backup case? Is the extra stuff it's doing\nreally appropriate? I've already complained about the\ntablespace-related stuff here and the throttling, but there's more.\nSetting statrelpath here will probably break if somebody tries to use\nSEND_FILES without first calling START_BACKUP. Sending the\nbackup_label file here is oddly asymmetric, because that's done by\npg_stop_backup(), not pg_start_backup(). And similarly, StopBackup()\nlooks like it's just the end of perform_base_backup(), but that's not\npretty strange-looking too. Again, I've already complained about\ninclude_wal_files() being part of this, but there's also:\n\n+ /* ... and pg_control after everything else. */\n\n...which (1) is an odd thing to say when this is the first thing this\nparticular function is to send and (2) is another example of a sloppy\ndivision of labor between client and server; apparently, the client is\nsupposed to know not to request pg_control, because the server is\ngoing to send it unsolicited. There's no particular reason to have\nthis a special case. The client could just request it last. And then\nthe server code wouldn't need a special case, and you wouldn't have\nthis odd logic split between the client and the server.\n\nOverall, I think this needs a lot more work. The overall idea's not\nwrong, but there seem to be a very large number of details which, at\nleast to me, do not seem to be correct.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 19 Dec 2019 12:47:22 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Dec 19, 2019 at 10:47 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Thu, Dec 12, 2019 at 10:20 AM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n> > I have updated the patches (v7 attached) and have taken care of all\n> issues pointed by Jeevan, additionally\n> > ran the pgindent on each patch. Furthermore, Command names have been\n> renamed as suggested and I\n> > have simplified the SendFiles function. Client can only request the\n> regular files, any other kind such as\n> > directories or symlinks will be skipped, the client will be responsible\n> for taking care of such.\n>\n> Hi,\n>\n> Patch 0001 of this series conflicts with my recent commit\n> 303640199d0436c5e7acdf50b837a027b5726594; that commit was actually\n> inspired by some previous study of 0001. That being said, I think 0001\n> has the wrong idea. There's no reason that I can see why it should be\n> correct to remove the PG_ENSURE_ERROR_CLEANUP calls from\n> perform_base_backup(). It's true that if we register a long-lived\n> before_shmem_exit hook, then the backup will get cleaned up even\n> without the PG_ENSURE_ERROR_CLEANUP block, but there's also the\n> question of the warning message. I think that our goal should be to\n> emit the warning message about a backup being stopped too early if the\n> user uses either pg_start_backup() or the new START_BACKUP command and\n> does not end the backup with either pg_stop_backup() or the new\n> STOP_BACKUP command -- but not if a single command that both starts\n> and ends a backup, like BASE_BACKUP, is interrupted. To accomplish\n> that goal in the wake of 303640199d0436c5e7acdf50b837a027b5726594, we\n> need to temporarily register do_pg_abort_backup() as a\n> before_shmem_exit() handler using PG_ENSURE_ERROR_CLEANUP() during\n> commands like BASE_BACKUP() -- and for things like pg_start_backup()\n> or the new START_BACKUP command, we just need to add a single call to\n> register_persistent_abort_backup_handler().\n>\n> So I think you can drop 0001, and then in the patch that actually\n> introduces START_BACKUP, add the call to\n> register_persistent_abort_backup_handler() before calling\n> do_pg_start_backup(). Also in that patch, also adjust the warning text\n> that do_pg_abort_backup() emits to be more generic e.g. \"aborting\n> backup due to backend exiting while a non-exclusive backup is in\n> progress\".\n>\n> Sure. will do.\n\n\n> 0003 creates three new functions, moving code from\n> do_pg_start_backup() to a new function collectTablespaces() and from\n> perform_base_backup() to new functions setup_throttle() and\n> include_wal_files(). I'm skeptical about all of these changes. One\n> general nitpick is that the way these function names are capitalized\n> and punctuated does not seem to have been chosen very consistently;\n> how about name_like_this() throughout? A bit more substantively:\n>\n> - collectTablespaces() is factored out of do_pg_start_backup() so that\n> it can also be used by SendFileList(), but that means that a client is\n> going to invoke START_BACKUP, indirectly calling collectTablespaces(),\n> and then immediately afterward the client is probably going to call\n> SEND_FILE_LIST, which will again call collectTablespaces(). That does\n> not appear to be super-great. For one thing, it's duplicate work,\n> although because SendFileList() is going to pass infotbssize as false,\n> it's not a lot of duplicated work.\n\n\nI'll remove this duplication by eliminating this call from START_BACKUP and\nSEND_FILE_LIST functions. More about this is explained later in this email.\n\n\n> Also, what happens if the two calls\n> to collectTablespaces() return different answers due to concurrent\n> CREATE/DROP TABLESPACE commands? Maybe it would all work out fine, but\n> it seems like there is at least the possibility of bugs if different\n> parts of the backup have different notions of what tablespaces exist.\n>\n\nThe concurrent CREATE/DROP TABLESPACE commands, it can happen and will\nbe resolved by the WAL files collected for the backup. I don't think we\ncan do anything when objects are created or dropped in-between start and\nstop backup. BASE_BACKUPalso relies on the WAL files to handle such a\nscenario and does not error out when some relation files go away.\n\n\n>\n> - setup_throttle() is factored out of perform_base_backup() so that it\n> can be called in StartBackup() and StopBackup() and SendFiles(). This\n> seems extremely odd. Why does it make any sense to give the user an\n> option to activate throttling when *ending* a backup? Why does it make\n> sense to give the user a chance to enable throttling *both* at the\n> startup of a backup *and also* for each individual file. If we're\n> going to support throttling here, it seems like it should be either a\n> backup-level property or a file-level property, not both.\n>\n\nIt's a file-level property only. Throttle functionality relies on global\nvariables. StartBackup() and StopBackup() are calling setup_throttle\nfunction to disable the throttling.\n\nI should have been more explicit here by using -1 to setup_throttle,\nIllustrating that throttling is disabled, instead of using 'opt->maxrate'.\n(Although it defaults to -1 for these functions).\n\nI'll remove the setup_throttle() call for both functions.\n\n\n>\n> - include_wal_files() is factored out of perform_base_backup() so that\n> it can be called by StopBackup(). This seems like a poor design\n> decision. The idea behind the BASE_BACKUP command is that you run that\n> one command, and the server sends you everything. The idea in this new\n> way of doing business is that the client requests the individual files\n> it wants -- except for the WAL files, which are for some reason not\n> requested individually but sent all together as part of the\n> STOP_BACKUP response. It seems like it would be more consistent if the\n> client were to decide which WAL files it needs and request them one by\n> one, just as we do with other files.\n>\n\nAs I understand you are suggesting to add another command to fetch the\nlist of WAL files which would be called by the client after executing stop\nbackup. Once the client gets that list, it starts requesting the WAL files\none\nby one.\n\nSo I will add LIST_WAL_FILES command that will take start_lsn and end_lsn\nas arguments and return the list of WAL files between these LSNs.\n\nSomething like this :\nLIST_WAL_FILES 'start_lsn' 'end_lsn';\n\n\n>\n> I think there's a common theme to all of these complaints, which is\n> that you haven't done enough to move things that are the\n> responsibility of the backend in the BASE_BACKUP model to the frontend\n> in this model. I started wondering, for example, whether it might not\n> be better to have the client rather than the server construct the\n> tablespace_map file. After all, the client needs to get the list of\n> files anyway (hence SEND_FILE_LIST) and if it's got that then it knows\n> almost enough to construct the tablespace map. The only additional\n> thing it needs is the full pathname to which the link points. But, it\n> seems that we could fairly easily extend SEND_FILE_LIST to send, for\n> files that are symbolic links, the target of the link, using a new\n> column. Or alternatively, using a separate command, so that instead of\n> just sending a single SEND_FILE_LIST command, the client might first\n> ask for a tablespace list and then might ask for a list of files\n> within each tablespace (e.g. LIST_TABLESPACES, then LIST_FILES <oid>\n> for each tablespace, with 0 for the main tablespace, perhaps). I'm not\n> sure which way is better.\n>\n\ndo_pg_start_backup is collecting the tablespace information anyway to\nbuild the tablespace_map for BASE_BACKUP. So returning the same seemed\nbetter than adding a new command for the same information. hence multiple\ncalls to the collectTablespaces() [to be renamed to collect_tablespaces].\n\ntablespace_map can be constructed by the client, but then BASE_BACKUP\nis returning it as part of the full backup. If clients in parallel mode\nare to construct this themselves, these will seem like two different\napproaches. Perhaps this should be done for BASE_BACKUP as\nwell?\n\nI'll refactor the do_pg_start_backup function to remove the code related\nto tablespace information collection (to collect_tablespaces) and\ntablespace_map file creation, so that this function does not collect this\ninformation unnecessarily. perform_base_backup function can collect and\nsend the tablespace information to the client and then the client can\nconstruct the tablespace_map file.\n\nI'll add a new command to fetch the list of tablespaces i.e.\nLIST_TABLESPACES\nwhich will return the tablespace information to the client for parallel\nmode. And will refactor START_BACKUP and STOP_BACKUP commands,\nso that they only do the specific job of putting the system in backup mode\nor\nout of it, nothing else.These commands should only return the start and end\nLSN to the client.\n\n\n\n>\n> Similarly, for throttling, I have a hard time understanding how what\n> you've got here is going to work reasonably. It looks like each client\n> is just going to request whatever MAX_RATE the user specifies, but the\n> result of that will be that the actual transfer rate is probably a\n> multiple of the specified rate, approximately equal to the specified\n> rate times the number of clients. That's probably not what the user\n> wants. You could take the specified rate and divide it by the number\n> of workers, but limiting each of 4 workers to a quarter of the rate\n> will probably lead to a combined rate of less than than the specified\n> rate, because if one worker doesn't use all of the bandwidth to which\n> it's entitled, or even exits earlier than the others, the other\n> workers don't get to go any faster as a result. Another problem is\n> that, in the current approach, throttling applies overall to the\n> entire backup, but in this approach, it is applied separately to each\n> SEND_FILE command. In the current approach, if one file finishes a\n> little faster or slower than anticipated, the next file in the tarball\n> will be sent a little slower or faster to compensate. But in this\n> approach, each SEND_FILES command is throttled separately, so this\n> property is lost. Furthermore, while BASEBACKUP sends data\n> continuously, this approach naturally involves pauses between\n> commands. If files are large, that won't matter much, but if they're\n> small and numerous, it will tend to cause the actual transfer rate to\n> be less than the throttling rate.\n>\n> One potential way to solve this problem is... move it to the client\n> side. Instead of making it the server's job not to send data too fast,\n> make it the client's job not to receive data too fast. Let the server\n> backends write as fast as they want, and on the pg_basebackup side,\n> have the threads coordinate with each other so that they don't read\n> data faster than the configured rate. That's not quite the same thing,\n> though, because the server can get ahead by the size of the client's\n> receive buffers plus whatever data is on the wire. I don't know\n> whether that's a big enough problem to be worth caring about. If it\n> is, then I think we need some server infrastructure to \"group\n> throttle\" a group of cooperating backends.\n>\n\nThat was a mistake in my code. maxrate should've been equally divided\namongst all threads. I agree that we should move this to the client-side.\nWhen a thread exits, its share should also be equally divided amongst\nthe remaining threads (i.e. recalculate maxrate for each remaining thread).\n\nSay we have 4 running threads with each allocation 25% of the bandwidth.\nThread 1 exits. We recalculate bandwidth and assign the remaining 3 threads\n33.33% each. This solves one problem that you had identified. However,\nit doesn't solve where one (or more) thread is not fully consuming their\nallocated share. I'm not really sure how we can solve it properly.\nSuggestions\nare welcome.\n\n\n>\n> A general comment about 0004 is that it seems like you've proceeded by\n> taking the code from perform_base_backup() and spreading it across\n> several different functions without, necessarily, as much thought as\n> is needed there. For instance, StartBackup() looks like just the\n> beginning of perform_base_backup(). But, why shouldn't it instead look\n> like pg_start_backup() -- in fact, a simplified version that only\n> handles the non-exclusive backup case? Is the extra stuff it's doing\n> really appropriate? I've already complained about the\n> tablespace-related stuff here and the throttling, but there's more.\n> Setting statrelpath here will probably break if somebody tries to use\n> SEND_FILES without first calling START_BACKUP. Sending the\n> backup_label file here is oddly asymmetric, because that's done by\n> pg_stop_backup(), not pg_start_backup(). And similarly, StopBackup()\n> looks like it's just the end of perform_base_backup(), but that's not\n> pretty strange-looking too. Again, I've already complained about\n> include_wal_files() being part of this, but there's also:\n>\n> + /* ... and pg_control after everything else. */\n>\n> ...which (1) is an odd thing to say when this is the first thing this\n> particular function is to send and (2) is another example of a sloppy\n> division of labor between client and server; apparently, the client is\n> supposed to know not to request pg_control, because the server is\n> going to send it unsolicited. There's no particular reason to have\n> this a special case. The client could just request it last. And then\n> the server code wouldn't need a special case, and you wouldn't have\n> this odd logic split between the client and the server.\n>\n> Overall, I think this needs a lot more work. The overall idea's not\n> wrong, but there seem to be a very large number of details which, at\n> least to me, do not seem to be correct.\n>\n>\n\nThank you Robert for the detailed review. I really appreciate your insights\nand very precise feedback.\n\nAfter the changes suggested above, the design on a high level will look\nsomething\nlike this:\n\n=== SEQUENTIAL EXECUTION ===\nSTART_BACKUP [LABEL | FAST]\n- Starts backup on the server\n- Returns the start LSN to client\n\nLIST_TABLESPACES\n- Sends a list of all tables spaces to client\n\nLoops over LIST_TABLESPACES\n- LIST_FILES [tablespace]\n- Sends file list for the given tablespace\n- Create a list of all files\n\n=== PARALLEL EXECUTION ===\nThread loop until the list of files is exhausted\nSEND_FILE <file(s)> [CHECKSUM | WAL_START_LOCATION]\n- If the checksum is enabled then WAL_START_LOCATION is required.\n- Can request server to send one or more files but we are requesting one at\na time\n- Pick next file from list of files\n\n- Threads sleep after the list is exhausted\n- All threads are sleeping\n\n=== SEQUENTIAL EXECUTION ===\nSTOP_BACKUP [NOWAIT]\n- Stops backup mode\n- Return end LSN\n\nIf --wal-method=fetch then\nLIST_WAL_FILES 'start_lsn' 'end_lsn'\n- Sends a list of WAL files between start LSN and end LSN\n\n=== PARALLEL EXECUTION ===\nThread loop until the list of WAL files is exhausted\nSEND_FILE <WAL file>\n- Can request server to send one or more files but we are requesting one\nWAL file at a time\n- Pick next file from list of WAL files\n\n- Threads terminate and set their status as completed/terminated\n\n=== SEQUENTIAL EXECUTION ===\nCleanup\n\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nOn Thu, Dec 19, 2019 at 10:47 PM Robert Haas <robertmhaas@gmail.com> wrote:On Thu, Dec 12, 2019 at 10:20 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> I have updated the patches (v7 attached) and have taken care of all issues pointed by Jeevan, additionally\n> ran the pgindent on each patch. Furthermore, Command names have been renamed as suggested and I\n> have simplified the SendFiles function. Client can only request the regular files, any other kind such as\n> directories or symlinks will be skipped, the client will be responsible for taking care of such.\n\nHi,\n\nPatch 0001 of this series conflicts with my recent commit\n303640199d0436c5e7acdf50b837a027b5726594; that commit was actually\ninspired by some previous study of 0001. That being said, I think 0001\nhas the wrong idea. There's no reason that I can see why it should be\ncorrect to remove the PG_ENSURE_ERROR_CLEANUP calls from\nperform_base_backup(). It's true that if we register a long-lived\nbefore_shmem_exit hook, then the backup will get cleaned up even\nwithout the PG_ENSURE_ERROR_CLEANUP block, but there's also the\nquestion of the warning message. I think that our goal should be to\nemit the warning message about a backup being stopped too early if the\nuser uses either pg_start_backup() or the new START_BACKUP command and\ndoes not end the backup with either pg_stop_backup() or the new\nSTOP_BACKUP command -- but not if a single command that both starts\nand ends a backup, like BASE_BACKUP, is interrupted. To accomplish\nthat goal in the wake of 303640199d0436c5e7acdf50b837a027b5726594, we\nneed to temporarily register do_pg_abort_backup() as a\nbefore_shmem_exit() handler using PG_ENSURE_ERROR_CLEANUP() during\ncommands like BASE_BACKUP() -- and for things like pg_start_backup()\nor the new START_BACKUP command, we just need to add a single call to\nregister_persistent_abort_backup_handler().\n\nSo I think you can drop 0001, and then in the patch that actually\nintroduces START_BACKUP, add the call to\nregister_persistent_abort_backup_handler() before calling\ndo_pg_start_backup(). Also in that patch, also adjust the warning text\nthat do_pg_abort_backup() emits to be more generic e.g. \"aborting\nbackup due to backend exiting while a non-exclusive backup is in\nprogress\".\nSure. will do. \n0003 creates three new functions, moving code from\ndo_pg_start_backup() to a new function collectTablespaces() and from\nperform_base_backup() to new functions setup_throttle() and\ninclude_wal_files(). I'm skeptical about all of these changes. One\ngeneral nitpick is that the way these function names are capitalized\nand punctuated does not seem to have been chosen very consistently;\nhow about name_like_this() throughout? A bit more substantively:\n\n- collectTablespaces() is factored out of do_pg_start_backup() so that\nit can also be used by SendFileList(), but that means that a client is\ngoing to invoke START_BACKUP, indirectly calling collectTablespaces(),\nand then immediately afterward the client is probably going to call\nSEND_FILE_LIST, which will again call collectTablespaces(). That does\nnot appear to be super-great. For one thing, it's duplicate work,\nalthough because SendFileList() is going to pass infotbssize as false,\nit's not a lot of duplicated work.I'll remove this duplication by eliminating this call from START_BACKUP andSEND_FILE_LIST functions. More about this is explained later in this email.  Also, what happens if the two calls\nto collectTablespaces() return different answers due to concurrent\nCREATE/DROP TABLESPACE commands? Maybe it would all work out fine, but\nit seems like there is at least the possibility of bugs if different\nparts of the backup have different notions of what tablespaces exist.The concurrent CREATE/DROP TABLESPACE commands, it can happen and willbe resolved by the WAL files collected for the backup. I don't think wecan do anything when objects are created or dropped in-between start andstop backup. BASE_BACKUPalso relies on the WAL files to handle such ascenario and does not error out when some relation files go away. \n\n- setup_throttle() is factored out of perform_base_backup() so that it\ncan be called in StartBackup() and StopBackup() and SendFiles(). This\nseems extremely odd. Why does it make any sense to give the user an\noption to activate throttling when *ending* a backup? Why does it make\nsense to give the user a chance to enable throttling *both* at the\nstartup of a backup *and also* for each individual file. If we're\ngoing to support throttling here, it seems like it should be either a\nbackup-level property or a file-level property, not both.It's a file-level property only. Throttle functionality relies on globalvariables. StartBackup() and StopBackup() are calling setup_throttlefunction to disable the throttling.I should have been more explicit here by using -1 to setup_throttle,Illustrating that throttling is disabled, instead of using 'opt->maxrate'.(Although it defaults to -1 for these functions).I'll remove the setup_throttle() call for both functions. \n\n- include_wal_files() is factored out of perform_base_backup() so that\nit can be called by StopBackup(). This seems like a poor design\ndecision. The idea behind the BASE_BACKUP command is that you run that\none command, and the server sends you everything. The idea in this new\nway of doing business is that the client requests the individual files\nit wants -- except for the WAL files, which are for some reason not\nrequested individually but sent all together as part of the\nSTOP_BACKUP response. It seems like it would be more consistent if the\nclient were to decide which WAL files it needs and request them one by\none, just as we do with other files.As I understand you are suggesting to add another command to fetch thelist of WAL files which would be called by the client after executing stopbackup. Once the client gets that list, it starts requesting the WAL files oneby one.So I will add LIST_WAL_FILES command that will take start_lsn and end_lsnas arguments and return the list of WAL files between these LSNs.Something like this : LIST_WAL_FILES 'start_lsn'  'end_lsn'; \n\nI think there's a common theme to all of these complaints, which is\nthat you haven't done enough to move things that are the\nresponsibility of the backend in the BASE_BACKUP model to the frontend\nin this model. I started wondering, for example, whether it might not\nbe better to have the client rather than the server construct the\ntablespace_map file. After all, the client needs to get the list of\nfiles anyway (hence SEND_FILE_LIST) and if it's got that then it knows\nalmost enough to construct the tablespace map. The only additional\nthing it needs is the full pathname to which the link points. But, it\nseems that we could fairly easily extend SEND_FILE_LIST to send, for\nfiles that are symbolic links, the target of the link, using a new\ncolumn. Or alternatively, using a separate command, so that instead of\njust sending a single SEND_FILE_LIST command, the client might first\nask for a tablespace list and then might ask for a list of files\nwithin each tablespace (e.g. LIST_TABLESPACES, then LIST_FILES <oid>\nfor each tablespace, with 0 for the main tablespace, perhaps). I'm not\nsure which way is better.do_pg_start_backup is collecting the tablespace information anyway tobuild the tablespace_map for BASE_BACKUP. So returning the same seemedbetter than adding a new command for the same information. hence multiplecalls to the collectTablespaces() [to be renamed to collect_tablespaces].tablespace_map can be constructed by the client, but then BASE_BACKUPis returning it as part of the full backup. If clients in parallel modeare to construct this themselves, these will seem like two differentapproaches. Perhaps this should be done for BASE_BACKUP aswell?I'll refactor the do_pg_start_backup function to remove the code relatedto tablespace information collection (to collect_tablespaces) andtablespace_map file creation, so that this function does not collect thisinformation unnecessarily. perform_base_backup function can collect andsend the tablespace information to the client and then the client canconstruct the tablespace_map file.I'll add a new command to fetch the list of tablespaces i.e. LIST_TABLESPACESwhich will return the tablespace information to the client for parallelmode. And will refactor START_BACKUP and STOP_BACKUP commands,so that they only do the specific job of putting the system in backup mode orout of it, nothing else.These commands should only return the start and endLSN to the client. \n\nSimilarly, for throttling, I have a hard time understanding how what\nyou've got here is going to work reasonably. It looks like each client\nis just going to request whatever MAX_RATE the user specifies, but the\nresult of that will be that the actual transfer rate is probably a\nmultiple of the specified rate, approximately equal to the specified\nrate times the number of clients. That's probably not what the user\nwants. You could take the specified rate and divide it by the number\nof workers, but limiting each of 4 workers to a quarter of the rate\nwill probably lead to a combined rate of less than than the specified\nrate, because if one worker doesn't use all of the bandwidth to which\nit's entitled, or even exits earlier than the others, the other\nworkers don't get to go any faster as a result. Another problem is\nthat, in the current approach, throttling applies overall to the\nentire backup, but in this approach, it is applied separately to each\nSEND_FILE command. In the current approach, if one file finishes a\nlittle faster or slower than anticipated, the next file in the tarball\nwill be sent a little slower or faster to compensate. But in this\napproach, each SEND_FILES command is throttled separately, so this\nproperty is lost. Furthermore, while BASEBACKUP sends data\ncontinuously, this approach naturally involves pauses between\ncommands. If files are large, that won't matter much, but if they're\nsmall and numerous, it will tend to cause the actual transfer rate to\nbe less than the throttling rate.\n\nOne potential way to solve this problem is... move it to the client\nside. Instead of making it the server's job not to send data too fast,\nmake it the client's job not to receive data too fast. Let the server\nbackends write as fast as they want, and on the pg_basebackup side,\nhave the threads coordinate with each other so that they don't read\ndata faster than the configured rate. That's not quite the same thing,\nthough, because the server can get ahead by the size of the client's\nreceive buffers plus whatever data is on the wire. I don't know\nwhether that's a big enough problem to be worth caring about. If it\nis, then I think we need some server infrastructure to \"group\nthrottle\" a group of cooperating backends.That was a mistake in my code. maxrate should've been equally dividedamongst all threads. I agree that we should move this to the client-side.When a thread exits, its share should also be equally divided amongst the remaining threads (i.e. recalculate maxrate for each remaining thread). Say we have 4 running threads with each allocation 25% of the bandwidth.Thread 1 exits. We recalculate bandwidth and assign the remaining 3 threads33.33% each. This solves one problem that you had identified. However,it doesn't solve where one (or more) thread is not fully consuming their allocated share. I'm not really sure how we can solve it properly. Suggestionsare welcome. \n\nA general comment about 0004 is that it seems like you've proceeded by\ntaking the code from perform_base_backup() and spreading it across\nseveral different functions without, necessarily, as much thought as\nis needed there. For instance, StartBackup() looks like just the\nbeginning of perform_base_backup(). But, why shouldn't it instead look\nlike pg_start_backup() -- in fact, a simplified version that only\nhandles the non-exclusive backup case? Is the extra stuff it's doing\nreally appropriate? I've already complained about the\ntablespace-related stuff here and the throttling, but there's more.\nSetting statrelpath here will probably break if somebody tries to use\nSEND_FILES without first calling START_BACKUP. Sending the\nbackup_label file here is oddly asymmetric, because that's done by\npg_stop_backup(), not pg_start_backup(). And similarly, StopBackup()\nlooks like it's just the end of perform_base_backup(), but that's not\npretty strange-looking too. Again, I've already complained about\ninclude_wal_files() being part of this, but there's also:\n\n+       /* ... and pg_control after everything else. */\n\n...which (1) is an odd thing to say when this is the first thing this\nparticular function is to send and (2) is another example of a sloppy\ndivision of labor between client and server; apparently, the client is\nsupposed to know not to request pg_control, because the server is\ngoing to send it unsolicited. There's no particular reason to have\nthis a special case. The client could just request it last. And then\nthe server code wouldn't need a special case, and you wouldn't have\nthis odd logic split between the client and the server.\n\nOverall, I think this needs a lot more work. The overall idea's not\nwrong, but there seem to be a very large number of details which, at\nleast to me, do not seem to be correct.\n\nThank you Robert for the detailed review. I really appreciate your insightsand very precise feedback.After the changes suggested above, the design on a high level will look somethinglike this:=== SEQUENTIAL EXECUTION ===START_BACKUP [LABEL | FAST]- Starts backup on the server- Returns the start LSN to clientLIST_TABLESPACES- Sends a list of all tables spaces to clientLoops over LIST_TABLESPACES- LIST_FILES [tablespace] - Sends file list for the given tablespace- Create a list of all files=== PARALLEL EXECUTION ===Thread loop until the list of files is exhausted SEND_FILE <file(s)> [CHECKSUM | WAL_START_LOCATION] - If the checksum is enabled then WAL_START_LOCATION is required. - Can request server to send one or more files but we are requesting one at a time - Pick next file from list of files- Threads sleep after the list is exhausted- All threads are sleeping=== SEQUENTIAL EXECUTION ===STOP_BACKUP [NOWAIT]- Stops backup mode- Return end LSNIf --wal-method=fetch then LIST_WAL_FILES 'start_lsn' 'end_lsn' - Sends a list of WAL files between start LSN and end LSN === PARALLEL EXECUTION === Thread loop until the list of WAL files is exhausted SEND_FILE <WAL file> - Can request server to send one or more files but we are requesting one WAL file at a time - Pick next file from list of WAL files- Threads terminate and set their status as completed/terminated=== SEQUENTIAL EXECUTION ===Cleanup--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Sat, 4 Jan 2020 11:53:52 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Sat, Jan 4, 2020 at 11:53 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Thu, Dec 19, 2019 at 10:47 PM Robert Haas <robertmhaas@gmail.com>\n> wrote:\n>\n>> On Thu, Dec 12, 2019 at 10:20 AM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>> > I have updated the patches (v7 attached) and have taken care of all\n>> issues pointed by Jeevan, additionally\n>> > ran the pgindent on each patch. Furthermore, Command names have been\n>> renamed as suggested and I\n>> > have simplified the SendFiles function. Client can only request the\n>> regular files, any other kind such as\n>> > directories or symlinks will be skipped, the client will be responsible\n>> for taking care of such.\n>>\n>> Hi,\n>>\n>> Patch 0001 of this series conflicts with my recent commit\n>> 303640199d0436c5e7acdf50b837a027b5726594; that commit was actually\n>> inspired by some previous study of 0001. That being said, I think 0001\n>> has the wrong idea. There's no reason that I can see why it should be\n>> correct to remove the PG_ENSURE_ERROR_CLEANUP calls from\n>> perform_base_backup(). It's true that if we register a long-lived\n>> before_shmem_exit hook, then the backup will get cleaned up even\n>> without the PG_ENSURE_ERROR_CLEANUP block, but there's also the\n>> question of the warning message. I think that our goal should be to\n>> emit the warning message about a backup being stopped too early if the\n>> user uses either pg_start_backup() or the new START_BACKUP command and\n>> does not end the backup with either pg_stop_backup() or the new\n>> STOP_BACKUP command -- but not if a single command that both starts\n>> and ends a backup, like BASE_BACKUP, is interrupted. To accomplish\n>> that goal in the wake of 303640199d0436c5e7acdf50b837a027b5726594, we\n>> need to temporarily register do_pg_abort_backup() as a\n>> before_shmem_exit() handler using PG_ENSURE_ERROR_CLEANUP() during\n>> commands like BASE_BACKUP() -- and for things like pg_start_backup()\n>> or the new START_BACKUP command, we just need to add a single call to\n>> register_persistent_abort_backup_handler().\n>>\n>> So I think you can drop 0001, and then in the patch that actually\n>> introduces START_BACKUP, add the call to\n>> register_persistent_abort_backup_handler() before calling\n>> do_pg_start_backup(). Also in that patch, also adjust the warning text\n>> that do_pg_abort_backup() emits to be more generic e.g. \"aborting\n>> backup due to backend exiting while a non-exclusive backup is in\n>> progress\".\n>>\n>> Sure. will do.\n>\n>\n>> 0003 creates three new functions, moving code from\n>> do_pg_start_backup() to a new function collectTablespaces() and from\n>> perform_base_backup() to new functions setup_throttle() and\n>> include_wal_files(). I'm skeptical about all of these changes. One\n>> general nitpick is that the way these function names are capitalized\n>> and punctuated does not seem to have been chosen very consistently;\n>> how about name_like_this() throughout? A bit more substantively:\n>>\n>> - collectTablespaces() is factored out of do_pg_start_backup() so that\n>> it can also be used by SendFileList(), but that means that a client is\n>> going to invoke START_BACKUP, indirectly calling collectTablespaces(),\n>> and then immediately afterward the client is probably going to call\n>> SEND_FILE_LIST, which will again call collectTablespaces(). That does\n>> not appear to be super-great. For one thing, it's duplicate work,\n>> although because SendFileList() is going to pass infotbssize as false,\n>> it's not a lot of duplicated work.\n>\n>\n> I'll remove this duplication by eliminating this call from START_BACKUP and\n> SEND_FILE_LIST functions. More about this is explained later in this email.\n>\n>\n>> Also, what happens if the two calls\n>> to collectTablespaces() return different answers due to concurrent\n>> CREATE/DROP TABLESPACE commands? Maybe it would all work out fine, but\n>> it seems like there is at least the possibility of bugs if different\n>> parts of the backup have different notions of what tablespaces exist.\n>>\n>\n> The concurrent CREATE/DROP TABLESPACE commands, it can happen and will\n> be resolved by the WAL files collected for the backup. I don't think we\n> can do anything when objects are created or dropped in-between start and\n> stop backup. BASE_BACKUPalso relies on the WAL files to handle such a\n> scenario and does not error out when some relation files go away.\n>\n>\n>>\n>> - setup_throttle() is factored out of perform_base_backup() so that it\n>> can be called in StartBackup() and StopBackup() and SendFiles(). This\n>> seems extremely odd. Why does it make any sense to give the user an\n>> option to activate throttling when *ending* a backup? Why does it make\n>> sense to give the user a chance to enable throttling *both* at the\n>> startup of a backup *and also* for each individual file. If we're\n>> going to support throttling here, it seems like it should be either a\n>> backup-level property or a file-level property, not both.\n>>\n>\n> It's a file-level property only. Throttle functionality relies on global\n> variables. StartBackup() and StopBackup() are calling setup_throttle\n> function to disable the throttling.\n>\n> I should have been more explicit here by using -1 to setup_throttle,\n> Illustrating that throttling is disabled, instead of using 'opt->maxrate'.\n> (Although it defaults to -1 for these functions).\n>\n> I'll remove the setup_throttle() call for both functions.\n>\n>\n>>\n>> - include_wal_files() is factored out of perform_base_backup() so that\n>> it can be called by StopBackup(). This seems like a poor design\n>> decision. The idea behind the BASE_BACKUP command is that you run that\n>> one command, and the server sends you everything. The idea in this new\n>> way of doing business is that the client requests the individual files\n>> it wants -- except for the WAL files, which are for some reason not\n>> requested individually but sent all together as part of the\n>> STOP_BACKUP response. It seems like it would be more consistent if the\n>> client were to decide which WAL files it needs and request them one by\n>> one, just as we do with other files.\n>>\n>\n> As I understand you are suggesting to add another command to fetch the\n> list of WAL files which would be called by the client after executing stop\n> backup. Once the client gets that list, it starts requesting the WAL files\n> one\n> by one.\n>\n> So I will add LIST_WAL_FILES command that will take start_lsn and end_lsn\n> as arguments and return the list of WAL files between these LSNs.\n>\n> Something like this :\n> LIST_WAL_FILES 'start_lsn' 'end_lsn';\n>\n>\n>>\n>> I think there's a common theme to all of these complaints, which is\n>> that you haven't done enough to move things that are the\n>> responsibility of the backend in the BASE_BACKUP model to the frontend\n>> in this model. I started wondering, for example, whether it might not\n>> be better to have the client rather than the server construct the\n>> tablespace_map file. After all, the client needs to get the list of\n>> files anyway (hence SEND_FILE_LIST) and if it's got that then it knows\n>> almost enough to construct the tablespace map. The only additional\n>> thing it needs is the full pathname to which the link points. But, it\n>> seems that we could fairly easily extend SEND_FILE_LIST to send, for\n>> files that are symbolic links, the target of the link, using a new\n>> column. Or alternatively, using a separate command, so that instead of\n>> just sending a single SEND_FILE_LIST command, the client might first\n>> ask for a tablespace list and then might ask for a list of files\n>> within each tablespace (e.g. LIST_TABLESPACES, then LIST_FILES <oid>\n>> for each tablespace, with 0 for the main tablespace, perhaps). I'm not\n>> sure which way is better.\n>>\n>\n> do_pg_start_backup is collecting the tablespace information anyway to\n> build the tablespace_map for BASE_BACKUP. So returning the same seemed\n> better than adding a new command for the same information. hence multiple\n> calls to the collectTablespaces() [to be renamed to collect_tablespaces].\n>\n> tablespace_map can be constructed by the client, but then BASE_BACKUP\n> is returning it as part of the full backup. If clients in parallel mode\n> are to construct this themselves, these will seem like two different\n> approaches. Perhaps this should be done for BASE_BACKUP as\n> well?\n>\n> I'll refactor the do_pg_start_backup function to remove the code related\n> to tablespace information collection (to collect_tablespaces) and\n> tablespace_map file creation, so that this function does not collect this\n> information unnecessarily. perform_base_backup function can collect and\n> send the tablespace information to the client and then the client can\n> construct the tablespace_map file.\n>\n> I'll add a new command to fetch the list of tablespaces i.e.\n> LIST_TABLESPACES\n> which will return the tablespace information to the client for parallel\n> mode. And will refactor START_BACKUP and STOP_BACKUP commands,\n> so that they only do the specific job of putting the system in backup mode\n> or\n> out of it, nothing else.These commands should only return the start and end\n> LSN to the client.\n>\n>\n>\n>>\n>> Similarly, for throttling, I have a hard time understanding how what\n>> you've got here is going to work reasonably. It looks like each client\n>> is just going to request whatever MAX_RATE the user specifies, but the\n>> result of that will be that the actual transfer rate is probably a\n>> multiple of the specified rate, approximately equal to the specified\n>> rate times the number of clients. That's probably not what the user\n>> wants. You could take the specified rate and divide it by the number\n>> of workers, but limiting each of 4 workers to a quarter of the rate\n>> will probably lead to a combined rate of less than than the specified\n>> rate, because if one worker doesn't use all of the bandwidth to which\n>> it's entitled, or even exits earlier than the others, the other\n>> workers don't get to go any faster as a result. Another problem is\n>> that, in the current approach, throttling applies overall to the\n>> entire backup, but in this approach, it is applied separately to each\n>> SEND_FILE command. In the current approach, if one file finishes a\n>> little faster or slower than anticipated, the next file in the tarball\n>> will be sent a little slower or faster to compensate. But in this\n>> approach, each SEND_FILES command is throttled separately, so this\n>> property is lost. Furthermore, while BASEBACKUP sends data\n>> continuously, this approach naturally involves pauses between\n>> commands. If files are large, that won't matter much, but if they're\n>> small and numerous, it will tend to cause the actual transfer rate to\n>> be less than the throttling rate.\n>>\n>> One potential way to solve this problem is... move it to the client\n>> side. Instead of making it the server's job not to send data too fast,\n>> make it the client's job not to receive data too fast. Let the server\n>> backends write as fast as they want, and on the pg_basebackup side,\n>> have the threads coordinate with each other so that they don't read\n>> data faster than the configured rate. That's not quite the same thing,\n>> though, because the server can get ahead by the size of the client's\n>> receive buffers plus whatever data is on the wire. I don't know\n>> whether that's a big enough problem to be worth caring about. If it\n>> is, then I think we need some server infrastructure to \"group\n>> throttle\" a group of cooperating backends.\n>>\n>\n> That was a mistake in my code. maxrate should've been equally divided\n> amongst all threads. I agree that we should move this to the client-side.\n> When a thread exits, its share should also be equally divided amongst\n> the remaining threads (i.e. recalculate maxrate for each remaining\n> thread).\n>\n> Say we have 4 running threads with each allocation 25% of the bandwidth.\n> Thread 1 exits. We recalculate bandwidth and assign the remaining 3 threads\n> 33.33% each. This solves one problem that you had identified. However,\n> it doesn't solve where one (or more) thread is not fully consuming their\n> allocated share. I'm not really sure how we can solve it properly.\n> Suggestions\n> are welcome.\n>\n>\n>>\n>> A general comment about 0004 is that it seems like you've proceeded by\n>> taking the code from perform_base_backup() and spreading it across\n>> several different functions without, necessarily, as much thought as\n>> is needed there. For instance, StartBackup() looks like just the\n>> beginning of perform_base_backup(). But, why shouldn't it instead look\n>> like pg_start_backup() -- in fact, a simplified version that only\n>> handles the non-exclusive backup case? Is the extra stuff it's doing\n>> really appropriate? I've already complained about the\n>> tablespace-related stuff here and the throttling, but there's more.\n>> Setting statrelpath here will probably break if somebody tries to use\n>> SEND_FILES without first calling START_BACKUP. Sending the\n>> backup_label file here is oddly asymmetric, because that's done by\n>> pg_stop_backup(), not pg_start_backup(). And similarly, StopBackup()\n>> looks like it's just the end of perform_base_backup(), but that's not\n>> pretty strange-looking too. Again, I've already complained about\n>> include_wal_files() being part of this, but there's also:\n>>\n>> + /* ... and pg_control after everything else. */\n>>\n>> ...which (1) is an odd thing to say when this is the first thing this\n>> particular function is to send and (2) is another example of a sloppy\n>> division of labor between client and server; apparently, the client is\n>> supposed to know not to request pg_control, because the server is\n>> going to send it unsolicited. There's no particular reason to have\n>> this a special case. The client could just request it last. And then\n>> the server code wouldn't need a special case, and you wouldn't have\n>> this odd logic split between the client and the server.\n>>\n>> Overall, I think this needs a lot more work. The overall idea's not\n>> wrong, but there seem to be a very large number of details which, at\n>> least to me, do not seem to be correct.\n>>\n>>\n>\n> Thank you Robert for the detailed review. I really appreciate your insights\n> and very precise feedback.\n>\n> After the changes suggested above, the design on a high level will look\n> something\n> like this:\n>\n> === SEQUENTIAL EXECUTION ===\n> START_BACKUP [LABEL | FAST]\n> - Starts backup on the server\n> - Returns the start LSN to client\n>\n> LIST_TABLESPACES\n> - Sends a list of all tables spaces to client\n>\n> Loops over LIST_TABLESPACES\n> - LIST_FILES [tablespace]\n> - Sends file list for the given tablespace\n> - Create a list of all files\n>\n> === PARALLEL EXECUTION ===\n> Thread loop until the list of files is exhausted\n> SEND_FILE <file(s)> [CHECKSUM | WAL_START_LOCATION]\n> - If the checksum is enabled then WAL_START_LOCATION is required.\n> - Can request server to send one or more files but we are requesting one\n> at a time\n> - Pick next file from list of files\n>\n> - Threads sleep after the list is exhausted\n> - All threads are sleeping\n>\n> === SEQUENTIAL EXECUTION ===\n> STOP_BACKUP [NOWAIT]\n> - Stops backup mode\n> - Return end LSN\n>\n> If --wal-method=fetch then\n> LIST_WAL_FILES 'start_lsn' 'end_lsn'\n> - Sends a list of WAL files between start LSN and end LSN\n>\n> === PARALLEL EXECUTION ===\n> Thread loop until the list of WAL files is exhausted\n> SEND_FILE <WAL file>\n> - Can request server to send one or more files but we are requesting one\n> WAL file at a time\n> - Pick next file from list of WAL files\n>\n> - Threads terminate and set their status as completed/terminated\n>\n> === SEQUENTIAL EXECUTION ===\n> Cleanup\n>\n>\n>\n>\nHere are the the updated patches, taking care of the issues pointed\nearlier. This patch adds the following commands (with specified option):\n\nSTART_BACKUP [LABEL '<label>'] [FAST]\nSTOP_BACKUP [NOWAIT]\nLIST_TABLESPACES [PROGRESS]\nLIST_FILES [TABLESPACE]\nLIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\nSEND_FILES '(' FILE, FILE... ')' [START_WAL_LOCATION 'X/X']\n [NOVERIFY_CHECKSUMS]\n\n\nParallel backup is not making any use of tablespace map, so I have\nremoved that option from the above commands. There is a patch pending\nto remove the exclusive backup; we can further refactor the\ndo_pg_start_backup\nfunction at that time, to remove the tablespace information and move the\ncreation of tablespace_map file to the client.\n\n\nI have disabled the maxrate option for parallel backup. I intend to send\nout a separate patch for it. Robert previously suggested to implement\nthrottling on the client-side. I found the original email thread [1]\nwhere throttling was proposed and added to the server. In that thread,\nit was originally implemented on the client-side, but per many suggestions,\nit was moved to server-side.\n\nSo, I have a few suggestions on how we can implement this:\n\n1- have another option for pg_basebackup (i.e. per-worker-maxrate) where\nthe user could choose the bandwidth allocation for each worker. This\napproach\ncan be implemented on the client-side as well as on the server-side.\n\n2- have the maxrate, be divided among workers equally at first. and the\nlet the main thread keep adjusting it whenever one of the workers finishes.\nI believe this would only be possible if we handle throttling on the client.\nAlso, as I understand it, implementing this will introduce additional mutex\nfor handling of bandwidth consumption data so that rate may be adjusted\naccording to data received by threads.\n\n[1]\nhttps://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Thu, 30 Jan 2020 18:39:51 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif,\n\nOn Thu, Jan 30, 2020 at 7:10 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n> Here are the the updated patches, taking care of the issues pointed\n> earlier. This patch adds the following commands (with specified option):\n>\n> START_BACKUP [LABEL '<label>'] [FAST]\n> STOP_BACKUP [NOWAIT]\n> LIST_TABLESPACES [PROGRESS]\n> LIST_FILES [TABLESPACE]\n> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n> SEND_FILES '(' FILE, FILE... ')' [START_WAL_LOCATION 'X/X']\n> [NOVERIFY_CHECKSUMS]\n>\n>\n> Parallel backup is not making any use of tablespace map, so I have\n> removed that option from the above commands. There is a patch pending\n> to remove the exclusive backup; we can further refactor the\n> do_pg_start_backup\n> function at that time, to remove the tablespace information and move the\n> creation of tablespace_map file to the client.\n>\n>\n> I have disabled the maxrate option for parallel backup. I intend to send\n> out a separate patch for it. Robert previously suggested to implement\n> throttling on the client-side. I found the original email thread [1]\n> where throttling was proposed and added to the server. In that thread,\n> it was originally implemented on the client-side, but per many suggestions,\n> it was moved to server-side.\n>\n> So, I have a few suggestions on how we can implement this:\n>\n> 1- have another option for pg_basebackup (i.e. per-worker-maxrate) where\n> the user could choose the bandwidth allocation for each worker. This\n> approach\n> can be implemented on the client-side as well as on the server-side.\n>\n> 2- have the maxrate, be divided among workers equally at first. and the\n> let the main thread keep adjusting it whenever one of the workers finishes.\n> I believe this would only be possible if we handle throttling on the\n> client.\n> Also, as I understand it, implementing this will introduce additional mutex\n> for handling of bandwidth consumption data so that rate may be adjusted\n> according to data received by threads.\n>\n> [1]\n> https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af\n>\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\nThe latest changes look good to me. However, the patch set is missing the\ndocumentation.\nPlease add those.\n\nThanks\n\n-- \nJeevan Chalke\nAssociate Database Architect & Team Lead, Product Development\nEnterpriseDB Corporation\nThe Enterprise PostgreSQL Company\n\nHi Asif,On Thu, Jan 30, 2020 at 7:10 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Here are the the updated patches, taking care of the issues pointedearlier. This patch adds the following commands (with specified option):START_BACKUP [LABEL '<label>'] [FAST]STOP_BACKUP [NOWAIT]LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']SEND_FILES '(' FILE, FILE... ')' [START_WAL_LOCATION 'X/X']                            [NOVERIFY_CHECKSUMS]Parallel backup is not making any use of tablespace map, so I haveremoved that option from the above commands. There is a patch pendingto remove the exclusive backup; we can further refactor the do_pg_start_backupfunction at that time, to remove the tablespace information and move thecreation of tablespace_map file to the client.I have disabled the maxrate option for parallel backup. I intend to sendout a separate patch for it. Robert previously suggested to implementthrottling on the client-side. I found the original email thread [1] where throttling was proposed and added to the server. In that thread,it was originally implemented on the client-side, but per many suggestions,it was moved to server-side.So, I have a few suggestions on how we can implement this:1- have another option for pg_basebackup (i.e. per-worker-maxrate) wherethe user could choose the bandwidth allocation for each worker. This approachcan be implemented on the client-side as well as on the server-side.2- have the maxrate, be divided among workers equally at first. and the let the main thread keep adjusting it whenever one of the workers finishes.I believe this would only be possible if we handle throttling on the client.Also, as I understand it, implementing this will introduce additional mutexfor handling of bandwidth consumption data so that rate may be adjusted according to data received by threads.[1] https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \nThe latest changes look good to me. However, the patch set is missing the documentation.Please add those.Thanks-- Jeevan ChalkeAssociate Database Architect & Team Lead, Product DevelopmentEnterpriseDB CorporationThe Enterprise PostgreSQL Company", "msg_date": "Mon, 10 Feb 2020 19:18:37 +0530", "msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Thanks Jeevan. Here is the documentation patch.\n\nOn Mon, Feb 10, 2020 at 6:49 PM Jeevan Chalke <\njeevan.chalke@enterprisedb.com> wrote:\n\n> Hi Asif,\n>\n> On Thu, Jan 30, 2020 at 7:10 PM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n>\n>>\n>> Here are the the updated patches, taking care of the issues pointed\n>> earlier. This patch adds the following commands (with specified option):\n>>\n>> START_BACKUP [LABEL '<label>'] [FAST]\n>> STOP_BACKUP [NOWAIT]\n>> LIST_TABLESPACES [PROGRESS]\n>> LIST_FILES [TABLESPACE]\n>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>> SEND_FILES '(' FILE, FILE... ')' [START_WAL_LOCATION 'X/X']\n>> [NOVERIFY_CHECKSUMS]\n>>\n>>\n>> Parallel backup is not making any use of tablespace map, so I have\n>> removed that option from the above commands. There is a patch pending\n>> to remove the exclusive backup; we can further refactor the\n>> do_pg_start_backup\n>> function at that time, to remove the tablespace information and move the\n>> creation of tablespace_map file to the client.\n>>\n>>\n>> I have disabled the maxrate option for parallel backup. I intend to send\n>> out a separate patch for it. Robert previously suggested to implement\n>> throttling on the client-side. I found the original email thread [1]\n>> where throttling was proposed and added to the server. In that thread,\n>> it was originally implemented on the client-side, but per many\n>> suggestions,\n>> it was moved to server-side.\n>>\n>> So, I have a few suggestions on how we can implement this:\n>>\n>> 1- have another option for pg_basebackup (i.e. per-worker-maxrate) where\n>> the user could choose the bandwidth allocation for each worker. This\n>> approach\n>> can be implemented on the client-side as well as on the server-side.\n>>\n>> 2- have the maxrate, be divided among workers equally at first. and the\n>> let the main thread keep adjusting it whenever one of the workers\n>> finishes.\n>> I believe this would only be possible if we handle throttling on the\n>> client.\n>> Also, as I understand it, implementing this will introduce additional\n>> mutex\n>> for handling of bandwidth consumption data so that rate may be adjusted\n>> according to data received by threads.\n>>\n>> [1]\n>> https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af\n>>\n>> --\n>> Asif Rehman\n>> Highgo Software (Canada/China/Pakistan)\n>> URL : www.highgo.ca\n>>\n>>\n>\n> The latest changes look good to me. However, the patch set is missing the\n> documentation.\n> Please add those.\n>\n> Thanks\n>\n> --\n> Jeevan Chalke\n> Associate Database Architect & Team Lead, Product Development\n> EnterpriseDB Corporation\n> The Enterprise PostgreSQL Company\n>\n>\n\n-- \n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Mon, 17 Feb 2020 13:39:08 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi,\n\nI have created a commitfest entry.\nhttps://commitfest.postgresql.org/27/2472/\n\n\nOn Mon, Feb 17, 2020 at 1:39 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n> Thanks Jeevan. Here is the documentation patch.\n>\n> On Mon, Feb 10, 2020 at 6:49 PM Jeevan Chalke <\n> jeevan.chalke@enterprisedb.com> wrote:\n>\n>> Hi Asif,\n>>\n>> On Thu, Jan 30, 2020 at 7:10 PM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>>\n>>>\n>>> Here are the the updated patches, taking care of the issues pointed\n>>> earlier. This patch adds the following commands (with specified option):\n>>>\n>>> START_BACKUP [LABEL '<label>'] [FAST]\n>>> STOP_BACKUP [NOWAIT]\n>>> LIST_TABLESPACES [PROGRESS]\n>>> LIST_FILES [TABLESPACE]\n>>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>> SEND_FILES '(' FILE, FILE... ')' [START_WAL_LOCATION 'X/X']\n>>> [NOVERIFY_CHECKSUMS]\n>>>\n>>>\n>>> Parallel backup is not making any use of tablespace map, so I have\n>>> removed that option from the above commands. There is a patch pending\n>>> to remove the exclusive backup; we can further refactor the\n>>> do_pg_start_backup\n>>> function at that time, to remove the tablespace information and move the\n>>> creation of tablespace_map file to the client.\n>>>\n>>>\n>>> I have disabled the maxrate option for parallel backup. I intend to send\n>>> out a separate patch for it. Robert previously suggested to implement\n>>> throttling on the client-side. I found the original email thread [1]\n>>> where throttling was proposed and added to the server. In that thread,\n>>> it was originally implemented on the client-side, but per many\n>>> suggestions,\n>>> it was moved to server-side.\n>>>\n>>> So, I have a few suggestions on how we can implement this:\n>>>\n>>> 1- have another option for pg_basebackup (i.e. per-worker-maxrate) where\n>>> the user could choose the bandwidth allocation for each worker. This\n>>> approach\n>>> can be implemented on the client-side as well as on the server-side.\n>>>\n>>> 2- have the maxrate, be divided among workers equally at first. and the\n>>> let the main thread keep adjusting it whenever one of the workers\n>>> finishes.\n>>> I believe this would only be possible if we handle throttling on the\n>>> client.\n>>> Also, as I understand it, implementing this will introduce additional\n>>> mutex\n>>> for handling of bandwidth consumption data so that rate may be adjusted\n>>> according to data received by threads.\n>>>\n>>> [1]\n>>> https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af\n>>>\n>>> --\n>>> Asif Rehman\n>>> Highgo Software (Canada/China/Pakistan)\n>>> URL : www.highgo.ca\n>>>\n>>>\n>>\n>> The latest changes look good to me. However, the patch set is missing the\n>> documentation.\n>> Please add those.\n>>\n>> Thanks\n>>\n>> --\n>> Jeevan Chalke\n>> Associate Database Architect & Team Lead, Product Development\n>> EnterpriseDB Corporation\n>> The Enterprise PostgreSQL Company\n>>\n>>\n>\n> --\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\n-- \n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nHi,I have created a commitfest entry.https://commitfest.postgresql.org/27/2472/On Mon, Feb 17, 2020 at 1:39 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Thanks Jeevan. Here is the documentation patch.On Mon, Feb 10, 2020 at 6:49 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:Hi Asif,On Thu, Jan 30, 2020 at 7:10 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Here are the the updated patches, taking care of the issues pointedearlier. This patch adds the following commands (with specified option):START_BACKUP [LABEL '<label>'] [FAST]STOP_BACKUP [NOWAIT]LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']SEND_FILES '(' FILE, FILE... ')' [START_WAL_LOCATION 'X/X']                            [NOVERIFY_CHECKSUMS]Parallel backup is not making any use of tablespace map, so I haveremoved that option from the above commands. There is a patch pendingto remove the exclusive backup; we can further refactor the do_pg_start_backupfunction at that time, to remove the tablespace information and move thecreation of tablespace_map file to the client.I have disabled the maxrate option for parallel backup. I intend to sendout a separate patch for it. Robert previously suggested to implementthrottling on the client-side. I found the original email thread [1] where throttling was proposed and added to the server. In that thread,it was originally implemented on the client-side, but per many suggestions,it was moved to server-side.So, I have a few suggestions on how we can implement this:1- have another option for pg_basebackup (i.e. per-worker-maxrate) wherethe user could choose the bandwidth allocation for each worker. This approachcan be implemented on the client-side as well as on the server-side.2- have the maxrate, be divided among workers equally at first. and the let the main thread keep adjusting it whenever one of the workers finishes.I believe this would only be possible if we handle throttling on the client.Also, as I understand it, implementing this will introduce additional mutexfor handling of bandwidth consumption data so that rate may be adjusted according to data received by threads.[1] https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \nThe latest changes look good to me. However, the patch set is missing the documentation.Please add those.Thanks-- Jeevan ChalkeAssociate Database Architect & Team Lead, Product DevelopmentEnterpriseDB CorporationThe Enterprise PostgreSQL Company\n-- --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Tue, 25 Feb 2020 19:18:42 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif\n\nI have started testing this feature. I have applied v6 patch on commit\na069218163704c44a8996e7e98e765c56e2b9c8e (30 Jan).\nI got few observations, please take a look.\n\n*--if backup failed, backup directory is not getting removed.*\n[edb@localhost bin]$ ./pg_basebackup -p 5432 --jobs=9 -D /tmp/test_bkp/bkp6\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\n[edb@localhost bin]$ ./pg_basebackup -p 5432 --jobs=8 -D /tmp/test_bkp/bkp6\npg_basebackup: error: directory \"/tmp/test_bkp/bkp6\" exists but is not empty\n\n\n*--giving large number of jobs leading segmentation fault.*\n./pg_basebackup -p 5432 --jobs=1000 -D /tmp/t3\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\n.\n.\n.\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: error: could not connect to server: could not fork new\nprocess for connection: Resource temporarily unavailable\n\ncould not fork new process for connection: Resource temporarily unavailable\npg_basebackup: error: failed to create thread: Resource temporarily\nunavailable\nSegmentation fault (core dumped)\n\n--stack-trace\ngdb -q -c core.11824 pg_basebackup\nLoaded symbols for /lib64/libnss_files.so.2\nCore was generated by `./pg_basebackup -p 5432 --jobs=1000 -D\n/tmp/test_bkp/bkp10'.\nProgram terminated with signal 11, Segmentation fault.\n#0 pthread_join (threadid=140503120623360, thread_return=0x0) at\npthread_join.c:46\n46 if (INVALID_NOT_TERMINATED_TD_P (pd))\nMissing separate debuginfos, use: debuginfo-install\nkeyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\nlibcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\nopenssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n(gdb) bt\n#0 pthread_join (threadid=140503120623360, thread_return=0x0) at\npthread_join.c:46\n#1 0x0000000000408e21 in cleanup_workers () at pg_basebackup.c:2840\n#2 0x0000000000403846 in disconnect_atexit () at pg_basebackup.c:316\n#3 0x0000003921235a02 in __run_exit_handlers (status=1) at exit.c:78\n#4 exit (status=1) at exit.c:100\n#5 0x0000000000408aa6 in create_parallel_workers (backupinfo=0x1a4b8c0) at\npg_basebackup.c:2713\n#6 0x0000000000407946 in BaseBackup () at pg_basebackup.c:2127\n#7 0x000000000040895c in main (argc=6, argv=0x7ffd566f4718) at\npg_basebackup.c:2668\n\n\n*--with tablespace is in the same directory as data, parallel_backup\ncrashed*\n[edb@localhost bin]$ ./initdb -D /tmp/data\n[edb@localhost bin]$ ./pg_ctl -D /tmp/data -l /tmp/logfile start\n[edb@localhost bin]$ mkdir /tmp/ts\n[edb@localhost bin]$ ./psql postgres\npsql (13devel)\nType \"help\" for help.\n\npostgres=# create tablespace ts location '/tmp/ts';\nCREATE TABLESPACE\npostgres=# create table tx (a int) tablespace ts;\nCREATE TABLE\npostgres=# \\q\n[edb@localhost bin]$ ./pg_basebackup -j 2 -D /tmp/tts -T /tmp/ts=/tmp/ts1\nSegmentation fault (core dumped)\n\n--stack-trace\n[edb@localhost bin]$ gdb -q -c core.15778 pg_basebackup\nLoaded symbols for /lib64/libnss_files.so.2\nCore was generated by `./pg_basebackup -j 2 -D /tmp/tts -T\n/tmp/ts=/tmp/ts1'.\nProgram terminated with signal 11, Segmentation fault.\n#0 0x0000000000409442 in get_backup_filelist (conn=0x140cb20,\nbackupInfo=0x14210a0) at pg_basebackup.c:3000\n3000 backupInfo->curr->next = file;\nMissing separate debuginfos, use: debuginfo-install\nkeyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\nlibcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\nopenssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n(gdb) bt\n#0 0x0000000000409442 in get_backup_filelist (conn=0x140cb20,\nbackupInfo=0x14210a0) at pg_basebackup.c:3000\n#1 0x0000000000408b56 in parallel_backup_run (backupinfo=0x14210a0) at\npg_basebackup.c:2739\n#2 0x0000000000407955 in BaseBackup () at pg_basebackup.c:2128\n#3 0x000000000040895c in main (argc=7, argv=0x7ffca2910c58) at\npg_basebackup.c:2668\n(gdb)\n\nThanks & Regards,\nRajkumar Raghuwanshi\n\n\nOn Tue, Feb 25, 2020 at 7:49 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n> Hi,\n>\n> I have created a commitfest entry.\n> https://commitfest.postgresql.org/27/2472/\n>\n>\n> On Mon, Feb 17, 2020 at 1:39 PM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n>\n>> Thanks Jeevan. Here is the documentation patch.\n>>\n>> On Mon, Feb 10, 2020 at 6:49 PM Jeevan Chalke <\n>> jeevan.chalke@enterprisedb.com> wrote:\n>>\n>>> Hi Asif,\n>>>\n>>> On Thu, Jan 30, 2020 at 7:10 PM Asif Rehman <asifr.rehman@gmail.com>\n>>> wrote:\n>>>\n>>>>\n>>>> Here are the the updated patches, taking care of the issues pointed\n>>>> earlier. This patch adds the following commands (with specified option):\n>>>>\n>>>> START_BACKUP [LABEL '<label>'] [FAST]\n>>>> STOP_BACKUP [NOWAIT]\n>>>> LIST_TABLESPACES [PROGRESS]\n>>>> LIST_FILES [TABLESPACE]\n>>>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>>> SEND_FILES '(' FILE, FILE... ')' [START_WAL_LOCATION 'X/X']\n>>>> [NOVERIFY_CHECKSUMS]\n>>>>\n>>>>\n>>>> Parallel backup is not making any use of tablespace map, so I have\n>>>> removed that option from the above commands. There is a patch pending\n>>>> to remove the exclusive backup; we can further refactor the\n>>>> do_pg_start_backup\n>>>> function at that time, to remove the tablespace information and move the\n>>>> creation of tablespace_map file to the client.\n>>>>\n>>>>\n>>>> I have disabled the maxrate option for parallel backup. I intend to send\n>>>> out a separate patch for it. Robert previously suggested to implement\n>>>> throttling on the client-side. I found the original email thread [1]\n>>>> where throttling was proposed and added to the server. In that thread,\n>>>> it was originally implemented on the client-side, but per many\n>>>> suggestions,\n>>>> it was moved to server-side.\n>>>>\n>>>> So, I have a few suggestions on how we can implement this:\n>>>>\n>>>> 1- have another option for pg_basebackup (i.e. per-worker-maxrate) where\n>>>> the user could choose the bandwidth allocation for each worker. This\n>>>> approach\n>>>> can be implemented on the client-side as well as on the server-side.\n>>>>\n>>>> 2- have the maxrate, be divided among workers equally at first. and the\n>>>> let the main thread keep adjusting it whenever one of the workers\n>>>> finishes.\n>>>> I believe this would only be possible if we handle throttling on the\n>>>> client.\n>>>> Also, as I understand it, implementing this will introduce additional\n>>>> mutex\n>>>> for handling of bandwidth consumption data so that rate may be adjusted\n>>>> according to data received by threads.\n>>>>\n>>>> [1]\n>>>> https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af\n>>>>\n>>>> --\n>>>> Asif Rehman\n>>>> Highgo Software (Canada/China/Pakistan)\n>>>> URL : www.highgo.ca\n>>>>\n>>>>\n>>>\n>>> The latest changes look good to me. However, the patch set is missing\n>>> the documentation.\n>>> Please add those.\n>>>\n>>> Thanks\n>>>\n>>> --\n>>> Jeevan Chalke\n>>> Associate Database Architect & Team Lead, Product Development\n>>> EnterpriseDB Corporation\n>>> The Enterprise PostgreSQL Company\n>>>\n>>>\n>>\n>> --\n>> --\n>> Asif Rehman\n>> Highgo Software (Canada/China/Pakistan)\n>> URL : www.highgo.ca\n>>\n>>\n>\n> --\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\nHi AsifI have started testing this feature. I have applied v6 patch on commit a069218163704c44a8996e7e98e765c56e2b9c8e (30 Jan).I got few observations, please take a look.--if backup failed, backup directory is not getting removed.[edb@localhost bin]$ ./pg_basebackup -p 5432 --jobs=9 -D /tmp/test_bkp/bkp6pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)[edb@localhost bin]$ ./pg_basebackup -p 5432 --jobs=8 -D /tmp/test_bkp/bkp6pg_basebackup: error: directory \"/tmp/test_bkp/bkp6\" exists but is not empty--giving large number of jobs leading segmentation fault../pg_basebackup -p 5432 --jobs=1000 -D /tmp/t3pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)...pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: error: could not connect to server: could not fork new process for connection: Resource temporarily unavailablecould not fork new process for connection: Resource temporarily unavailablepg_basebackup: error: failed to create thread: Resource temporarily unavailableSegmentation fault (core dumped)--stack-tracegdb -q -c core.11824 pg_basebackupLoaded symbols for /lib64/libnss_files.so.2Core was generated by `./pg_basebackup -p 5432 --jobs=1000 -D /tmp/test_bkp/bkp10'.Program terminated with signal 11, Segmentation fault.#0  pthread_join (threadid=140503120623360, thread_return=0x0) at pthread_join.c:4646\t  if (INVALID_NOT_TERMINATED_TD_P (pd))Missing separate debuginfos, use: debuginfo-install keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64 libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64(gdb) bt#0  pthread_join (threadid=140503120623360, thread_return=0x0) at pthread_join.c:46#1  0x0000000000408e21 in cleanup_workers () at pg_basebackup.c:2840#2  0x0000000000403846 in disconnect_atexit () at pg_basebackup.c:316#3  0x0000003921235a02 in __run_exit_handlers (status=1) at exit.c:78#4  exit (status=1) at exit.c:100#5  0x0000000000408aa6 in create_parallel_workers (backupinfo=0x1a4b8c0) at pg_basebackup.c:2713#6  0x0000000000407946 in BaseBackup () at pg_basebackup.c:2127#7  0x000000000040895c in main (argc=6, argv=0x7ffd566f4718) at pg_basebackup.c:2668--with tablespace is in the same directory as data, parallel_backup crashed[edb@localhost bin]$ ./initdb -D /tmp/data[edb@localhost bin]$ ./pg_ctl -D /tmp/data -l /tmp/logfile start[edb@localhost bin]$ mkdir /tmp/ts[edb@localhost bin]$ ./psql postgres psql (13devel)Type \"help\" for help.postgres=# create tablespace ts location '/tmp/ts';CREATE TABLESPACEpostgres=# create table tx (a int) tablespace ts;CREATE TABLEpostgres=# \\q[edb@localhost bin]$ ./pg_basebackup -j 2 -D /tmp/tts -T /tmp/ts=/tmp/ts1Segmentation fault (core dumped)--stack-trace[edb@localhost bin]$ gdb -q -c core.15778 pg_basebackup Loaded symbols for /lib64/libnss_files.so.2Core was generated by `./pg_basebackup -j 2 -D /tmp/tts -T /tmp/ts=/tmp/ts1'.Program terminated with signal 11, Segmentation fault.#0  0x0000000000409442 in get_backup_filelist (conn=0x140cb20, backupInfo=0x14210a0) at pg_basebackup.c:30003000\t\t\t\t\tbackupInfo->curr->next = file;Missing separate debuginfos, use: debuginfo-install keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64 libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64(gdb) bt#0  0x0000000000409442 in get_backup_filelist (conn=0x140cb20, backupInfo=0x14210a0) at pg_basebackup.c:3000#1  0x0000000000408b56 in parallel_backup_run (backupinfo=0x14210a0) at pg_basebackup.c:2739#2  0x0000000000407955 in BaseBackup () at pg_basebackup.c:2128#3  0x000000000040895c in main (argc=7, argv=0x7ffca2910c58) at pg_basebackup.c:2668(gdb) Thanks & Regards,Rajkumar RaghuwanshiOn Tue, Feb 25, 2020 at 7:49 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Hi,I have created a commitfest entry.https://commitfest.postgresql.org/27/2472/On Mon, Feb 17, 2020 at 1:39 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Thanks Jeevan. Here is the documentation patch.On Mon, Feb 10, 2020 at 6:49 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:Hi Asif,On Thu, Jan 30, 2020 at 7:10 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Here are the the updated patches, taking care of the issues pointedearlier. This patch adds the following commands (with specified option):START_BACKUP [LABEL '<label>'] [FAST]STOP_BACKUP [NOWAIT]LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']SEND_FILES '(' FILE, FILE... ')' [START_WAL_LOCATION 'X/X']                            [NOVERIFY_CHECKSUMS]Parallel backup is not making any use of tablespace map, so I haveremoved that option from the above commands. There is a patch pendingto remove the exclusive backup; we can further refactor the do_pg_start_backupfunction at that time, to remove the tablespace information and move thecreation of tablespace_map file to the client.I have disabled the maxrate option for parallel backup. I intend to sendout a separate patch for it. Robert previously suggested to implementthrottling on the client-side. I found the original email thread [1] where throttling was proposed and added to the server. In that thread,it was originally implemented on the client-side, but per many suggestions,it was moved to server-side.So, I have a few suggestions on how we can implement this:1- have another option for pg_basebackup (i.e. per-worker-maxrate) wherethe user could choose the bandwidth allocation for each worker. This approachcan be implemented on the client-side as well as on the server-side.2- have the maxrate, be divided among workers equally at first. and the let the main thread keep adjusting it whenever one of the workers finishes.I believe this would only be possible if we handle throttling on the client.Also, as I understand it, implementing this will introduce additional mutexfor handling of bandwidth consumption data so that rate may be adjusted according to data received by threads.[1] https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \nThe latest changes look good to me. However, the patch set is missing the documentation.Please add those.Thanks-- Jeevan ChalkeAssociate Database Architect & Team Lead, Product DevelopmentEnterpriseDB CorporationThe Enterprise PostgreSQL Company\n-- --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Wed, 11 Mar 2020 15:08:20 +0530", "msg_from": "Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, Mar 11, 2020 at 2:38 PM Rajkumar Raghuwanshi <\nrajkumar.raghuwanshi@enterprisedb.com> wrote:\n\n> Hi Asif\n>\n> I have started testing this feature. I have applied v6 patch on commit\n> a069218163704c44a8996e7e98e765c56e2b9c8e (30 Jan).\n> I got few observations, please take a look.\n>\n> *--if backup failed, backup directory is not getting removed.*\n> [edb@localhost bin]$ ./pg_basebackup -p 5432 --jobs=9 -D\n> /tmp/test_bkp/bkp6\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> [edb@localhost bin]$ ./pg_basebackup -p 5432 --jobs=8 -D\n> /tmp/test_bkp/bkp6\n> pg_basebackup: error: directory \"/tmp/test_bkp/bkp6\" exists but is not\n> empty\n>\n>\n> *--giving large number of jobs leading segmentation fault.*\n> ./pg_basebackup -p 5432 --jobs=1000 -D /tmp/t3\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> .\n> .\n> .\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: error: could not connect to server: could not fork new\n> process for connection: Resource temporarily unavailable\n>\n> could not fork new process for connection: Resource temporarily unavailable\n> pg_basebackup: error: failed to create thread: Resource temporarily\n> unavailable\n> Segmentation fault (core dumped)\n>\n> --stack-trace\n> gdb -q -c core.11824 pg_basebackup\n> Loaded symbols for /lib64/libnss_files.so.2\n> Core was generated by `./pg_basebackup -p 5432 --jobs=1000 -D\n> /tmp/test_bkp/bkp10'.\n> Program terminated with signal 11, Segmentation fault.\n> #0 pthread_join (threadid=140503120623360, thread_return=0x0) at\n> pthread_join.c:46\n> 46 if (INVALID_NOT_TERMINATED_TD_P (pd))\n> Missing separate debuginfos, use: debuginfo-install\n> keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\n> libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\n> openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n> (gdb) bt\n> #0 pthread_join (threadid=140503120623360, thread_return=0x0) at\n> pthread_join.c:46\n> #1 0x0000000000408e21 in cleanup_workers () at pg_basebackup.c:2840\n> #2 0x0000000000403846 in disconnect_atexit () at pg_basebackup.c:316\n> #3 0x0000003921235a02 in __run_exit_handlers (status=1) at exit.c:78\n> #4 exit (status=1) at exit.c:100\n> #5 0x0000000000408aa6 in create_parallel_workers (backupinfo=0x1a4b8c0)\n> at pg_basebackup.c:2713\n> #6 0x0000000000407946 in BaseBackup () at pg_basebackup.c:2127\n> #7 0x000000000040895c in main (argc=6, argv=0x7ffd566f4718) at\n> pg_basebackup.c:2668\n>\n>\n> *--with tablespace is in the same directory as data, parallel_backup\n> crashed*\n> [edb@localhost bin]$ ./initdb -D /tmp/data\n> [edb@localhost bin]$ ./pg_ctl -D /tmp/data -l /tmp/logfile start\n> [edb@localhost bin]$ mkdir /tmp/ts\n> [edb@localhost bin]$ ./psql postgres\n> psql (13devel)\n> Type \"help\" for help.\n>\n> postgres=# create tablespace ts location '/tmp/ts';\n> CREATE TABLESPACE\n> postgres=# create table tx (a int) tablespace ts;\n> CREATE TABLE\n> postgres=# \\q\n> [edb@localhost bin]$ ./pg_basebackup -j 2 -D /tmp/tts -T /tmp/ts=/tmp/ts1\n> Segmentation fault (core dumped)\n>\n> --stack-trace\n> [edb@localhost bin]$ gdb -q -c core.15778 pg_basebackup\n> Loaded symbols for /lib64/libnss_files.so.2\n> Core was generated by `./pg_basebackup -j 2 -D /tmp/tts -T\n> /tmp/ts=/tmp/ts1'.\n> Program terminated with signal 11, Segmentation fault.\n> #0 0x0000000000409442 in get_backup_filelist (conn=0x140cb20,\n> backupInfo=0x14210a0) at pg_basebackup.c:3000\n> 3000 backupInfo->curr->next = file;\n> Missing separate debuginfos, use: debuginfo-install\n> keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\n> libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\n> openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n> (gdb) bt\n> #0 0x0000000000409442 in get_backup_filelist (conn=0x140cb20,\n> backupInfo=0x14210a0) at pg_basebackup.c:3000\n> #1 0x0000000000408b56 in parallel_backup_run (backupinfo=0x14210a0) at\n> pg_basebackup.c:2739\n> #2 0x0000000000407955 in BaseBackup () at pg_basebackup.c:2128\n> #3 0x000000000040895c in main (argc=7, argv=0x7ffca2910c58) at\n> pg_basebackup.c:2668\n> (gdb)\n>\n\n\nThanks Rajkumar. I have fixed the above issues and have rebased the patch\nto the latest master (b7f64c64).\n(V9 of the patches are attached).\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Fri, 13 Mar 2020 21:21:09 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Thanks for the patches.\n\nI have verified reported issues with new patches, issues are fixed now.\n\nI got another observation where If a new slot name given without -C option,\nit leads to server crash error.\n\n[edb@localhost bin]$ ./pg_basebackup -p 5432 -j 4 -D /tmp/bkp --slot\ntest_bkp_slot\npg_basebackup: error: could not send replication command\n\"START_REPLICATION\": ERROR: replication slot \"test_bkp_slot\" does not exist\npg_basebackup: error: could not list backup files: server closed the\nconnection unexpectedly\nThis probably means the server terminated abnormally\nbefore or while processing the request.\npg_basebackup: removing data directory \"/tmp/bkp\"\n\nThanks & Regards,\nRajkumar Raghuwanshi\n\n\nOn Fri, Mar 13, 2020 at 9:51 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n> On Wed, Mar 11, 2020 at 2:38 PM Rajkumar Raghuwanshi <\n> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>\n>> Hi Asif\n>>\n>> I have started testing this feature. I have applied v6 patch on commit\n>> a069218163704c44a8996e7e98e765c56e2b9c8e (30 Jan).\n>> I got few observations, please take a look.\n>>\n>> *--if backup failed, backup directory is not getting removed.*\n>> [edb@localhost bin]$ ./pg_basebackup -p 5432 --jobs=9 -D\n>> /tmp/test_bkp/bkp6\n>> pg_basebackup: error: could not connect to server: FATAL: number of\n>> requested standby connections exceeds max_wal_senders (currently 10)\n>> [edb@localhost bin]$ ./pg_basebackup -p 5432 --jobs=8 -D\n>> /tmp/test_bkp/bkp6\n>> pg_basebackup: error: directory \"/tmp/test_bkp/bkp6\" exists but is not\n>> empty\n>>\n>>\n>> *--giving large number of jobs leading segmentation fault.*\n>> ./pg_basebackup -p 5432 --jobs=1000 -D /tmp/t3\n>> pg_basebackup: error: could not connect to server: FATAL: number of\n>> requested standby connections exceeds max_wal_senders (currently 10)\n>> pg_basebackup: error: could not connect to server: FATAL: number of\n>> requested standby connections exceeds max_wal_senders (currently 10)\n>> pg_basebackup: error: could not connect to server: FATAL: number of\n>> requested standby connections exceeds max_wal_senders (currently 10)\n>> .\n>> .\n>> .\n>> pg_basebackup: error: could not connect to server: FATAL: number of\n>> requested standby connections exceeds max_wal_senders (currently 10)\n>> pg_basebackup: error: could not connect to server: FATAL: number of\n>> requested standby connections exceeds max_wal_senders (currently 10)\n>> pg_basebackup: error: could not connect to server: FATAL: number of\n>> requested standby connections exceeds max_wal_senders (currently 10)\n>> pg_basebackup: error: could not connect to server: FATAL: number of\n>> requested standby connections exceeds max_wal_senders (currently 10)\n>> pg_basebackup: error: could not connect to server: could not fork new\n>> process for connection: Resource temporarily unavailable\n>>\n>> could not fork new process for connection: Resource temporarily\n>> unavailable\n>> pg_basebackup: error: failed to create thread: Resource temporarily\n>> unavailable\n>> Segmentation fault (core dumped)\n>>\n>> --stack-trace\n>> gdb -q -c core.11824 pg_basebackup\n>> Loaded symbols for /lib64/libnss_files.so.2\n>> Core was generated by `./pg_basebackup -p 5432 --jobs=1000 -D\n>> /tmp/test_bkp/bkp10'.\n>> Program terminated with signal 11, Segmentation fault.\n>> #0 pthread_join (threadid=140503120623360, thread_return=0x0) at\n>> pthread_join.c:46\n>> 46 if (INVALID_NOT_TERMINATED_TD_P (pd))\n>> Missing separate debuginfos, use: debuginfo-install\n>> keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\n>> libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\n>> openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n>> (gdb) bt\n>> #0 pthread_join (threadid=140503120623360, thread_return=0x0) at\n>> pthread_join.c:46\n>> #1 0x0000000000408e21 in cleanup_workers () at pg_basebackup.c:2840\n>> #2 0x0000000000403846 in disconnect_atexit () at pg_basebackup.c:316\n>> #3 0x0000003921235a02 in __run_exit_handlers (status=1) at exit.c:78\n>> #4 exit (status=1) at exit.c:100\n>> #5 0x0000000000408aa6 in create_parallel_workers (backupinfo=0x1a4b8c0)\n>> at pg_basebackup.c:2713\n>> #6 0x0000000000407946 in BaseBackup () at pg_basebackup.c:2127\n>> #7 0x000000000040895c in main (argc=6, argv=0x7ffd566f4718) at\n>> pg_basebackup.c:2668\n>>\n>>\n>> *--with tablespace is in the same directory as data, parallel_backup\n>> crashed*\n>> [edb@localhost bin]$ ./initdb -D /tmp/data\n>> [edb@localhost bin]$ ./pg_ctl -D /tmp/data -l /tmp/logfile start\n>> [edb@localhost bin]$ mkdir /tmp/ts\n>> [edb@localhost bin]$ ./psql postgres\n>> psql (13devel)\n>> Type \"help\" for help.\n>>\n>> postgres=# create tablespace ts location '/tmp/ts';\n>> CREATE TABLESPACE\n>> postgres=# create table tx (a int) tablespace ts;\n>> CREATE TABLE\n>> postgres=# \\q\n>> [edb@localhost bin]$ ./pg_basebackup -j 2 -D /tmp/tts -T /tmp/ts=/tmp/ts1\n>> Segmentation fault (core dumped)\n>>\n>> --stack-trace\n>> [edb@localhost bin]$ gdb -q -c core.15778 pg_basebackup\n>> Loaded symbols for /lib64/libnss_files.so.2\n>> Core was generated by `./pg_basebackup -j 2 -D /tmp/tts -T\n>> /tmp/ts=/tmp/ts1'.\n>> Program terminated with signal 11, Segmentation fault.\n>> #0 0x0000000000409442 in get_backup_filelist (conn=0x140cb20,\n>> backupInfo=0x14210a0) at pg_basebackup.c:3000\n>> 3000 backupInfo->curr->next = file;\n>> Missing separate debuginfos, use: debuginfo-install\n>> keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\n>> libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\n>> openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n>> (gdb) bt\n>> #0 0x0000000000409442 in get_backup_filelist (conn=0x140cb20,\n>> backupInfo=0x14210a0) at pg_basebackup.c:3000\n>> #1 0x0000000000408b56 in parallel_backup_run (backupinfo=0x14210a0) at\n>> pg_basebackup.c:2739\n>> #2 0x0000000000407955 in BaseBackup () at pg_basebackup.c:2128\n>> #3 0x000000000040895c in main (argc=7, argv=0x7ffca2910c58) at\n>> pg_basebackup.c:2668\n>> (gdb)\n>>\n>\n>\n> Thanks Rajkumar. I have fixed the above issues and have rebased the patch\n> to the latest master (b7f64c64).\n> (V9 of the patches are attached).\n>\n>\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\nThanks for the patches.I have verified reported issues with new patches, issues are fixed now. I got another observation where If a new slot name given without -C option, it leads to server crash error.[edb@localhost bin]$ ./pg_basebackup -p 5432 -j 4 -D /tmp/bkp --slot test_bkp_slotpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test_bkp_slot\" does not existpg_basebackup: error: could not list backup files: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.pg_basebackup: removing data directory \"/tmp/bkp\"Thanks & Regards,Rajkumar RaghuwanshiOn Fri, Mar 13, 2020 at 9:51 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Wed, Mar 11, 2020 at 2:38 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi AsifI have started testing this feature. I have applied v6 patch on commit a069218163704c44a8996e7e98e765c56e2b9c8e (30 Jan).I got few observations, please take a look.--if backup failed, backup directory is not getting removed.[edb@localhost bin]$ ./pg_basebackup -p 5432 --jobs=9 -D /tmp/test_bkp/bkp6pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)[edb@localhost bin]$ ./pg_basebackup -p 5432 --jobs=8 -D /tmp/test_bkp/bkp6pg_basebackup: error: directory \"/tmp/test_bkp/bkp6\" exists but is not empty--giving large number of jobs leading segmentation fault../pg_basebackup -p 5432 --jobs=1000 -D /tmp/t3pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)...pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: error: could not connect to server: could not fork new process for connection: Resource temporarily unavailablecould not fork new process for connection: Resource temporarily unavailablepg_basebackup: error: failed to create thread: Resource temporarily unavailableSegmentation fault (core dumped)--stack-tracegdb -q -c core.11824 pg_basebackupLoaded symbols for /lib64/libnss_files.so.2Core was generated by `./pg_basebackup -p 5432 --jobs=1000 -D /tmp/test_bkp/bkp10'.Program terminated with signal 11, Segmentation fault.#0  pthread_join (threadid=140503120623360, thread_return=0x0) at pthread_join.c:4646\t  if (INVALID_NOT_TERMINATED_TD_P (pd))Missing separate debuginfos, use: debuginfo-install keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64 libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64(gdb) bt#0  pthread_join (threadid=140503120623360, thread_return=0x0) at pthread_join.c:46#1  0x0000000000408e21 in cleanup_workers () at pg_basebackup.c:2840#2  0x0000000000403846 in disconnect_atexit () at pg_basebackup.c:316#3  0x0000003921235a02 in __run_exit_handlers (status=1) at exit.c:78#4  exit (status=1) at exit.c:100#5  0x0000000000408aa6 in create_parallel_workers (backupinfo=0x1a4b8c0) at pg_basebackup.c:2713#6  0x0000000000407946 in BaseBackup () at pg_basebackup.c:2127#7  0x000000000040895c in main (argc=6, argv=0x7ffd566f4718) at pg_basebackup.c:2668--with tablespace is in the same directory as data, parallel_backup crashed[edb@localhost bin]$ ./initdb -D /tmp/data[edb@localhost bin]$ ./pg_ctl -D /tmp/data -l /tmp/logfile start[edb@localhost bin]$ mkdir /tmp/ts[edb@localhost bin]$ ./psql postgres psql (13devel)Type \"help\" for help.postgres=# create tablespace ts location '/tmp/ts';CREATE TABLESPACEpostgres=# create table tx (a int) tablespace ts;CREATE TABLEpostgres=# \\q[edb@localhost bin]$ ./pg_basebackup -j 2 -D /tmp/tts -T /tmp/ts=/tmp/ts1Segmentation fault (core dumped)--stack-trace[edb@localhost bin]$ gdb -q -c core.15778 pg_basebackup Loaded symbols for /lib64/libnss_files.so.2Core was generated by `./pg_basebackup -j 2 -D /tmp/tts -T /tmp/ts=/tmp/ts1'.Program terminated with signal 11, Segmentation fault.#0  0x0000000000409442 in get_backup_filelist (conn=0x140cb20, backupInfo=0x14210a0) at pg_basebackup.c:30003000\t\t\t\t\tbackupInfo->curr->next = file;Missing separate debuginfos, use: debuginfo-install keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64 libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64(gdb) bt#0  0x0000000000409442 in get_backup_filelist (conn=0x140cb20, backupInfo=0x14210a0) at pg_basebackup.c:3000#1  0x0000000000408b56 in parallel_backup_run (backupinfo=0x14210a0) at pg_basebackup.c:2739#2  0x0000000000407955 in BaseBackup () at pg_basebackup.c:2128#3  0x000000000040895c in main (argc=7, argv=0x7ffca2910c58) at pg_basebackup.c:2668(gdb)  Thanks Rajkumar. I have fixed the above issues and have rebased the patch to the latest master (b7f64c64).(V9 of the patches are attached). --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Mon, 16 Mar 2020 11:38:31 +0530", "msg_from": "Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Mar 16, 2020 at 11:08 AM Rajkumar Raghuwanshi <\nrajkumar.raghuwanshi@enterprisedb.com> wrote:\n\n> Thanks for the patches.\n>\n> I have verified reported issues with new patches, issues are fixed now.\n>\n> I got another observation where If a new slot name given without -C\n> option, it leads to server crash error.\n>\n> [edb@localhost bin]$ ./pg_basebackup -p 5432 -j 4 -D /tmp/bkp --slot\n> test_bkp_slot\n> pg_basebackup: error: could not send replication command\n> \"START_REPLICATION\": ERROR: replication slot \"test_bkp_slot\" does not exist\n> pg_basebackup: error: could not list backup files: server closed the\n> connection unexpectedly\n> This probably means the server terminated abnormally\n> before or while processing the request.\n> pg_basebackup: removing data directory \"/tmp/bkp\"\n>\n\nIt seems to be an expected behavior. The START_BACKUP command has been\nexecuted, and\npg_basebackup tries to start a WAL streaming process with a non-existent\nslot, which results in\nan error. So the backup is aborted while terminating all other processes.\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nOn Mon, Mar 16, 2020 at 11:08 AM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Thanks for the patches.I have verified reported issues with new patches, issues are fixed now. I got another observation where If a new slot name given without -C option, it leads to server crash error.[edb@localhost bin]$ ./pg_basebackup -p 5432 -j 4 -D /tmp/bkp --slot test_bkp_slotpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test_bkp_slot\" does not existpg_basebackup: error: could not list backup files: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.pg_basebackup: removing data directory \"/tmp/bkp\"It seems to be an expected behavior. The START_BACKUP command has been executed, andpg_basebackup tries to start a WAL streaming process with a non-existent slot, which results inan error. So the backup is aborted while terminating all other processes.--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Mon, 16 Mar 2020 11:21:49 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Mar 16, 2020 at 11:52 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Mon, Mar 16, 2020 at 11:08 AM Rajkumar Raghuwanshi <\n> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>\n>> Thanks for the patches.\n>>\n>> I have verified reported issues with new patches, issues are fixed now.\n>>\n>> I got another observation where If a new slot name given without -C\n>> option, it leads to server crash error.\n>>\n>> [edb@localhost bin]$ ./pg_basebackup -p 5432 -j 4 -D /tmp/bkp --slot\n>> test_bkp_slot\n>> pg_basebackup: error: could not send replication command\n>> \"START_REPLICATION\": ERROR: replication slot \"test_bkp_slot\" does not exist\n>> pg_basebackup: error: could not list backup files: server closed the\n>> connection unexpectedly\n>> This probably means the server terminated abnormally\n>> before or while processing the request.\n>> pg_basebackup: removing data directory \"/tmp/bkp\"\n>>\n>\n> It seems to be an expected behavior. The START_BACKUP command has been\n> executed, and\n> pg_basebackup tries to start a WAL streaming process with a non-existent\n> slot, which results in\n> an error. So the backup is aborted while terminating all other processes.\n>\nI think error message can be improved. current error message looks like\ndatabase server is crashed.\n\non PG same is existing with exit 1.\n[edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp --slot\ntest_bkp_slot\npg_basebackup: error: could not send replication command\n\"START_REPLICATION\": ERROR: replication slot \"test_bkp_slot\" does not exist\npg_basebackup: error: child process exited with exit code 1\npg_basebackup: removing data directory \"/tmp/bkp\"\n\n\n>\n>\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\nOn Mon, Mar 16, 2020 at 11:52 AM Asif Rehman <asifr.rehman@gmail.com> wrote:On Mon, Mar 16, 2020 at 11:08 AM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Thanks for the patches.I have verified reported issues with new patches, issues are fixed now. I got another observation where If a new slot name given without -C option, it leads to server crash error.[edb@localhost bin]$ ./pg_basebackup -p 5432 -j 4 -D /tmp/bkp --slot test_bkp_slotpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test_bkp_slot\" does not existpg_basebackup: error: could not list backup files: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request.pg_basebackup: removing data directory \"/tmp/bkp\"It seems to be an expected behavior. The START_BACKUP command has been executed, andpg_basebackup tries to start a WAL streaming process with a non-existent slot, which results inan error. So the backup is aborted while terminating all other processes.I think error message can be improved. current error message looks like database server is crashed.on PG same is existing with exit 1.[edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp --slot test_bkp_slotpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test_bkp_slot\" does not existpg_basebackup: error: child process exited with exit code 1pg_basebackup: removing data directory \"/tmp/bkp\" --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Mon, 16 Mar 2020 11:56:16 +0530", "msg_from": "Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif,\n\n\n> Thanks Rajkumar. I have fixed the above issues and have rebased the patch\n> to the latest master (b7f64c64).\n> (V9 of the patches are attached).\n>\n\nI had a further review of the patches and here are my few observations:\n\n1.\n+/*\n+ * stop_backup() - ends an online backup\n+ *\n+ * The function is called at the end of an online backup. It sends out\npg_control\n+ * file, optionally WAL segments and ending WAL location.\n+ */\n\nComments seem out-dated.\n\n2. With parallel jobs, maxrate is now not supported. Since we are now asking\ndata in multiple threads throttling seems important here. Can you please\nexplain why have you disabled that?\n\n3. As we are always fetching a single file and as Robert suggested, let\nrename\nSEND_FILES to SEND_FILE instead.\n\n4. Does this work on Windows? I mean does pthread_create() work on Windows?\nI asked this as I see that pgbench has its own implementation for\npthread_create() for WIN32 but this patch doesn't.\n\n5. Typos:\ntablspace => tablespace\nsafly => safely\n\n6. parallel_backup_run() needs some comments explaining the states it goes\nthrough PB_* states.\n\n7.\n+ case PB_FETCH_REL_FILES: /* fetch files from server */\n+ if (backupinfo->activeworkers == 0)\n+ {\n+ backupinfo->backupstate = PB_STOP_BACKUP;\n+ free_filelist(backupinfo);\n+ }\n+ break;\n+ case PB_FETCH_WAL_FILES: /* fetch WAL files from server */\n+ if (backupinfo->activeworkers == 0)\n+ {\n+ backupinfo->backupstate = PB_BACKUP_COMPLETE;\n+ }\n+ break;\n\nWhy free_filelist() is not called in PB_FETCH_WAL_FILES case?\n\nThanks\n-- \nJeevan Chalke\nAssociate Database Architect & Team Lead, Product Development\nEnterpriseDB Corporation\nThe Enterprise PostgreSQL Company\n\nPhone: +91 20 66449694\n\nWebsite: www.enterprisedb.com\nEnterpriseDB Blog: http://blogs.enterprisedb.com/\nFollow us on Twitter: http://www.twitter.com/enterprisedb\n\nThis e-mail message (and any attachment) is intended for the use of the\nindividual or entity to whom it is addressed. This message contains\ninformation from EnterpriseDB Corporation that may be privileged,\nconfidential, or exempt from disclosure under applicable law. If you are\nnot the intended recipient or authorized to receive this for the intended\nrecipient, any use, dissemination, distribution, retention, archiving, or\ncopying of this communication is strictly prohibited. If you have received\nthis e-mail in error, please notify the sender immediately by reply e-mail\nand delete this message.\n\nHi Asif, Thanks Rajkumar. I have fixed the above issues and have rebased the patch to the latest master (b7f64c64).(V9 of the patches are attached).I had a further review of the patches and here are my few observations: 1.+/*+ * stop_backup() - ends an online backup+ *+ * The function is called at the end of an online backup. It sends out pg_control+ * file, optionally WAL segments and ending WAL location.+ */Comments seem out-dated.2. With parallel jobs, maxrate is now not supported. Since we are now askingdata in multiple threads throttling seems important here. Can you pleaseexplain why have you disabled that?3. As we are always fetching a single file and as Robert suggested, let renameSEND_FILES to SEND_FILE instead.4. Does this work on Windows? I mean does pthread_create() work on Windows?I asked this as I see that pgbench has its own implementation forpthread_create() for WIN32 but this patch doesn't.5. Typos:tablspace => tablespacesafly => safely6. parallel_backup_run() needs some comments explaining the states it goesthrough PB_* states.7. +            case PB_FETCH_REL_FILES:    /* fetch files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_STOP_BACKUP;+                    free_filelist(backupinfo);+                }+                break;+            case PB_FETCH_WAL_FILES:    /* fetch WAL files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_BACKUP_COMPLETE;+                }+                break;Why free_filelist() is not called in PB_FETCH_WAL_FILES case?Thanks-- Jeevan ChalkeAssociate Database Architect & Team Lead, Product DevelopmentEnterpriseDB CorporationThe Enterprise PostgreSQL CompanyPhone: +91 20 66449694Website: www.enterprisedb.comEnterpriseDB Blog: http://blogs.enterprisedb.com/Follow us on Twitter: http://www.twitter.com/enterprisedbThis e-mail message (and any attachment) is intended for the use of the individual or entity to whom it is addressed. This message contains information from EnterpriseDB Corporation that may be privileged, confidential, or exempt from disclosure under applicable law. If you are not the intended recipient or authorized to receive this for the intended recipient, any use, dissemination, distribution, retention, archiving, or copying of this communication is strictly prohibited. If you have received this e-mail in error, please notify the sender immediately by reply e-mail and delete this message.", "msg_date": "Mon, 16 Mar 2020 14:13:48 +0530", "msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif,\n\nOn testing further, I found when taking backup with -R, pg_basebackup\ncrashed\nthis crash is not consistently reproducible.\n\n[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a\ntext);\"\nCREATE TABLE\n[edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test values\n('parallel_backup with -R recovery-conf');\"\nINSERT 0 1\n[edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -R\nSegmentation fault (core dumped)\n\nstack trace looks the same as it was on earlier reported crash with\ntablespace.\n--stack trace\n[edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup\nLoaded symbols for /lib64/libnss_files.so.2\nCore was generated by `./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp\n-R'.\nProgram terminated with signal 11, Segmentation fault.\n#0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\npg_basebackup.c:3175\n3175 backupinfo->curr = fetchfile->next;\nMissing separate debuginfos, use: debuginfo-install\nkeyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\nlibcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\nopenssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n(gdb) bt\n#0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\npg_basebackup.c:3175\n#1 0x0000000000408a9e in worker_run (arg=0xc1e458) at pg_basebackup.c:2715\n#2 0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at\npthread_create.c:301\n#3 0x00000039212e8c4d in clone () at\n../sysdeps/unix/sysv/linux/x86_64/clone.S:115\n(gdb)\n\nThanks & Regards,\nRajkumar Raghuwanshi\n\n\nOn Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <\njeevan.chalke@enterprisedb.com> wrote:\n\n> Hi Asif,\n>\n>\n>> Thanks Rajkumar. I have fixed the above issues and have rebased the patch\n>> to the latest master (b7f64c64).\n>> (V9 of the patches are attached).\n>>\n>\n> I had a further review of the patches and here are my few observations:\n>\n> 1.\n> +/*\n> + * stop_backup() - ends an online backup\n> + *\n> + * The function is called at the end of an online backup. It sends out\n> pg_control\n> + * file, optionally WAL segments and ending WAL location.\n> + */\n>\n> Comments seem out-dated.\n>\n> 2. With parallel jobs, maxrate is now not supported. Since we are now\n> asking\n> data in multiple threads throttling seems important here. Can you please\n> explain why have you disabled that?\n>\n> 3. As we are always fetching a single file and as Robert suggested, let\n> rename\n> SEND_FILES to SEND_FILE instead.\n>\n> 4. Does this work on Windows? I mean does pthread_create() work on Windows?\n> I asked this as I see that pgbench has its own implementation for\n> pthread_create() for WIN32 but this patch doesn't.\n>\n> 5. Typos:\n> tablspace => tablespace\n> safly => safely\n>\n> 6. parallel_backup_run() needs some comments explaining the states it goes\n> through PB_* states.\n>\n> 7.\n> + case PB_FETCH_REL_FILES: /* fetch files from server */\n> + if (backupinfo->activeworkers == 0)\n> + {\n> + backupinfo->backupstate = PB_STOP_BACKUP;\n> + free_filelist(backupinfo);\n> + }\n> + break;\n> + case PB_FETCH_WAL_FILES: /* fetch WAL files from server */\n> + if (backupinfo->activeworkers == 0)\n> + {\n> + backupinfo->backupstate = PB_BACKUP_COMPLETE;\n> + }\n> + break;\n>\n> Why free_filelist() is not called in PB_FETCH_WAL_FILES case?\n>\n> Thanks\n> --\n> Jeevan Chalke\n> Associate Database Architect & Team Lead, Product Development\n> EnterpriseDB Corporation\n> The Enterprise PostgreSQL Company\n>\n> Phone: +91 20 66449694\n>\n> Website: www.enterprisedb.com\n> EnterpriseDB Blog: http://blogs.enterprisedb.com/\n> Follow us on Twitter: http://www.twitter.com/enterprisedb\n>\n> This e-mail message (and any attachment) is intended for the use of the\n> individual or entity to whom it is addressed. This message contains\n> information from EnterpriseDB Corporation that may be privileged,\n> confidential, or exempt from disclosure under applicable law. If you are\n> not the intended recipient or authorized to receive this for the intended\n> recipient, any use, dissemination, distribution, retention, archiving, or\n> copying of this communication is strictly prohibited. If you have received\n> this e-mail in error, please notify the sender immediately by reply e-mail\n> and delete this message.\n>\n\nHi Asif,On testing further, I found when taking backup with -R, pg_basebackup crashedthis crash is not consistently reproducible.[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a text);\"CREATE TABLE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test values ('parallel_backup with -R recovery-conf');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -RSegmentation fault (core dumped)stack trace looks the same as it was on earlier reported crash with tablespace.--stack trace[edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup Loaded symbols for /lib64/libnss_files.so.2Core was generated by `./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -R'.Program terminated with signal 11, Segmentation fault.#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:31753175\t\t\t\tbackupinfo->curr = fetchfile->next;Missing separate debuginfos, use: debuginfo-install keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64 libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64(gdb) bt#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:3175#1  0x0000000000408a9e in worker_run (arg=0xc1e458) at pg_basebackup.c:2715#2  0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at pthread_create.c:301#3  0x00000039212e8c4d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:115(gdb) Thanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:Hi Asif, Thanks Rajkumar. I have fixed the above issues and have rebased the patch to the latest master (b7f64c64).(V9 of the patches are attached).I had a further review of the patches and here are my few observations: 1.+/*+ * stop_backup() - ends an online backup+ *+ * The function is called at the end of an online backup. It sends out pg_control+ * file, optionally WAL segments and ending WAL location.+ */Comments seem out-dated.2. With parallel jobs, maxrate is now not supported. Since we are now askingdata in multiple threads throttling seems important here. Can you pleaseexplain why have you disabled that?3. As we are always fetching a single file and as Robert suggested, let renameSEND_FILES to SEND_FILE instead.4. Does this work on Windows? I mean does pthread_create() work on Windows?I asked this as I see that pgbench has its own implementation forpthread_create() for WIN32 but this patch doesn't.5. Typos:tablspace => tablespacesafly => safely6. parallel_backup_run() needs some comments explaining the states it goesthrough PB_* states.7. +            case PB_FETCH_REL_FILES:    /* fetch files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_STOP_BACKUP;+                    free_filelist(backupinfo);+                }+                break;+            case PB_FETCH_WAL_FILES:    /* fetch WAL files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_BACKUP_COMPLETE;+                }+                break;Why free_filelist() is not called in PB_FETCH_WAL_FILES case?Thanks-- Jeevan ChalkeAssociate Database Architect & Team Lead, Product DevelopmentEnterpriseDB CorporationThe Enterprise PostgreSQL CompanyPhone: +91 20 66449694Website: www.enterprisedb.comEnterpriseDB Blog: http://blogs.enterprisedb.com/Follow us on Twitter: http://www.twitter.com/enterprisedbThis e-mail message (and any attachment) is intended for the use of the individual or entity to whom it is addressed. This message contains information from EnterpriseDB Corporation that may be privileged, confidential, or exempt from disclosure under applicable law. If you are not the intended recipient or authorized to receive this for the intended recipient, any use, dissemination, distribution, retention, archiving, or copying of this communication is strictly prohibited. If you have received this e-mail in error, please notify the sender immediately by reply e-mail and delete this message.", "msg_date": "Mon, 16 Mar 2020 18:19:44 +0530", "msg_from": "Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif,\n\nIn another scenarios, bkp data is corrupted for tablespace. again this is\nnot reproducible everytime,\nbut If I am running the same set of commands I am getting the same error.\n\n[edb@localhost bin]$ ./pg_ctl -D data -l logfile start\nwaiting for server to start.... done\nserver started\n[edb@localhost bin]$\n[edb@localhost bin]$ mkdir /tmp/tblsp\n[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace tblsp\nlocation '/tmp/tblsp';\"\nCREATE TABLESPACE\n[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create database testdb\ntablespace tblsp;\"\nCREATE DATABASE\n[edb@localhost bin]$ ./psql testdb -p 5432 -c \"create table testtbl (a\ntext);\"\nCREATE TABLE\n[edb@localhost bin]$ ./psql testdb -p 5432 -c \"insert into testtbl values\n('parallel_backup with tablespace');\"\nINSERT 0 1\n[edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp -T\n/tmp/tblsp=/tmp/tblsp_bkp --jobs 2\n[edb@localhost bin]$ ./pg_ctl -D /tmp/bkp -l /tmp/bkp_logs -o \"-p 5555\"\nstart\nwaiting for server to start.... done\nserver started\n[edb@localhost bin]$ ./psql postgres -p 5555 -c \"select * from\npg_tablespace where spcname like 'tblsp%' or spcname = 'pg_default'\";\n oid | spcname | spcowner | spcacl | spcoptions\n-------+------------+----------+--------+------------\n 1663 | pg_default | 10 | |\n 16384 | tblsp | 10 | |\n(2 rows)\n\n[edb@localhost bin]$ ./psql testdb -p 5555 -c \"select * from testtbl\";\npsql: error: could not connect to server: FATAL:\n \"pg_tblspc/16384/PG_13_202003051/16385\" is not a valid data directory\nDETAIL: File \"pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\" is missing.\n[edb@localhost bin]$\n[edb@localhost bin]$ ls\ndata/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\ndata/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n[edb@localhost bin]$ ls\n/tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\nls: cannot access\n/tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION: No such file or\ndirectory\n\n\nThanks & Regards,\nRajkumar Raghuwanshi\n\n\nOn Mon, Mar 16, 2020 at 6:19 PM Rajkumar Raghuwanshi <\nrajkumar.raghuwanshi@enterprisedb.com> wrote:\n\n> Hi Asif,\n>\n> On testing further, I found when taking backup with -R, pg_basebackup\n> crashed\n> this crash is not consistently reproducible.\n>\n> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a\n> text);\"\n> CREATE TABLE\n> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test values\n> ('parallel_backup with -R recovery-conf');\"\n> INSERT 0 1\n> [edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -R\n> Segmentation fault (core dumped)\n>\n> stack trace looks the same as it was on earlier reported crash with\n> tablespace.\n> --stack trace\n> [edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup\n> Loaded symbols for /lib64/libnss_files.so.2\n> Core was generated by `./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp\n> -R'.\n> Program terminated with signal 11, Segmentation fault.\n> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n> pg_basebackup.c:3175\n> 3175 backupinfo->curr = fetchfile->next;\n> Missing separate debuginfos, use: debuginfo-install\n> keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\n> libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\n> openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n> (gdb) bt\n> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n> pg_basebackup.c:3175\n> #1 0x0000000000408a9e in worker_run (arg=0xc1e458) at pg_basebackup.c:2715\n> #2 0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at\n> pthread_create.c:301\n> #3 0x00000039212e8c4d in clone () at\n> ../sysdeps/unix/sysv/linux/x86_64/clone.S:115\n> (gdb)\n>\n> Thanks & Regards,\n> Rajkumar Raghuwanshi\n>\n>\n> On Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <\n> jeevan.chalke@enterprisedb.com> wrote:\n>\n>> Hi Asif,\n>>\n>>\n>>> Thanks Rajkumar. I have fixed the above issues and have rebased the\n>>> patch to the latest master (b7f64c64).\n>>> (V9 of the patches are attached).\n>>>\n>>\n>> I had a further review of the patches and here are my few observations:\n>>\n>> 1.\n>> +/*\n>> + * stop_backup() - ends an online backup\n>> + *\n>> + * The function is called at the end of an online backup. It sends out\n>> pg_control\n>> + * file, optionally WAL segments and ending WAL location.\n>> + */\n>>\n>> Comments seem out-dated.\n>>\n>> 2. With parallel jobs, maxrate is now not supported. Since we are now\n>> asking\n>> data in multiple threads throttling seems important here. Can you please\n>> explain why have you disabled that?\n>>\n>> 3. As we are always fetching a single file and as Robert suggested, let\n>> rename\n>> SEND_FILES to SEND_FILE instead.\n>>\n>> 4. Does this work on Windows? I mean does pthread_create() work on\n>> Windows?\n>> I asked this as I see that pgbench has its own implementation for\n>> pthread_create() for WIN32 but this patch doesn't.\n>>\n>> 5. Typos:\n>> tablspace => tablespace\n>> safly => safely\n>>\n>> 6. parallel_backup_run() needs some comments explaining the states it goes\n>> through PB_* states.\n>>\n>> 7.\n>> + case PB_FETCH_REL_FILES: /* fetch files from server */\n>> + if (backupinfo->activeworkers == 0)\n>> + {\n>> + backupinfo->backupstate = PB_STOP_BACKUP;\n>> + free_filelist(backupinfo);\n>> + }\n>> + break;\n>> + case PB_FETCH_WAL_FILES: /* fetch WAL files from server */\n>> + if (backupinfo->activeworkers == 0)\n>> + {\n>> + backupinfo->backupstate = PB_BACKUP_COMPLETE;\n>> + }\n>> + break;\n>>\n>> Why free_filelist() is not called in PB_FETCH_WAL_FILES case?\n>>\n>> Thanks\n>> --\n>> Jeevan Chalke\n>> Associate Database Architect & Team Lead, Product Development\n>> EnterpriseDB Corporation\n>> The Enterprise PostgreSQL Company\n>>\n>> Phone: +91 20 66449694\n>>\n>> Website: www.enterprisedb.com\n>> EnterpriseDB Blog: http://blogs.enterprisedb.com/\n>> Follow us on Twitter: http://www.twitter.com/enterprisedb\n>>\n>> This e-mail message (and any attachment) is intended for the use of the\n>> individual or entity to whom it is addressed. This message contains\n>> information from EnterpriseDB Corporation that may be privileged,\n>> confidential, or exempt from disclosure under applicable law. If you are\n>> not the intended recipient or authorized to receive this for the intended\n>> recipient, any use, dissemination, distribution, retention, archiving, or\n>> copying of this communication is strictly prohibited. If you have received\n>> this e-mail in error, please notify the sender immediately by reply e-mail\n>> and delete this message.\n>>\n>\n\nHi Asif,In another scenarios, bkp data is corrupted for tablespace. again this is not reproducible everytime,but If I am running the same set of commands I am getting the same error.[edb@localhost bin]$ ./pg_ctl -D data -l logfile startwaiting for server to start.... doneserver started[edb@localhost bin]$ [edb@localhost bin]$ mkdir /tmp/tblsp[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace tblsp location '/tmp/tblsp';\"CREATE TABLESPACE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create database testdb tablespace tblsp;\"CREATE DATABASE[edb@localhost bin]$ ./psql testdb -p 5432 -c \"create table testtbl (a text);\"CREATE TABLE[edb@localhost bin]$ ./psql testdb -p 5432 -c \"insert into testtbl values ('parallel_backup with tablespace');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp -T /tmp/tblsp=/tmp/tblsp_bkp --jobs 2 [edb@localhost bin]$ ./pg_ctl -D /tmp/bkp -l /tmp/bkp_logs -o \"-p 5555\" startwaiting for server to start.... doneserver started[edb@localhost bin]$ ./psql postgres -p 5555 -c \"select * from pg_tablespace where spcname like 'tblsp%' or spcname = 'pg_default'\";  oid  |  spcname   | spcowner | spcacl | spcoptions -------+------------+----------+--------+------------  1663 | pg_default |       10 |        |  16384 | tblsp      |       10 |        | (2 rows)[edb@localhost bin]$ ./psql testdb -p 5555 -c \"select * from testtbl\";psql: error: could not connect to server: FATAL:  \"pg_tblspc/16384/PG_13_202003051/16385\" is not a valid data directoryDETAIL:  File \"pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\" is missing.[edb@localhost bin]$ [edb@localhost bin]$ ls data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSIONdata/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION[edb@localhost bin]$ ls /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSIONls: cannot access /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION: No such file or directoryThanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 16, 2020 at 6:19 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,On testing further, I found when taking backup with -R, pg_basebackup crashedthis crash is not consistently reproducible.[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a text);\"CREATE TABLE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test values ('parallel_backup with -R recovery-conf');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -RSegmentation fault (core dumped)stack trace looks the same as it was on earlier reported crash with tablespace.--stack trace[edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup Loaded symbols for /lib64/libnss_files.so.2Core was generated by `./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -R'.Program terminated with signal 11, Segmentation fault.#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:31753175\t\t\t\tbackupinfo->curr = fetchfile->next;Missing separate debuginfos, use: debuginfo-install keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64 libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64(gdb) bt#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:3175#1  0x0000000000408a9e in worker_run (arg=0xc1e458) at pg_basebackup.c:2715#2  0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at pthread_create.c:301#3  0x00000039212e8c4d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:115(gdb) Thanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:Hi Asif, Thanks Rajkumar. I have fixed the above issues and have rebased the patch to the latest master (b7f64c64).(V9 of the patches are attached).I had a further review of the patches and here are my few observations: 1.+/*+ * stop_backup() - ends an online backup+ *+ * The function is called at the end of an online backup. It sends out pg_control+ * file, optionally WAL segments and ending WAL location.+ */Comments seem out-dated.2. With parallel jobs, maxrate is now not supported. Since we are now askingdata in multiple threads throttling seems important here. Can you pleaseexplain why have you disabled that?3. As we are always fetching a single file and as Robert suggested, let renameSEND_FILES to SEND_FILE instead.4. Does this work on Windows? I mean does pthread_create() work on Windows?I asked this as I see that pgbench has its own implementation forpthread_create() for WIN32 but this patch doesn't.5. Typos:tablspace => tablespacesafly => safely6. parallel_backup_run() needs some comments explaining the states it goesthrough PB_* states.7. +            case PB_FETCH_REL_FILES:    /* fetch files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_STOP_BACKUP;+                    free_filelist(backupinfo);+                }+                break;+            case PB_FETCH_WAL_FILES:    /* fetch WAL files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_BACKUP_COMPLETE;+                }+                break;Why free_filelist() is not called in PB_FETCH_WAL_FILES case?Thanks-- Jeevan ChalkeAssociate Database Architect & Team Lead, Product DevelopmentEnterpriseDB CorporationThe Enterprise PostgreSQL CompanyPhone: +91 20 66449694Website: www.enterprisedb.comEnterpriseDB Blog: http://blogs.enterprisedb.com/Follow us on Twitter: http://www.twitter.com/enterprisedbThis e-mail message (and any attachment) is intended for the use of the individual or entity to whom it is addressed. This message contains information from EnterpriseDB Corporation that may be privileged, confidential, or exempt from disclosure under applicable law. If you are not the intended recipient or authorized to receive this for the intended recipient, any use, dissemination, distribution, retention, archiving, or copying of this communication is strictly prohibited. If you have received this e-mail in error, please notify the sender immediately by reply e-mail and delete this message.", "msg_date": "Thu, 19 Mar 2020 16:11:24 +0530", "msg_from": "Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif,\n\nWhile testing further I observed parallel backup is not able to take backup\nof standby server.\n\nmkdir /tmp/archive_dir\necho \"archive_mode='on'\">> data/postgresql.conf\necho \"archive_command='cp %p /tmp/archive_dir/%f'\">> data/postgresql.conf\n\n./pg_ctl -D data -l logs start\n./pg_basebackup -p 5432 -Fp -R -D /tmp/slave\n\necho \"primary_conninfo='host=127.0.0.1 port=5432 user=edb'\">>\n/tmp/slave/postgresql.conf\necho \"restore_command='cp /tmp/archive_dir/%f %p'\">>\n/tmp/slave/postgresql.conf\necho \"promote_trigger_file='/tmp/failover.log'\">> /tmp/slave/postgresql.conf\n\n./pg_ctl -D /tmp/slave -l /tmp/slave_logs -o \"-p 5433\" start -c\n\n[edb@localhost bin]$ ./psql postgres -p 5432 -c \"select\npg_is_in_recovery();\"\n pg_is_in_recovery\n-------------------\n f\n(1 row)\n\n[edb@localhost bin]$ ./psql postgres -p 5433 -c \"select\npg_is_in_recovery();\"\n pg_is_in_recovery\n-------------------\n t\n(1 row)\n\n\n\n\n*[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs\n6pg_basebackup: error: could not list backup files: ERROR: the standby was\npromoted during online backupHINT: This means that the backup being taken\nis corrupt and should not be used. Try taking another online\nbackup.pg_basebackup: removing data directory \"/tmp/bkp_s\"*\n\n#same is working fine without parallel backup\n[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 1\n[edb@localhost bin]$ ls /tmp/bkp_s/PG_VERSION\n/tmp/bkp_s/PG_VERSION\n\nThanks & Regards,\nRajkumar Raghuwanshi\n\n\nOn Thu, Mar 19, 2020 at 4:11 PM Rajkumar Raghuwanshi <\nrajkumar.raghuwanshi@enterprisedb.com> wrote:\n\n> Hi Asif,\n>\n> In another scenarios, bkp data is corrupted for tablespace. again this is\n> not reproducible everytime,\n> but If I am running the same set of commands I am getting the same error.\n>\n> [edb@localhost bin]$ ./pg_ctl -D data -l logfile start\n> waiting for server to start.... done\n> server started\n> [edb@localhost bin]$\n> [edb@localhost bin]$ mkdir /tmp/tblsp\n> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace tblsp\n> location '/tmp/tblsp';\"\n> CREATE TABLESPACE\n> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create database testdb\n> tablespace tblsp;\"\n> CREATE DATABASE\n> [edb@localhost bin]$ ./psql testdb -p 5432 -c \"create table testtbl (a\n> text);\"\n> CREATE TABLE\n> [edb@localhost bin]$ ./psql testdb -p 5432 -c \"insert into testtbl values\n> ('parallel_backup with tablespace');\"\n> INSERT 0 1\n> [edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp -T\n> /tmp/tblsp=/tmp/tblsp_bkp --jobs 2\n> [edb@localhost bin]$ ./pg_ctl -D /tmp/bkp -l /tmp/bkp_logs -o \"-p 5555\"\n> start\n> waiting for server to start.... done\n> server started\n> [edb@localhost bin]$ ./psql postgres -p 5555 -c \"select * from\n> pg_tablespace where spcname like 'tblsp%' or spcname = 'pg_default'\";\n> oid | spcname | spcowner | spcacl | spcoptions\n> -------+------------+----------+--------+------------\n> 1663 | pg_default | 10 | |\n> 16384 | tblsp | 10 | |\n> (2 rows)\n>\n> [edb@localhost bin]$ ./psql testdb -p 5555 -c \"select * from testtbl\";\n> psql: error: could not connect to server: FATAL:\n> \"pg_tblspc/16384/PG_13_202003051/16385\" is not a valid data directory\n> DETAIL: File \"pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\" is\n> missing.\n> [edb@localhost bin]$\n> [edb@localhost bin]$ ls\n> data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n> data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n> [edb@localhost bin]$ ls\n> /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n> ls: cannot access\n> /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION: No such file or\n> directory\n>\n>\n> Thanks & Regards,\n> Rajkumar Raghuwanshi\n>\n>\n> On Mon, Mar 16, 2020 at 6:19 PM Rajkumar Raghuwanshi <\n> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>\n>> Hi Asif,\n>>\n>> On testing further, I found when taking backup with -R, pg_basebackup\n>> crashed\n>> this crash is not consistently reproducible.\n>>\n>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a\n>> text);\"\n>> CREATE TABLE\n>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test values\n>> ('parallel_backup with -R recovery-conf');\"\n>> INSERT 0 1\n>> [edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -R\n>> Segmentation fault (core dumped)\n>>\n>> stack trace looks the same as it was on earlier reported crash with\n>> tablespace.\n>> --stack trace\n>> [edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup\n>> Loaded symbols for /lib64/libnss_files.so.2\n>> Core was generated by `./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp\n>> -R'.\n>> Program terminated with signal 11, Segmentation fault.\n>> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n>> pg_basebackup.c:3175\n>> 3175 backupinfo->curr = fetchfile->next;\n>> Missing separate debuginfos, use: debuginfo-install\n>> keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\n>> libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\n>> openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n>> (gdb) bt\n>> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n>> pg_basebackup.c:3175\n>> #1 0x0000000000408a9e in worker_run (arg=0xc1e458) at\n>> pg_basebackup.c:2715\n>> #2 0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at\n>> pthread_create.c:301\n>> #3 0x00000039212e8c4d in clone () at\n>> ../sysdeps/unix/sysv/linux/x86_64/clone.S:115\n>> (gdb)\n>>\n>> Thanks & Regards,\n>> Rajkumar Raghuwanshi\n>>\n>>\n>> On Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <\n>> jeevan.chalke@enterprisedb.com> wrote:\n>>\n>>> Hi Asif,\n>>>\n>>>\n>>>> Thanks Rajkumar. I have fixed the above issues and have rebased the\n>>>> patch to the latest master (b7f64c64).\n>>>> (V9 of the patches are attached).\n>>>>\n>>>\n>>> I had a further review of the patches and here are my few observations:\n>>>\n>>> 1.\n>>> +/*\n>>> + * stop_backup() - ends an online backup\n>>> + *\n>>> + * The function is called at the end of an online backup. It sends out\n>>> pg_control\n>>> + * file, optionally WAL segments and ending WAL location.\n>>> + */\n>>>\n>>> Comments seem out-dated.\n>>>\n>>> 2. With parallel jobs, maxrate is now not supported. Since we are now\n>>> asking\n>>> data in multiple threads throttling seems important here. Can you please\n>>> explain why have you disabled that?\n>>>\n>>> 3. As we are always fetching a single file and as Robert suggested, let\n>>> rename\n>>> SEND_FILES to SEND_FILE instead.\n>>>\n>>> 4. Does this work on Windows? I mean does pthread_create() work on\n>>> Windows?\n>>> I asked this as I see that pgbench has its own implementation for\n>>> pthread_create() for WIN32 but this patch doesn't.\n>>>\n>>> 5. Typos:\n>>> tablspace => tablespace\n>>> safly => safely\n>>>\n>>> 6. parallel_backup_run() needs some comments explaining the states it\n>>> goes\n>>> through PB_* states.\n>>>\n>>> 7.\n>>> + case PB_FETCH_REL_FILES: /* fetch files from server */\n>>> + if (backupinfo->activeworkers == 0)\n>>> + {\n>>> + backupinfo->backupstate = PB_STOP_BACKUP;\n>>> + free_filelist(backupinfo);\n>>> + }\n>>> + break;\n>>> + case PB_FETCH_WAL_FILES: /* fetch WAL files from server\n>>> */\n>>> + if (backupinfo->activeworkers == 0)\n>>> + {\n>>> + backupinfo->backupstate = PB_BACKUP_COMPLETE;\n>>> + }\n>>> + break;\n>>>\n>>> Why free_filelist() is not called in PB_FETCH_WAL_FILES case?\n>>>\n>>> Thanks\n>>> --\n>>> Jeevan Chalke\n>>> Associate Database Architect & Team Lead, Product Development\n>>> EnterpriseDB Corporation\n>>> The Enterprise PostgreSQL Company\n>>>\n>>> Phone: +91 20 66449694\n>>>\n>>> Website: www.enterprisedb.com\n>>> EnterpriseDB Blog: http://blogs.enterprisedb.com/\n>>> Follow us on Twitter: http://www.twitter.com/enterprisedb\n>>>\n>>> This e-mail message (and any attachment) is intended for the use of the\n>>> individual or entity to whom it is addressed. This message contains\n>>> information from EnterpriseDB Corporation that may be privileged,\n>>> confidential, or exempt from disclosure under applicable law. If you are\n>>> not the intended recipient or authorized to receive this for the intended\n>>> recipient, any use, dissemination, distribution, retention, archiving, or\n>>> copying of this communication is strictly prohibited. If you have received\n>>> this e-mail in error, please notify the sender immediately by reply e-mail\n>>> and delete this message.\n>>>\n>>\n\nHi Asif,While testing further I observed parallel backup is not able to take backup of standby server.mkdir /tmp/archive_direcho \"archive_mode='on'\">> data/postgresql.confecho \"archive_command='cp %p /tmp/archive_dir/%f'\">> data/postgresql.conf./pg_ctl -D data -l logs start./pg_basebackup -p 5432 -Fp -R -D /tmp/slaveecho \"primary_conninfo='host=127.0.0.1 port=5432 user=edb'\">> /tmp/slave/postgresql.confecho \"restore_command='cp /tmp/archive_dir/%f %p'\">> /tmp/slave/postgresql.confecho \"promote_trigger_file='/tmp/failover.log'\">> /tmp/slave/postgresql.conf./pg_ctl -D /tmp/slave -l /tmp/slave_logs -o \"-p 5433\" start -c [edb@localhost bin]$ ./psql postgres -p 5432 -c \"select pg_is_in_recovery();\" pg_is_in_recovery ------------------- f(1 row)[edb@localhost bin]$ ./psql postgres -p 5433 -c \"select pg_is_in_recovery();\" pg_is_in_recovery ------------------- t(1 row)[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 6pg_basebackup: error: could not list backup files: ERROR:  the standby was promoted during online backupHINT:  This means that the backup being taken is corrupt and should not be used. Try taking another online backup.pg_basebackup: removing data directory \"/tmp/bkp_s\"#same is working fine without parallel backup[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 1[edb@localhost bin]$ ls /tmp/bkp_s/PG_VERSION/tmp/bkp_s/PG_VERSIONThanks & Regards,Rajkumar RaghuwanshiOn Thu, Mar 19, 2020 at 4:11 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,In another scenarios, bkp data is corrupted for tablespace. again this is not reproducible everytime,but If I am running the same set of commands I am getting the same error.[edb@localhost bin]$ ./pg_ctl -D data -l logfile startwaiting for server to start.... doneserver started[edb@localhost bin]$ [edb@localhost bin]$ mkdir /tmp/tblsp[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace tblsp location '/tmp/tblsp';\"CREATE TABLESPACE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create database testdb tablespace tblsp;\"CREATE DATABASE[edb@localhost bin]$ ./psql testdb -p 5432 -c \"create table testtbl (a text);\"CREATE TABLE[edb@localhost bin]$ ./psql testdb -p 5432 -c \"insert into testtbl values ('parallel_backup with tablespace');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp -T /tmp/tblsp=/tmp/tblsp_bkp --jobs 2 [edb@localhost bin]$ ./pg_ctl -D /tmp/bkp -l /tmp/bkp_logs -o \"-p 5555\" startwaiting for server to start.... doneserver started[edb@localhost bin]$ ./psql postgres -p 5555 -c \"select * from pg_tablespace where spcname like 'tblsp%' or spcname = 'pg_default'\";  oid  |  spcname   | spcowner | spcacl | spcoptions -------+------------+----------+--------+------------  1663 | pg_default |       10 |        |  16384 | tblsp      |       10 |        | (2 rows)[edb@localhost bin]$ ./psql testdb -p 5555 -c \"select * from testtbl\";psql: error: could not connect to server: FATAL:  \"pg_tblspc/16384/PG_13_202003051/16385\" is not a valid data directoryDETAIL:  File \"pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\" is missing.[edb@localhost bin]$ [edb@localhost bin]$ ls data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSIONdata/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION[edb@localhost bin]$ ls /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSIONls: cannot access /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION: No such file or directoryThanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 16, 2020 at 6:19 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,On testing further, I found when taking backup with -R, pg_basebackup crashedthis crash is not consistently reproducible.[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a text);\"CREATE TABLE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test values ('parallel_backup with -R recovery-conf');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -RSegmentation fault (core dumped)stack trace looks the same as it was on earlier reported crash with tablespace.--stack trace[edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup Loaded symbols for /lib64/libnss_files.so.2Core was generated by `./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -R'.Program terminated with signal 11, Segmentation fault.#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:31753175\t\t\t\tbackupinfo->curr = fetchfile->next;Missing separate debuginfos, use: debuginfo-install keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64 libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64(gdb) bt#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:3175#1  0x0000000000408a9e in worker_run (arg=0xc1e458) at pg_basebackup.c:2715#2  0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at pthread_create.c:301#3  0x00000039212e8c4d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:115(gdb) Thanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:Hi Asif, Thanks Rajkumar. I have fixed the above issues and have rebased the patch to the latest master (b7f64c64).(V9 of the patches are attached).I had a further review of the patches and here are my few observations: 1.+/*+ * stop_backup() - ends an online backup+ *+ * The function is called at the end of an online backup. It sends out pg_control+ * file, optionally WAL segments and ending WAL location.+ */Comments seem out-dated.2. With parallel jobs, maxrate is now not supported. Since we are now askingdata in multiple threads throttling seems important here. Can you pleaseexplain why have you disabled that?3. As we are always fetching a single file and as Robert suggested, let renameSEND_FILES to SEND_FILE instead.4. Does this work on Windows? I mean does pthread_create() work on Windows?I asked this as I see that pgbench has its own implementation forpthread_create() for WIN32 but this patch doesn't.5. Typos:tablspace => tablespacesafly => safely6. parallel_backup_run() needs some comments explaining the states it goesthrough PB_* states.7. +            case PB_FETCH_REL_FILES:    /* fetch files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_STOP_BACKUP;+                    free_filelist(backupinfo);+                }+                break;+            case PB_FETCH_WAL_FILES:    /* fetch WAL files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_BACKUP_COMPLETE;+                }+                break;Why free_filelist() is not called in PB_FETCH_WAL_FILES case?Thanks-- Jeevan ChalkeAssociate Database Architect & Team Lead, Product DevelopmentEnterpriseDB CorporationThe Enterprise PostgreSQL CompanyPhone: +91 20 66449694Website: www.enterprisedb.comEnterpriseDB Blog: http://blogs.enterprisedb.com/Follow us on Twitter: http://www.twitter.com/enterprisedbThis e-mail message (and any attachment) is intended for the use of the individual or entity to whom it is addressed. This message contains information from EnterpriseDB Corporation that may be privileged, confidential, or exempt from disclosure under applicable law. If you are not the intended recipient or authorized to receive this for the intended recipient, any use, dissemination, distribution, retention, archiving, or copying of this communication is strictly prohibited. If you have received this e-mail in error, please notify the sender immediately by reply e-mail and delete this message.", "msg_date": "Wed, 25 Mar 2020 12:52:11 +0530", "msg_from": "Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, Mar 25, 2020 at 12:22 PM Rajkumar Raghuwanshi <\nrajkumar.raghuwanshi@enterprisedb.com> wrote:\n\n> Hi Asif,\n>\n> While testing further I observed parallel backup is not able to take\n> backup of standby server.\n>\n> mkdir /tmp/archive_dir\n> echo \"archive_mode='on'\">> data/postgresql.conf\n> echo \"archive_command='cp %p /tmp/archive_dir/%f'\">> data/postgresql.conf\n>\n> ./pg_ctl -D data -l logs start\n> ./pg_basebackup -p 5432 -Fp -R -D /tmp/slave\n>\n> echo \"primary_conninfo='host=127.0.0.1 port=5432 user=edb'\">>\n> /tmp/slave/postgresql.conf\n> echo \"restore_command='cp /tmp/archive_dir/%f %p'\">>\n> /tmp/slave/postgresql.conf\n> echo \"promote_trigger_file='/tmp/failover.log'\">>\n> /tmp/slave/postgresql.conf\n>\n> ./pg_ctl -D /tmp/slave -l /tmp/slave_logs -o \"-p 5433\" start -c\n>\n> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"select\n> pg_is_in_recovery();\"\n> pg_is_in_recovery\n> -------------------\n> f\n> (1 row)\n>\n> [edb@localhost bin]$ ./psql postgres -p 5433 -c \"select\n> pg_is_in_recovery();\"\n> pg_is_in_recovery\n> -------------------\n> t\n> (1 row)\n>\n>\n>\n>\n> *[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs\n> 6pg_basebackup: error: could not list backup files: ERROR: the standby was\n> promoted during online backupHINT: This means that the backup being taken\n> is corrupt and should not be used. Try taking another online\n> backup.pg_basebackup: removing data directory \"/tmp/bkp_s\"*\n>\n> #same is working fine without parallel backup\n> [edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 1\n> [edb@localhost bin]$ ls /tmp/bkp_s/PG_VERSION\n> /tmp/bkp_s/PG_VERSION\n>\n> Thanks & Regards,\n> Rajkumar Raghuwanshi\n>\n>\n> On Thu, Mar 19, 2020 at 4:11 PM Rajkumar Raghuwanshi <\n> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>\n>> Hi Asif,\n>>\n>> In another scenarios, bkp data is corrupted for tablespace. again this is\n>> not reproducible everytime,\n>> but If I am running the same set of commands I am getting the same error.\n>>\n>> [edb@localhost bin]$ ./pg_ctl -D data -l logfile start\n>> waiting for server to start.... done\n>> server started\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ mkdir /tmp/tblsp\n>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace tblsp\n>> location '/tmp/tblsp';\"\n>> CREATE TABLESPACE\n>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create database testdb\n>> tablespace tblsp;\"\n>> CREATE DATABASE\n>> [edb@localhost bin]$ ./psql testdb -p 5432 -c \"create table testtbl (a\n>> text);\"\n>> CREATE TABLE\n>> [edb@localhost bin]$ ./psql testdb -p 5432 -c \"insert into testtbl\n>> values ('parallel_backup with tablespace');\"\n>> INSERT 0 1\n>> [edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp -T\n>> /tmp/tblsp=/tmp/tblsp_bkp --jobs 2\n>> [edb@localhost bin]$ ./pg_ctl -D /tmp/bkp -l /tmp/bkp_logs -o \"-p 5555\"\n>> start\n>> waiting for server to start.... done\n>> server started\n>> [edb@localhost bin]$ ./psql postgres -p 5555 -c \"select * from\n>> pg_tablespace where spcname like 'tblsp%' or spcname = 'pg_default'\";\n>> oid | spcname | spcowner | spcacl | spcoptions\n>> -------+------------+----------+--------+------------\n>> 1663 | pg_default | 10 | |\n>> 16384 | tblsp | 10 | |\n>> (2 rows)\n>>\n>> [edb@localhost bin]$ ./psql testdb -p 5555 -c \"select * from testtbl\";\n>> psql: error: could not connect to server: FATAL:\n>> \"pg_tblspc/16384/PG_13_202003051/16385\" is not a valid data directory\n>> DETAIL: File \"pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\" is\n>> missing.\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ ls\n>> data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>> data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>> [edb@localhost bin]$ ls\n>> /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>> ls: cannot access\n>> /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION: No such file or\n>> directory\n>>\n>>\n>> Thanks & Regards,\n>> Rajkumar Raghuwanshi\n>>\n>>\n>> On Mon, Mar 16, 2020 at 6:19 PM Rajkumar Raghuwanshi <\n>> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>>\n>>> Hi Asif,\n>>>\n>>> On testing further, I found when taking backup with -R, pg_basebackup\n>>> crashed\n>>> this crash is not consistently reproducible.\n>>>\n>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a\n>>> text);\"\n>>> CREATE TABLE\n>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test\n>>> values ('parallel_backup with -R recovery-conf');\"\n>>> INSERT 0 1\n>>> [edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp\n>>> -R\n>>> Segmentation fault (core dumped)\n>>>\n>>> stack trace looks the same as it was on earlier reported crash with\n>>> tablespace.\n>>> --stack trace\n>>> [edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup\n>>> Loaded symbols for /lib64/libnss_files.so.2\n>>> Core was generated by `./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp\n>>> -R'.\n>>> Program terminated with signal 11, Segmentation fault.\n>>> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n>>> pg_basebackup.c:3175\n>>> 3175 backupinfo->curr = fetchfile->next;\n>>> Missing separate debuginfos, use: debuginfo-install\n>>> keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\n>>> libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\n>>> openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n>>> (gdb) bt\n>>> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n>>> pg_basebackup.c:3175\n>>> #1 0x0000000000408a9e in worker_run (arg=0xc1e458) at\n>>> pg_basebackup.c:2715\n>>> #2 0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at\n>>> pthread_create.c:301\n>>> #3 0x00000039212e8c4d in clone () at\n>>> ../sysdeps/unix/sysv/linux/x86_64/clone.S:115\n>>> (gdb)\n>>>\n>>> Thanks & Regards,\n>>> Rajkumar Raghuwanshi\n>>>\n>>>\n>>> On Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <\n>>> jeevan.chalke@enterprisedb.com> wrote:\n>>>\n>>>> Hi Asif,\n>>>>\n>>>>\n>>>>> Thanks Rajkumar. I have fixed the above issues and have rebased the\n>>>>> patch to the latest master (b7f64c64).\n>>>>> (V9 of the patches are attached).\n>>>>>\n>>>>\n>>>> I had a further review of the patches and here are my few observations:\n>>>>\n>>>> 1.\n>>>> +/*\n>>>> + * stop_backup() - ends an online backup\n>>>> + *\n>>>> + * The function is called at the end of an online backup. It sends out\n>>>> pg_control\n>>>> + * file, optionally WAL segments and ending WAL location.\n>>>> + */\n>>>>\n>>>> Comments seem out-dated.\n>>>>\n>>>\nFixed.\n\n\n>\n>>>> 2. With parallel jobs, maxrate is now not supported. Since we are now\n>>>> asking\n>>>> data in multiple threads throttling seems important here. Can you please\n>>>> explain why have you disabled that?\n>>>>\n>>>> 3. As we are always fetching a single file and as Robert suggested, let\n>>>> rename\n>>>> SEND_FILES to SEND_FILE instead.\n>>>>\n>>>\nYes, we are fetching a single file. However, SEND_FILES is still capable of\nfetching multiple files in one\ngo, that's why the name.\n\n\n>>>> 4. Does this work on Windows? I mean does pthread_create() work on\n>>>> Windows?\n>>>> I asked this as I see that pgbench has its own implementation for\n>>>> pthread_create() for WIN32 but this patch doesn't.\n>>>>\n>>>\npatch is updated to add support for the Windows platform.\n\n\n>>>> 5. Typos:\n>>>> tablspace => tablespace\n>>>> safly => safely\n>>>>\n>>>> Done.\n\n\n> 6. parallel_backup_run() needs some comments explaining the states it goes\n>>>> through PB_* states.\n>>>>\n>>>> 7.\n>>>> + case PB_FETCH_REL_FILES: /* fetch files from server */\n>>>> + if (backupinfo->activeworkers == 0)\n>>>> + {\n>>>> + backupinfo->backupstate = PB_STOP_BACKUP;\n>>>> + free_filelist(backupinfo);\n>>>> + }\n>>>> + break;\n>>>> + case PB_FETCH_WAL_FILES: /* fetch WAL files from server\n>>>> */\n>>>> + if (backupinfo->activeworkers == 0)\n>>>> + {\n>>>> + backupinfo->backupstate = PB_BACKUP_COMPLETE;\n>>>> + }\n>>>> + break;\n>>>>\n>>> Done.\n\n\n>\n>>>> Why free_filelist() is not called in PB_FETCH_WAL_FILES case?\n>>>>\n>>> Done.\n\nThe corrupted tablespace and crash, reported by Rajkumar, have been fixed.\nA pointer\nvariable remained uninitialized which in turn caused the system to\nmisbehave.\n\nAttached is the updated set of patches. AFAIK, to complete parallel backup\nfeature\nset, there remain three sub-features:\n\n1- parallel backup does not work with a standby server. In parallel backup,\nthe server\nspawns multiple processes and there is no shared state being maintained. So\ncurrently,\nno way to tell multiple processes if the standby was promoted during the\nbackup since\nthe START_BACKUP was called.\n\n2- throttling. Robert previously suggested that we implement throttling on\nthe client-side.\nHowever, I found a previous discussion where it was advocated to be added\nto the\nbackend instead[1].\n\nSo, it was better to have a consensus before moving the throttle function\nto the client.\nThat’s why for the time being I have disabled it and have asked for\nsuggestions on it\nto move forward.\n\nIt seems to me that we have to maintain a shared state in order to support\ntaking backup\nfrom standby. Also, there is a new feature recently committed for backup\nprogress\nreporting in the backend (pg_stat_progress_basebackup). This functionality\nwas recently\nadded via this commit ID: e65497df. For parallel backup to update these\nstats, a shared\nstate will be required.\n\nSince multiple pg_basebackup can be running at the same time, maintaining a\nshared state\ncan become a little complex, unless we disallow taking multiple parallel\nbackups.\n\nSo proceeding on with this patch, I will be working on:\n- throttling to be implemented on the client-side.\n- adding a shared state to handle backup from the standby.\n\n\n\n[1]\nhttps://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Fri, 27 Mar 2020 22:33:28 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Thanks Asif,\n\nI have re-verified reported issue. expect standby backup, others are fixed.\n\nThanks & Regards,\nRajkumar Raghuwanshi\n\n\nOn Fri, Mar 27, 2020 at 11:04 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Wed, Mar 25, 2020 at 12:22 PM Rajkumar Raghuwanshi <\n> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>\n>> Hi Asif,\n>>\n>> While testing further I observed parallel backup is not able to take\n>> backup of standby server.\n>>\n>> mkdir /tmp/archive_dir\n>> echo \"archive_mode='on'\">> data/postgresql.conf\n>> echo \"archive_command='cp %p /tmp/archive_dir/%f'\">> data/postgresql.conf\n>>\n>> ./pg_ctl -D data -l logs start\n>> ./pg_basebackup -p 5432 -Fp -R -D /tmp/slave\n>>\n>> echo \"primary_conninfo='host=127.0.0.1 port=5432 user=edb'\">>\n>> /tmp/slave/postgresql.conf\n>> echo \"restore_command='cp /tmp/archive_dir/%f %p'\">>\n>> /tmp/slave/postgresql.conf\n>> echo \"promote_trigger_file='/tmp/failover.log'\">>\n>> /tmp/slave/postgresql.conf\n>>\n>> ./pg_ctl -D /tmp/slave -l /tmp/slave_logs -o \"-p 5433\" start -c\n>>\n>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"select\n>> pg_is_in_recovery();\"\n>> pg_is_in_recovery\n>> -------------------\n>> f\n>> (1 row)\n>>\n>> [edb@localhost bin]$ ./psql postgres -p 5433 -c \"select\n>> pg_is_in_recovery();\"\n>> pg_is_in_recovery\n>> -------------------\n>> t\n>> (1 row)\n>>\n>>\n>>\n>>\n>> *[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs\n>> 6pg_basebackup: error: could not list backup files: ERROR: the standby was\n>> promoted during online backupHINT: This means that the backup being taken\n>> is corrupt and should not be used. Try taking another online\n>> backup.pg_basebackup: removing data directory \"/tmp/bkp_s\"*\n>>\n>> #same is working fine without parallel backup\n>> [edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 1\n>> [edb@localhost bin]$ ls /tmp/bkp_s/PG_VERSION\n>> /tmp/bkp_s/PG_VERSION\n>>\n>> Thanks & Regards,\n>> Rajkumar Raghuwanshi\n>>\n>>\n>> On Thu, Mar 19, 2020 at 4:11 PM Rajkumar Raghuwanshi <\n>> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>>\n>>> Hi Asif,\n>>>\n>>> In another scenarios, bkp data is corrupted for tablespace. again this\n>>> is not reproducible everytime,\n>>> but If I am running the same set of commands I am getting the same error.\n>>>\n>>> [edb@localhost bin]$ ./pg_ctl -D data -l logfile start\n>>> waiting for server to start.... done\n>>> server started\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$ mkdir /tmp/tblsp\n>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace\n>>> tblsp location '/tmp/tblsp';\"\n>>> CREATE TABLESPACE\n>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create database testdb\n>>> tablespace tblsp;\"\n>>> CREATE DATABASE\n>>> [edb@localhost bin]$ ./psql testdb -p 5432 -c \"create table testtbl (a\n>>> text);\"\n>>> CREATE TABLE\n>>> [edb@localhost bin]$ ./psql testdb -p 5432 -c \"insert into testtbl\n>>> values ('parallel_backup with tablespace');\"\n>>> INSERT 0 1\n>>> [edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp -T\n>>> /tmp/tblsp=/tmp/tblsp_bkp --jobs 2\n>>> [edb@localhost bin]$ ./pg_ctl -D /tmp/bkp -l /tmp/bkp_logs -o \"-p 5555\"\n>>> start\n>>> waiting for server to start.... done\n>>> server started\n>>> [edb@localhost bin]$ ./psql postgres -p 5555 -c \"select * from\n>>> pg_tablespace where spcname like 'tblsp%' or spcname = 'pg_default'\";\n>>> oid | spcname | spcowner | spcacl | spcoptions\n>>> -------+------------+----------+--------+------------\n>>> 1663 | pg_default | 10 | |\n>>> 16384 | tblsp | 10 | |\n>>> (2 rows)\n>>>\n>>> [edb@localhost bin]$ ./psql testdb -p 5555 -c \"select * from testtbl\";\n>>> psql: error: could not connect to server: FATAL:\n>>> \"pg_tblspc/16384/PG_13_202003051/16385\" is not a valid data directory\n>>> DETAIL: File \"pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\" is\n>>> missing.\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$ ls\n>>> data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>>> data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>>> [edb@localhost bin]$ ls\n>>> /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>>> ls: cannot access\n>>> /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION: No such file or\n>>> directory\n>>>\n>>>\n>>> Thanks & Regards,\n>>> Rajkumar Raghuwanshi\n>>>\n>>>\n>>> On Mon, Mar 16, 2020 at 6:19 PM Rajkumar Raghuwanshi <\n>>> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>>>\n>>>> Hi Asif,\n>>>>\n>>>> On testing further, I found when taking backup with -R, pg_basebackup\n>>>> crashed\n>>>> this crash is not consistently reproducible.\n>>>>\n>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a\n>>>> text);\"\n>>>> CREATE TABLE\n>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test\n>>>> values ('parallel_backup with -R recovery-conf');\"\n>>>> INSERT 0 1\n>>>> [edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp\n>>>> -R\n>>>> Segmentation fault (core dumped)\n>>>>\n>>>> stack trace looks the same as it was on earlier reported crash with\n>>>> tablespace.\n>>>> --stack trace\n>>>> [edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup\n>>>> Loaded symbols for /lib64/libnss_files.so.2\n>>>> Core was generated by `./pg_basebackup -p 5432 -j 2 -D\n>>>> /tmp/test_bkp/bkp -R'.\n>>>> Program terminated with signal 11, Segmentation fault.\n>>>> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n>>>> pg_basebackup.c:3175\n>>>> 3175 backupinfo->curr = fetchfile->next;\n>>>> Missing separate debuginfos, use: debuginfo-install\n>>>> keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\n>>>> libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\n>>>> openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n>>>> (gdb) bt\n>>>> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n>>>> pg_basebackup.c:3175\n>>>> #1 0x0000000000408a9e in worker_run (arg=0xc1e458) at\n>>>> pg_basebackup.c:2715\n>>>> #2 0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at\n>>>> pthread_create.c:301\n>>>> #3 0x00000039212e8c4d in clone () at\n>>>> ../sysdeps/unix/sysv/linux/x86_64/clone.S:115\n>>>> (gdb)\n>>>>\n>>>> Thanks & Regards,\n>>>> Rajkumar Raghuwanshi\n>>>>\n>>>>\n>>>> On Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <\n>>>> jeevan.chalke@enterprisedb.com> wrote:\n>>>>\n>>>>> Hi Asif,\n>>>>>\n>>>>>\n>>>>>> Thanks Rajkumar. I have fixed the above issues and have rebased the\n>>>>>> patch to the latest master (b7f64c64).\n>>>>>> (V9 of the patches are attached).\n>>>>>>\n>>>>>\n>>>>> I had a further review of the patches and here are my few observations:\n>>>>>\n>>>>> 1.\n>>>>> +/*\n>>>>> + * stop_backup() - ends an online backup\n>>>>> + *\n>>>>> + * The function is called at the end of an online backup. It sends\n>>>>> out pg_control\n>>>>> + * file, optionally WAL segments and ending WAL location.\n>>>>> + */\n>>>>>\n>>>>> Comments seem out-dated.\n>>>>>\n>>>>\n> Fixed.\n>\n>\n>>\n>>>>> 2. With parallel jobs, maxrate is now not supported. Since we are now\n>>>>> asking\n>>>>> data in multiple threads throttling seems important here. Can you\n>>>>> please\n>>>>> explain why have you disabled that?\n>>>>>\n>>>>> 3. As we are always fetching a single file and as Robert suggested,\n>>>>> let rename\n>>>>> SEND_FILES to SEND_FILE instead.\n>>>>>\n>>>>\n> Yes, we are fetching a single file. However, SEND_FILES is still capable\n> of fetching multiple files in one\n> go, that's why the name.\n>\n>\n>>>>> 4. Does this work on Windows? I mean does pthread_create() work on\n>>>>> Windows?\n>>>>> I asked this as I see that pgbench has its own implementation for\n>>>>> pthread_create() for WIN32 but this patch doesn't.\n>>>>>\n>>>>\n> patch is updated to add support for the Windows platform.\n>\n>\n>>>>> 5. Typos:\n>>>>> tablspace => tablespace\n>>>>> safly => safely\n>>>>>\n>>>>> Done.\n>\n>\n>> 6. parallel_backup_run() needs some comments explaining the states it goes\n>>>>> through PB_* states.\n>>>>>\n>>>>> 7.\n>>>>> + case PB_FETCH_REL_FILES: /* fetch files from server */\n>>>>> + if (backupinfo->activeworkers == 0)\n>>>>> + {\n>>>>> + backupinfo->backupstate = PB_STOP_BACKUP;\n>>>>> + free_filelist(backupinfo);\n>>>>> + }\n>>>>> + break;\n>>>>> + case PB_FETCH_WAL_FILES: /* fetch WAL files from\n>>>>> server */\n>>>>> + if (backupinfo->activeworkers == 0)\n>>>>> + {\n>>>>> + backupinfo->backupstate = PB_BACKUP_COMPLETE;\n>>>>> + }\n>>>>> + break;\n>>>>>\n>>>> Done.\n>\n>\n>>\n>>>>> Why free_filelist() is not called in PB_FETCH_WAL_FILES case?\n>>>>>\n>>>> Done.\n>\n> The corrupted tablespace and crash, reported by Rajkumar, have been fixed.\n> A pointer\n> variable remained uninitialized which in turn caused the system to\n> misbehave.\n>\n> Attached is the updated set of patches. AFAIK, to complete parallel backup\n> feature\n> set, there remain three sub-features:\n>\n> 1- parallel backup does not work with a standby server. In parallel\n> backup, the server\n> spawns multiple processes and there is no shared state being maintained.\n> So currently,\n> no way to tell multiple processes if the standby was promoted during the\n> backup since\n> the START_BACKUP was called.\n>\n> 2- throttling. Robert previously suggested that we implement throttling on\n> the client-side.\n> However, I found a previous discussion where it was advocated to be added\n> to the\n> backend instead[1].\n>\n> So, it was better to have a consensus before moving the throttle function\n> to the client.\n> That’s why for the time being I have disabled it and have asked for\n> suggestions on it\n> to move forward.\n>\n> It seems to me that we have to maintain a shared state in order to support\n> taking backup\n> from standby. Also, there is a new feature recently committed for backup\n> progress\n> reporting in the backend (pg_stat_progress_basebackup). This functionality\n> was recently\n> added via this commit ID: e65497df. For parallel backup to update these\n> stats, a shared\n> state will be required.\n>\n> Since multiple pg_basebackup can be running at the same time, maintaining\n> a shared state\n> can become a little complex, unless we disallow taking multiple parallel\n> backups.\n>\n> So proceeding on with this patch, I will be working on:\n> - throttling to be implemented on the client-side.\n> - adding a shared state to handle backup from the standby.\n>\n>\n>\n> [1]\n> https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af\n>\n>\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\nThanks Asif,I have re-verified reported issue. expect standby backup, others are fixed.Thanks & Regards,Rajkumar RaghuwanshiOn Fri, Mar 27, 2020 at 11:04 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Wed, Mar 25, 2020 at 12:22 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,While testing further I observed parallel backup is not able to take backup of standby server.mkdir /tmp/archive_direcho \"archive_mode='on'\">> data/postgresql.confecho \"archive_command='cp %p /tmp/archive_dir/%f'\">> data/postgresql.conf./pg_ctl -D data -l logs start./pg_basebackup -p 5432 -Fp -R -D /tmp/slaveecho \"primary_conninfo='host=127.0.0.1 port=5432 user=edb'\">> /tmp/slave/postgresql.confecho \"restore_command='cp /tmp/archive_dir/%f %p'\">> /tmp/slave/postgresql.confecho \"promote_trigger_file='/tmp/failover.log'\">> /tmp/slave/postgresql.conf./pg_ctl -D /tmp/slave -l /tmp/slave_logs -o \"-p 5433\" start -c [edb@localhost bin]$ ./psql postgres -p 5432 -c \"select pg_is_in_recovery();\" pg_is_in_recovery ------------------- f(1 row)[edb@localhost bin]$ ./psql postgres -p 5433 -c \"select pg_is_in_recovery();\" pg_is_in_recovery ------------------- t(1 row)[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 6pg_basebackup: error: could not list backup files: ERROR:  the standby was promoted during online backupHINT:  This means that the backup being taken is corrupt and should not be used. Try taking another online backup.pg_basebackup: removing data directory \"/tmp/bkp_s\"#same is working fine without parallel backup[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 1[edb@localhost bin]$ ls /tmp/bkp_s/PG_VERSION/tmp/bkp_s/PG_VERSIONThanks & Regards,Rajkumar RaghuwanshiOn Thu, Mar 19, 2020 at 4:11 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,In another scenarios, bkp data is corrupted for tablespace. again this is not reproducible everytime,but If I am running the same set of commands I am getting the same error.[edb@localhost bin]$ ./pg_ctl -D data -l logfile startwaiting for server to start.... doneserver started[edb@localhost bin]$ [edb@localhost bin]$ mkdir /tmp/tblsp[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace tblsp location '/tmp/tblsp';\"CREATE TABLESPACE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create database testdb tablespace tblsp;\"CREATE DATABASE[edb@localhost bin]$ ./psql testdb -p 5432 -c \"create table testtbl (a text);\"CREATE TABLE[edb@localhost bin]$ ./psql testdb -p 5432 -c \"insert into testtbl values ('parallel_backup with tablespace');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp -T /tmp/tblsp=/tmp/tblsp_bkp --jobs 2 [edb@localhost bin]$ ./pg_ctl -D /tmp/bkp -l /tmp/bkp_logs -o \"-p 5555\" startwaiting for server to start.... doneserver started[edb@localhost bin]$ ./psql postgres -p 5555 -c \"select * from pg_tablespace where spcname like 'tblsp%' or spcname = 'pg_default'\";  oid  |  spcname   | spcowner | spcacl | spcoptions -------+------------+----------+--------+------------  1663 | pg_default |       10 |        |  16384 | tblsp      |       10 |        | (2 rows)[edb@localhost bin]$ ./psql testdb -p 5555 -c \"select * from testtbl\";psql: error: could not connect to server: FATAL:  \"pg_tblspc/16384/PG_13_202003051/16385\" is not a valid data directoryDETAIL:  File \"pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\" is missing.[edb@localhost bin]$ [edb@localhost bin]$ ls data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSIONdata/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION[edb@localhost bin]$ ls /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSIONls: cannot access /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION: No such file or directoryThanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 16, 2020 at 6:19 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,On testing further, I found when taking backup with -R, pg_basebackup crashedthis crash is not consistently reproducible.[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a text);\"CREATE TABLE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test values ('parallel_backup with -R recovery-conf');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -RSegmentation fault (core dumped)stack trace looks the same as it was on earlier reported crash with tablespace.--stack trace[edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup Loaded symbols for /lib64/libnss_files.so.2Core was generated by `./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -R'.Program terminated with signal 11, Segmentation fault.#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:31753175\t\t\t\tbackupinfo->curr = fetchfile->next;Missing separate debuginfos, use: debuginfo-install keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64 libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64(gdb) bt#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:3175#1  0x0000000000408a9e in worker_run (arg=0xc1e458) at pg_basebackup.c:2715#2  0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at pthread_create.c:301#3  0x00000039212e8c4d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:115(gdb) Thanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:Hi Asif, Thanks Rajkumar. I have fixed the above issues and have rebased the patch to the latest master (b7f64c64).(V9 of the patches are attached).I had a further review of the patches and here are my few observations: 1.+/*+ * stop_backup() - ends an online backup+ *+ * The function is called at the end of an online backup. It sends out pg_control+ * file, optionally WAL segments and ending WAL location.+ */Comments seem out-dated.Fixed. 2. With parallel jobs, maxrate is now not supported. Since we are now askingdata in multiple threads throttling seems important here. Can you pleaseexplain why have you disabled that?3. As we are always fetching a single file and as Robert suggested, let renameSEND_FILES to SEND_FILE instead.Yes, we are fetching a single file. However, SEND_FILES is still capable of fetching multiple files in onego, that's why the name.4. Does this work on Windows? I mean does pthread_create() work on Windows?I asked this as I see that pgbench has its own implementation forpthread_create() for WIN32 but this patch doesn't.patch is updated to add support for the Windows platform.5. Typos:tablspace => tablespacesafly => safelyDone. 6. parallel_backup_run() needs some comments explaining the states it goesthrough PB_* states.7. +            case PB_FETCH_REL_FILES:    /* fetch files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_STOP_BACKUP;+                    free_filelist(backupinfo);+                }+                break;+            case PB_FETCH_WAL_FILES:    /* fetch WAL files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_BACKUP_COMPLETE;+                }+                break;Done. Why free_filelist() is not called in PB_FETCH_WAL_FILES case?Done.The corrupted tablespace and crash, reported by Rajkumar, have been fixed. A pointervariable remained uninitialized which in turn caused the system to misbehave.Attached is the updated set of patches. AFAIK, to complete parallel backup featureset, there remain three sub-features:1- parallel backup does not work with a standby server. In parallel backup, the serverspawns multiple processes and there is no shared state being maintained. So currently,no way to tell multiple processes if the standby was promoted during the backup sincethe START_BACKUP was called.2- throttling. Robert previously suggested that we implement throttling on the client-side.However, I found a previous discussion where it was advocated to be added to thebackend instead[1].So, it was better to have a consensus before moving the throttle function to the client.That’s why for the time being I have disabled it and have asked for suggestions on itto move forward.It seems to me that we have to maintain a shared state in order to support taking backupfrom standby. Also, there is a new feature recently committed for backup progressreporting in the backend (pg_stat_progress_basebackup). This functionality was recentlyadded via this commit ID: e65497df. For parallel backup to update these stats, a sharedstate will be required.Since multiple pg_basebackup can be running at the same time, maintaining a shared statecan become a little complex, unless we disallow taking multiple parallel backups.So proceeding on with this patch, I will be working on:- throttling to be implemented on the client-side.- adding a shared state to handle backup from the standby.[1] https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Mon, 30 Mar 2020 16:13:47 +0530", "msg_from": "Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Mar 30, 2020 at 3:44 PM Rajkumar Raghuwanshi <\nrajkumar.raghuwanshi@enterprisedb.com> wrote:\n\n> Thanks Asif,\n>\n> I have re-verified reported issue. expect standby backup, others are fixed.\n>\n\nYes As Asif mentioned he is working on the standby issue and adding\nbandwidth throttling functionality to parallel backup.\n\nIt would be good to get some feedback on Asif previous email from Robert on\nthe design considerations for stand-by server support and throttling. I\nbelieve all the other points mentioned by Robert in this thread are\naddressed by Asif so it would be good to hear about any other concerns that\nare not addressed.\n\nThanks,\n\n-- Ahsan\n\n\n> Thanks & Regards,\n> Rajkumar Raghuwanshi\n>\n>\n> On Fri, Mar 27, 2020 at 11:04 PM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n>\n>>\n>>\n>> On Wed, Mar 25, 2020 at 12:22 PM Rajkumar Raghuwanshi <\n>> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>>\n>>> Hi Asif,\n>>>\n>>> While testing further I observed parallel backup is not able to take\n>>> backup of standby server.\n>>>\n>>> mkdir /tmp/archive_dir\n>>> echo \"archive_mode='on'\">> data/postgresql.conf\n>>> echo \"archive_command='cp %p /tmp/archive_dir/%f'\">> data/postgresql.conf\n>>>\n>>> ./pg_ctl -D data -l logs start\n>>> ./pg_basebackup -p 5432 -Fp -R -D /tmp/slave\n>>>\n>>> echo \"primary_conninfo='host=127.0.0.1 port=5432 user=edb'\">>\n>>> /tmp/slave/postgresql.conf\n>>> echo \"restore_command='cp /tmp/archive_dir/%f %p'\">>\n>>> /tmp/slave/postgresql.conf\n>>> echo \"promote_trigger_file='/tmp/failover.log'\">>\n>>> /tmp/slave/postgresql.conf\n>>>\n>>> ./pg_ctl -D /tmp/slave -l /tmp/slave_logs -o \"-p 5433\" start -c\n>>>\n>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"select\n>>> pg_is_in_recovery();\"\n>>> pg_is_in_recovery\n>>> -------------------\n>>> f\n>>> (1 row)\n>>>\n>>> [edb@localhost bin]$ ./psql postgres -p 5433 -c \"select\n>>> pg_is_in_recovery();\"\n>>> pg_is_in_recovery\n>>> -------------------\n>>> t\n>>> (1 row)\n>>>\n>>>\n>>>\n>>>\n>>> *[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs\n>>> 6pg_basebackup: error: could not list backup files: ERROR: the standby was\n>>> promoted during online backupHINT: This means that the backup being taken\n>>> is corrupt and should not be used. Try taking another online\n>>> backup.pg_basebackup: removing data directory \"/tmp/bkp_s\"*\n>>>\n>>> #same is working fine without parallel backup\n>>> [edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 1\n>>> [edb@localhost bin]$ ls /tmp/bkp_s/PG_VERSION\n>>> /tmp/bkp_s/PG_VERSION\n>>>\n>>> Thanks & Regards,\n>>> Rajkumar Raghuwanshi\n>>>\n>>>\n>>> On Thu, Mar 19, 2020 at 4:11 PM Rajkumar Raghuwanshi <\n>>> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>>>\n>>>> Hi Asif,\n>>>>\n>>>> In another scenarios, bkp data is corrupted for tablespace. again this\n>>>> is not reproducible everytime,\n>>>> but If I am running the same set of commands I am getting the same\n>>>> error.\n>>>>\n>>>> [edb@localhost bin]$ ./pg_ctl -D data -l logfile start\n>>>> waiting for server to start.... done\n>>>> server started\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$ mkdir /tmp/tblsp\n>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace\n>>>> tblsp location '/tmp/tblsp';\"\n>>>> CREATE TABLESPACE\n>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create database\n>>>> testdb tablespace tblsp;\"\n>>>> CREATE DATABASE\n>>>> [edb@localhost bin]$ ./psql testdb -p 5432 -c \"create table testtbl (a\n>>>> text);\"\n>>>> CREATE TABLE\n>>>> [edb@localhost bin]$ ./psql testdb -p 5432 -c \"insert into testtbl\n>>>> values ('parallel_backup with tablespace');\"\n>>>> INSERT 0 1\n>>>> [edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp -T\n>>>> /tmp/tblsp=/tmp/tblsp_bkp --jobs 2\n>>>> [edb@localhost bin]$ ./pg_ctl -D /tmp/bkp -l /tmp/bkp_logs -o \"-p\n>>>> 5555\" start\n>>>> waiting for server to start.... done\n>>>> server started\n>>>> [edb@localhost bin]$ ./psql postgres -p 5555 -c \"select * from\n>>>> pg_tablespace where spcname like 'tblsp%' or spcname = 'pg_default'\";\n>>>> oid | spcname | spcowner | spcacl | spcoptions\n>>>> -------+------------+----------+--------+------------\n>>>> 1663 | pg_default | 10 | |\n>>>> 16384 | tblsp | 10 | |\n>>>> (2 rows)\n>>>>\n>>>> [edb@localhost bin]$ ./psql testdb -p 5555 -c \"select * from testtbl\";\n>>>> psql: error: could not connect to server: FATAL:\n>>>> \"pg_tblspc/16384/PG_13_202003051/16385\" is not a valid data directory\n>>>> DETAIL: File \"pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\" is\n>>>> missing.\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$ ls\n>>>> data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>>>> data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>>>> [edb@localhost bin]$ ls\n>>>> /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>>>> ls: cannot access\n>>>> /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION: No such file or\n>>>> directory\n>>>>\n>>>>\n>>>> Thanks & Regards,\n>>>> Rajkumar Raghuwanshi\n>>>>\n>>>>\n>>>> On Mon, Mar 16, 2020 at 6:19 PM Rajkumar Raghuwanshi <\n>>>> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>>>>\n>>>>> Hi Asif,\n>>>>>\n>>>>> On testing further, I found when taking backup with -R, pg_basebackup\n>>>>> crashed\n>>>>> this crash is not consistently reproducible.\n>>>>>\n>>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a\n>>>>> text);\"\n>>>>> CREATE TABLE\n>>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test\n>>>>> values ('parallel_backup with -R recovery-conf');\"\n>>>>> INSERT 0 1\n>>>>> [edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D\n>>>>> /tmp/test_bkp/bkp -R\n>>>>> Segmentation fault (core dumped)\n>>>>>\n>>>>> stack trace looks the same as it was on earlier reported crash with\n>>>>> tablespace.\n>>>>> --stack trace\n>>>>> [edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup\n>>>>> Loaded symbols for /lib64/libnss_files.so.2\n>>>>> Core was generated by `./pg_basebackup -p 5432 -j 2 -D\n>>>>> /tmp/test_bkp/bkp -R'.\n>>>>> Program terminated with signal 11, Segmentation fault.\n>>>>> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n>>>>> pg_basebackup.c:3175\n>>>>> 3175 backupinfo->curr = fetchfile->next;\n>>>>> Missing separate debuginfos, use: debuginfo-install\n>>>>> keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\n>>>>> libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\n>>>>> openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n>>>>> (gdb) bt\n>>>>> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n>>>>> pg_basebackup.c:3175\n>>>>> #1 0x0000000000408a9e in worker_run (arg=0xc1e458) at\n>>>>> pg_basebackup.c:2715\n>>>>> #2 0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at\n>>>>> pthread_create.c:301\n>>>>> #3 0x00000039212e8c4d in clone () at\n>>>>> ../sysdeps/unix/sysv/linux/x86_64/clone.S:115\n>>>>> (gdb)\n>>>>>\n>>>>> Thanks & Regards,\n>>>>> Rajkumar Raghuwanshi\n>>>>>\n>>>>>\n>>>>> On Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <\n>>>>> jeevan.chalke@enterprisedb.com> wrote:\n>>>>>\n>>>>>> Hi Asif,\n>>>>>>\n>>>>>>\n>>>>>>> Thanks Rajkumar. I have fixed the above issues and have rebased the\n>>>>>>> patch to the latest master (b7f64c64).\n>>>>>>> (V9 of the patches are attached).\n>>>>>>>\n>>>>>>\n>>>>>> I had a further review of the patches and here are my few\n>>>>>> observations:\n>>>>>>\n>>>>>> 1.\n>>>>>> +/*\n>>>>>> + * stop_backup() - ends an online backup\n>>>>>> + *\n>>>>>> + * The function is called at the end of an online backup. It sends\n>>>>>> out pg_control\n>>>>>> + * file, optionally WAL segments and ending WAL location.\n>>>>>> + */\n>>>>>>\n>>>>>> Comments seem out-dated.\n>>>>>>\n>>>>>\n>> Fixed.\n>>\n>>\n>>>\n>>>>>> 2. With parallel jobs, maxrate is now not supported. Since we are now\n>>>>>> asking\n>>>>>> data in multiple threads throttling seems important here. Can you\n>>>>>> please\n>>>>>> explain why have you disabled that?\n>>>>>>\n>>>>>> 3. As we are always fetching a single file and as Robert suggested,\n>>>>>> let rename\n>>>>>> SEND_FILES to SEND_FILE instead.\n>>>>>>\n>>>>>\n>> Yes, we are fetching a single file. However, SEND_FILES is still capable\n>> of fetching multiple files in one\n>> go, that's why the name.\n>>\n>>\n>>>>>> 4. Does this work on Windows? I mean does pthread_create() work on\n>>>>>> Windows?\n>>>>>> I asked this as I see that pgbench has its own implementation for\n>>>>>> pthread_create() for WIN32 but this patch doesn't.\n>>>>>>\n>>>>>\n>> patch is updated to add support for the Windows platform.\n>>\n>>\n>>>>>> 5. Typos:\n>>>>>> tablspace => tablespace\n>>>>>> safly => safely\n>>>>>>\n>>>>>> Done.\n>>\n>>\n>>> 6. parallel_backup_run() needs some comments explaining the states it\n>>>>>> goes\n>>>>>> through PB_* states.\n>>>>>>\n>>>>>> 7.\n>>>>>> + case PB_FETCH_REL_FILES: /* fetch files from server */\n>>>>>> + if (backupinfo->activeworkers == 0)\n>>>>>> + {\n>>>>>> + backupinfo->backupstate = PB_STOP_BACKUP;\n>>>>>> + free_filelist(backupinfo);\n>>>>>> + }\n>>>>>> + break;\n>>>>>> + case PB_FETCH_WAL_FILES: /* fetch WAL files from\n>>>>>> server */\n>>>>>> + if (backupinfo->activeworkers == 0)\n>>>>>> + {\n>>>>>> + backupinfo->backupstate = PB_BACKUP_COMPLETE;\n>>>>>> + }\n>>>>>> + break;\n>>>>>>\n>>>>> Done.\n>>\n>>\n>>>\n>>>>>> Why free_filelist() is not called in PB_FETCH_WAL_FILES case?\n>>>>>>\n>>>>> Done.\n>>\n>> The corrupted tablespace and crash, reported by Rajkumar, have been\n>> fixed. A pointer\n>> variable remained uninitialized which in turn caused the system to\n>> misbehave.\n>>\n>> Attached is the updated set of patches. AFAIK, to complete parallel\n>> backup feature\n>> set, there remain three sub-features:\n>>\n>> 1- parallel backup does not work with a standby server. In parallel\n>> backup, the server\n>> spawns multiple processes and there is no shared state being maintained.\n>> So currently,\n>> no way to tell multiple processes if the standby was promoted during the\n>> backup since\n>> the START_BACKUP was called.\n>>\n>> 2- throttling. Robert previously suggested that we implement\n>> throttling on the client-side.\n>> However, I found a previous discussion where it was advocated to be added\n>> to the\n>> backend instead[1].\n>>\n>> So, it was better to have a consensus before moving the throttle function\n>> to the client.\n>> That’s why for the time being I have disabled it and have asked for\n>> suggestions on it\n>> to move forward.\n>>\n>> It seems to me that we have to maintain a shared state in order to\n>> support taking backup\n>> from standby. Also, there is a new feature recently committed for backup\n>> progress\n>> reporting in the backend (pg_stat_progress_basebackup). This\n>> functionality was recently\n>> added via this commit ID: e65497df. For parallel backup to update these\n>> stats, a shared\n>> state will be required.\n>>\n>> Since multiple pg_basebackup can be running at the same time, maintaining\n>> a shared state\n>> can become a little complex, unless we disallow taking multiple parallel\n>> backups.\n>>\n>> So proceeding on with this patch, I will be working on:\n>> - throttling to be implemented on the client-side.\n>> - adding a shared state to handle backup from the standby.\n>>\n>>\n>>\n>> [1]\n>> https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af\n>>\n>>\n>> --\n>> Asif Rehman\n>> Highgo Software (Canada/China/Pakistan)\n>> URL : www.highgo.ca\n>>\n>>\n\n-- \nHighgo Software (Canada/China/Pakistan)\nURL : http://www.highgo.ca\nADDR: 10318 WHALLEY BLVD, Surrey, BC\nEMAIL: mailto: ahsan.hadi@highgo.ca\n\nOn Mon, Mar 30, 2020 at 3:44 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Thanks Asif,I have re-verified reported issue. expect standby backup, others are fixed.Yes As Asif mentioned he is working on the standby issue and adding bandwidth throttling functionality to parallel backup.It would be good to get some feedback on Asif previous email from Robert on the design considerations for stand-by server support and throttling. I believe all the other points mentioned by Robert in this thread are addressed by Asif so it would be good to hear about any other concerns that are not addressed. Thanks,-- AhsanThanks & Regards,Rajkumar RaghuwanshiOn Fri, Mar 27, 2020 at 11:04 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Wed, Mar 25, 2020 at 12:22 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,While testing further I observed parallel backup is not able to take backup of standby server.mkdir /tmp/archive_direcho \"archive_mode='on'\">> data/postgresql.confecho \"archive_command='cp %p /tmp/archive_dir/%f'\">> data/postgresql.conf./pg_ctl -D data -l logs start./pg_basebackup -p 5432 -Fp -R -D /tmp/slaveecho \"primary_conninfo='host=127.0.0.1 port=5432 user=edb'\">> /tmp/slave/postgresql.confecho \"restore_command='cp /tmp/archive_dir/%f %p'\">> /tmp/slave/postgresql.confecho \"promote_trigger_file='/tmp/failover.log'\">> /tmp/slave/postgresql.conf./pg_ctl -D /tmp/slave -l /tmp/slave_logs -o \"-p 5433\" start -c [edb@localhost bin]$ ./psql postgres -p 5432 -c \"select pg_is_in_recovery();\" pg_is_in_recovery ------------------- f(1 row)[edb@localhost bin]$ ./psql postgres -p 5433 -c \"select pg_is_in_recovery();\" pg_is_in_recovery ------------------- t(1 row)[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 6pg_basebackup: error: could not list backup files: ERROR:  the standby was promoted during online backupHINT:  This means that the backup being taken is corrupt and should not be used. Try taking another online backup.pg_basebackup: removing data directory \"/tmp/bkp_s\"#same is working fine without parallel backup[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 1[edb@localhost bin]$ ls /tmp/bkp_s/PG_VERSION/tmp/bkp_s/PG_VERSIONThanks & Regards,Rajkumar RaghuwanshiOn Thu, Mar 19, 2020 at 4:11 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,In another scenarios, bkp data is corrupted for tablespace. again this is not reproducible everytime,but If I am running the same set of commands I am getting the same error.[edb@localhost bin]$ ./pg_ctl -D data -l logfile startwaiting for server to start.... doneserver started[edb@localhost bin]$ [edb@localhost bin]$ mkdir /tmp/tblsp[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace tblsp location '/tmp/tblsp';\"CREATE TABLESPACE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create database testdb tablespace tblsp;\"CREATE DATABASE[edb@localhost bin]$ ./psql testdb -p 5432 -c \"create table testtbl (a text);\"CREATE TABLE[edb@localhost bin]$ ./psql testdb -p 5432 -c \"insert into testtbl values ('parallel_backup with tablespace');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp -T /tmp/tblsp=/tmp/tblsp_bkp --jobs 2 [edb@localhost bin]$ ./pg_ctl -D /tmp/bkp -l /tmp/bkp_logs -o \"-p 5555\" startwaiting for server to start.... doneserver started[edb@localhost bin]$ ./psql postgres -p 5555 -c \"select * from pg_tablespace where spcname like 'tblsp%' or spcname = 'pg_default'\";  oid  |  spcname   | spcowner | spcacl | spcoptions -------+------------+----------+--------+------------  1663 | pg_default |       10 |        |  16384 | tblsp      |       10 |        | (2 rows)[edb@localhost bin]$ ./psql testdb -p 5555 -c \"select * from testtbl\";psql: error: could not connect to server: FATAL:  \"pg_tblspc/16384/PG_13_202003051/16385\" is not a valid data directoryDETAIL:  File \"pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\" is missing.[edb@localhost bin]$ [edb@localhost bin]$ ls data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSIONdata/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION[edb@localhost bin]$ ls /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSIONls: cannot access /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION: No such file or directoryThanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 16, 2020 at 6:19 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,On testing further, I found when taking backup with -R, pg_basebackup crashedthis crash is not consistently reproducible.[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a text);\"CREATE TABLE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test values ('parallel_backup with -R recovery-conf');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -RSegmentation fault (core dumped)stack trace looks the same as it was on earlier reported crash with tablespace.--stack trace[edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup Loaded symbols for /lib64/libnss_files.so.2Core was generated by `./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -R'.Program terminated with signal 11, Segmentation fault.#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:31753175\t\t\t\tbackupinfo->curr = fetchfile->next;Missing separate debuginfos, use: debuginfo-install keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64 libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64(gdb) bt#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:3175#1  0x0000000000408a9e in worker_run (arg=0xc1e458) at pg_basebackup.c:2715#2  0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at pthread_create.c:301#3  0x00000039212e8c4d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:115(gdb) Thanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:Hi Asif, Thanks Rajkumar. I have fixed the above issues and have rebased the patch to the latest master (b7f64c64).(V9 of the patches are attached).I had a further review of the patches and here are my few observations: 1.+/*+ * stop_backup() - ends an online backup+ *+ * The function is called at the end of an online backup. It sends out pg_control+ * file, optionally WAL segments and ending WAL location.+ */Comments seem out-dated.Fixed. 2. With parallel jobs, maxrate is now not supported. Since we are now askingdata in multiple threads throttling seems important here. Can you pleaseexplain why have you disabled that?3. As we are always fetching a single file and as Robert suggested, let renameSEND_FILES to SEND_FILE instead.Yes, we are fetching a single file. However, SEND_FILES is still capable of fetching multiple files in onego, that's why the name.4. Does this work on Windows? I mean does pthread_create() work on Windows?I asked this as I see that pgbench has its own implementation forpthread_create() for WIN32 but this patch doesn't.patch is updated to add support for the Windows platform.5. Typos:tablspace => tablespacesafly => safelyDone. 6. parallel_backup_run() needs some comments explaining the states it goesthrough PB_* states.7. +            case PB_FETCH_REL_FILES:    /* fetch files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_STOP_BACKUP;+                    free_filelist(backupinfo);+                }+                break;+            case PB_FETCH_WAL_FILES:    /* fetch WAL files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_BACKUP_COMPLETE;+                }+                break;Done. Why free_filelist() is not called in PB_FETCH_WAL_FILES case?Done.The corrupted tablespace and crash, reported by Rajkumar, have been fixed. A pointervariable remained uninitialized which in turn caused the system to misbehave.Attached is the updated set of patches. AFAIK, to complete parallel backup featureset, there remain three sub-features:1- parallel backup does not work with a standby server. In parallel backup, the serverspawns multiple processes and there is no shared state being maintained. So currently,no way to tell multiple processes if the standby was promoted during the backup sincethe START_BACKUP was called.2- throttling. Robert previously suggested that we implement throttling on the client-side.However, I found a previous discussion where it was advocated to be added to thebackend instead[1].So, it was better to have a consensus before moving the throttle function to the client.That’s why for the time being I have disabled it and have asked for suggestions on itto move forward.It seems to me that we have to maintain a shared state in order to support taking backupfrom standby. Also, there is a new feature recently committed for backup progressreporting in the backend (pg_stat_progress_basebackup). This functionality was recentlyadded via this commit ID: e65497df. For parallel backup to update these stats, a sharedstate will be required.Since multiple pg_basebackup can be running at the same time, maintaining a shared statecan become a little complex, unless we disallow taking multiple parallel backups.So proceeding on with this patch, I will be working on:- throttling to be implemented on the client-side.- adding a shared state to handle backup from the standby.[1] https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n\n-- Highgo Software (Canada/China/Pakistan)URL : http://www.highgo.caADDR: 10318 WHALLEY BLVD, Surrey, BCEMAIL: mailto: ahsan.hadi@highgo.ca", "msg_date": "Mon, 30 Mar 2020 17:58:18 +0500", "msg_from": "Ahsan Hadi <ahsan.hadi@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif,\n\nMy colleague Kashif Zeeshan reported an issue off-list, posting here,\nplease take a look.\n\nWhen executing two backups at the same time, getting FATAL error due to\nmax_wal_senders and instead of exit Backup got completed\nAnd when tried to start the server from the backup cluster, getting error.\n\n[edb@localhost bin]$ ./pgbench -i -s 200 -h localhost -p 5432 postgres\n[edb@localhost bin]$ ./pg_basebackup -v -j 8 -D /home/edb/Desktop/backup/\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 0/C2000270 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: created temporary replication slot \"pg_basebackup_57849\"\npg_basebackup: backup worker (0) created\npg_basebackup: backup worker (1) created\npg_basebackup: backup worker (2) created\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: backup worker (3) created\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: backup worker (4) created\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: backup worker (5) created\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: backup worker (6) created\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: backup worker (7) created\npg_basebackup: write-ahead log end point: 0/C3000050\npg_basebackup: waiting for background process to finish streaming ...\npg_basebackup: syncing data to disk ...\npg_basebackup: base backup completed\n[edb@localhost bin]$ ./pg_basebackup -v -j 8 -D /home/edb/Desktop/backup1/\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 0/C20001C0 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: created temporary replication slot \"pg_basebackup_57848\"\npg_basebackup: backup worker (0) created\npg_basebackup: backup worker (1) created\npg_basebackup: backup worker (2) created\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: backup worker (3) created\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: backup worker (4) created\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: backup worker (5) created\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: backup worker (6) created\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\npg_basebackup: backup worker (7) created\npg_basebackup: write-ahead log end point: 0/C2000348\npg_basebackup: waiting for background process to finish streaming ...\npg_basebackup: syncing data to disk ...\npg_basebackup: base backup completed\n\n[edb@localhost bin]$ ./pg_ctl -D /home/edb/Desktop/backup1/ -o \"-p 5438\"\nstart\npg_ctl: directory \"/home/edb/Desktop/backup1\" is not a database cluster\ndirectory\n\nThanks & Regards,\nRajkumar Raghuwanshi\n\n\nOn Mon, Mar 30, 2020 at 6:28 PM Ahsan Hadi <ahsan.hadi@gmail.com> wrote:\n\n>\n>\n> On Mon, Mar 30, 2020 at 3:44 PM Rajkumar Raghuwanshi <\n> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>\n>> Thanks Asif,\n>>\n>> I have re-verified reported issue. expect standby backup, others are\n>> fixed.\n>>\n>\n> Yes As Asif mentioned he is working on the standby issue and adding\n> bandwidth throttling functionality to parallel backup.\n>\n> It would be good to get some feedback on Asif previous email from Robert\n> on the design considerations for stand-by server support and throttling. I\n> believe all the other points mentioned by Robert in this thread are\n> addressed by Asif so it would be good to hear about any other concerns that\n> are not addressed.\n>\n> Thanks,\n>\n> -- Ahsan\n>\n>\n>> Thanks & Regards,\n>> Rajkumar Raghuwanshi\n>>\n>>\n>> On Fri, Mar 27, 2020 at 11:04 PM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>>\n>>>\n>>>\n>>> On Wed, Mar 25, 2020 at 12:22 PM Rajkumar Raghuwanshi <\n>>> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>>>\n>>>> Hi Asif,\n>>>>\n>>>> While testing further I observed parallel backup is not able to take\n>>>> backup of standby server.\n>>>>\n>>>> mkdir /tmp/archive_dir\n>>>> echo \"archive_mode='on'\">> data/postgresql.conf\n>>>> echo \"archive_command='cp %p /tmp/archive_dir/%f'\">>\n>>>> data/postgresql.conf\n>>>>\n>>>> ./pg_ctl -D data -l logs start\n>>>> ./pg_basebackup -p 5432 -Fp -R -D /tmp/slave\n>>>>\n>>>> echo \"primary_conninfo='host=127.0.0.1 port=5432 user=edb'\">>\n>>>> /tmp/slave/postgresql.conf\n>>>> echo \"restore_command='cp /tmp/archive_dir/%f %p'\">>\n>>>> /tmp/slave/postgresql.conf\n>>>> echo \"promote_trigger_file='/tmp/failover.log'\">>\n>>>> /tmp/slave/postgresql.conf\n>>>>\n>>>> ./pg_ctl -D /tmp/slave -l /tmp/slave_logs -o \"-p 5433\" start -c\n>>>>\n>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"select\n>>>> pg_is_in_recovery();\"\n>>>> pg_is_in_recovery\n>>>> -------------------\n>>>> f\n>>>> (1 row)\n>>>>\n>>>> [edb@localhost bin]$ ./psql postgres -p 5433 -c \"select\n>>>> pg_is_in_recovery();\"\n>>>> pg_is_in_recovery\n>>>> -------------------\n>>>> t\n>>>> (1 row)\n>>>>\n>>>>\n>>>>\n>>>>\n>>>> *[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs\n>>>> 6pg_basebackup: error: could not list backup files: ERROR: the standby was\n>>>> promoted during online backupHINT: This means that the backup being taken\n>>>> is corrupt and should not be used. Try taking another online\n>>>> backup.pg_basebackup: removing data directory \"/tmp/bkp_s\"*\n>>>>\n>>>> #same is working fine without parallel backup\n>>>> [edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 1\n>>>> [edb@localhost bin]$ ls /tmp/bkp_s/PG_VERSION\n>>>> /tmp/bkp_s/PG_VERSION\n>>>>\n>>>> Thanks & Regards,\n>>>> Rajkumar Raghuwanshi\n>>>>\n>>>>\n>>>> On Thu, Mar 19, 2020 at 4:11 PM Rajkumar Raghuwanshi <\n>>>> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>>>>\n>>>>> Hi Asif,\n>>>>>\n>>>>> In another scenarios, bkp data is corrupted for tablespace. again this\n>>>>> is not reproducible everytime,\n>>>>> but If I am running the same set of commands I am getting the same\n>>>>> error.\n>>>>>\n>>>>> [edb@localhost bin]$ ./pg_ctl -D data -l logfile start\n>>>>> waiting for server to start.... done\n>>>>> server started\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$ mkdir /tmp/tblsp\n>>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace\n>>>>> tblsp location '/tmp/tblsp';\"\n>>>>> CREATE TABLESPACE\n>>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create database\n>>>>> testdb tablespace tblsp;\"\n>>>>> CREATE DATABASE\n>>>>> [edb@localhost bin]$ ./psql testdb -p 5432 -c \"create table testtbl\n>>>>> (a text);\"\n>>>>> CREATE TABLE\n>>>>> [edb@localhost bin]$ ./psql testdb -p 5432 -c \"insert into testtbl\n>>>>> values ('parallel_backup with tablespace');\"\n>>>>> INSERT 0 1\n>>>>> [edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp -T\n>>>>> /tmp/tblsp=/tmp/tblsp_bkp --jobs 2\n>>>>> [edb@localhost bin]$ ./pg_ctl -D /tmp/bkp -l /tmp/bkp_logs -o \"-p\n>>>>> 5555\" start\n>>>>> waiting for server to start.... done\n>>>>> server started\n>>>>> [edb@localhost bin]$ ./psql postgres -p 5555 -c \"select * from\n>>>>> pg_tablespace where spcname like 'tblsp%' or spcname = 'pg_default'\";\n>>>>> oid | spcname | spcowner | spcacl | spcoptions\n>>>>> -------+------------+----------+--------+------------\n>>>>> 1663 | pg_default | 10 | |\n>>>>> 16384 | tblsp | 10 | |\n>>>>> (2 rows)\n>>>>>\n>>>>> [edb@localhost bin]$ ./psql testdb -p 5555 -c \"select * from testtbl\";\n>>>>> psql: error: could not connect to server: FATAL:\n>>>>> \"pg_tblspc/16384/PG_13_202003051/16385\" is not a valid data directory\n>>>>> DETAIL: File \"pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\" is\n>>>>> missing.\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$ ls\n>>>>> data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>>>>> data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>>>>> [edb@localhost bin]$ ls\n>>>>> /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>>>>> ls: cannot access\n>>>>> /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION: No such file or\n>>>>> directory\n>>>>>\n>>>>>\n>>>>> Thanks & Regards,\n>>>>> Rajkumar Raghuwanshi\n>>>>>\n>>>>>\n>>>>> On Mon, Mar 16, 2020 at 6:19 PM Rajkumar Raghuwanshi <\n>>>>> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>>>>>\n>>>>>> Hi Asif,\n>>>>>>\n>>>>>> On testing further, I found when taking backup with -R, pg_basebackup\n>>>>>> crashed\n>>>>>> this crash is not consistently reproducible.\n>>>>>>\n>>>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test\n>>>>>> (a text);\"\n>>>>>> CREATE TABLE\n>>>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test\n>>>>>> values ('parallel_backup with -R recovery-conf');\"\n>>>>>> INSERT 0 1\n>>>>>> [edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D\n>>>>>> /tmp/test_bkp/bkp -R\n>>>>>> Segmentation fault (core dumped)\n>>>>>>\n>>>>>> stack trace looks the same as it was on earlier reported crash with\n>>>>>> tablespace.\n>>>>>> --stack trace\n>>>>>> [edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup\n>>>>>> Loaded symbols for /lib64/libnss_files.so.2\n>>>>>> Core was generated by `./pg_basebackup -p 5432 -j 2 -D\n>>>>>> /tmp/test_bkp/bkp -R'.\n>>>>>> Program terminated with signal 11, Segmentation fault.\n>>>>>> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n>>>>>> pg_basebackup.c:3175\n>>>>>> 3175 backupinfo->curr = fetchfile->next;\n>>>>>> Missing separate debuginfos, use: debuginfo-install\n>>>>>> keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\n>>>>>> libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\n>>>>>> openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n>>>>>> (gdb) bt\n>>>>>> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n>>>>>> pg_basebackup.c:3175\n>>>>>> #1 0x0000000000408a9e in worker_run (arg=0xc1e458) at\n>>>>>> pg_basebackup.c:2715\n>>>>>> #2 0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at\n>>>>>> pthread_create.c:301\n>>>>>> #3 0x00000039212e8c4d in clone () at\n>>>>>> ../sysdeps/unix/sysv/linux/x86_64/clone.S:115\n>>>>>> (gdb)\n>>>>>>\n>>>>>> Thanks & Regards,\n>>>>>> Rajkumar Raghuwanshi\n>>>>>>\n>>>>>>\n>>>>>> On Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <\n>>>>>> jeevan.chalke@enterprisedb.com> wrote:\n>>>>>>\n>>>>>>> Hi Asif,\n>>>>>>>\n>>>>>>>\n>>>>>>>> Thanks Rajkumar. I have fixed the above issues and have rebased the\n>>>>>>>> patch to the latest master (b7f64c64).\n>>>>>>>> (V9 of the patches are attached).\n>>>>>>>>\n>>>>>>>\n>>>>>>> I had a further review of the patches and here are my few\n>>>>>>> observations:\n>>>>>>>\n>>>>>>> 1.\n>>>>>>> +/*\n>>>>>>> + * stop_backup() - ends an online backup\n>>>>>>> + *\n>>>>>>> + * The function is called at the end of an online backup. It sends\n>>>>>>> out pg_control\n>>>>>>> + * file, optionally WAL segments and ending WAL location.\n>>>>>>> + */\n>>>>>>>\n>>>>>>> Comments seem out-dated.\n>>>>>>>\n>>>>>>\n>>> Fixed.\n>>>\n>>>\n>>>>\n>>>>>>> 2. With parallel jobs, maxrate is now not supported. Since we are\n>>>>>>> now asking\n>>>>>>> data in multiple threads throttling seems important here. Can you\n>>>>>>> please\n>>>>>>> explain why have you disabled that?\n>>>>>>>\n>>>>>>> 3. As we are always fetching a single file and as Robert suggested,\n>>>>>>> let rename\n>>>>>>> SEND_FILES to SEND_FILE instead.\n>>>>>>>\n>>>>>>\n>>> Yes, we are fetching a single file. However, SEND_FILES is still capable\n>>> of fetching multiple files in one\n>>> go, that's why the name.\n>>>\n>>>\n>>>>>>> 4. Does this work on Windows? I mean does pthread_create() work on\n>>>>>>> Windows?\n>>>>>>> I asked this as I see that pgbench has its own implementation for\n>>>>>>> pthread_create() for WIN32 but this patch doesn't.\n>>>>>>>\n>>>>>>\n>>> patch is updated to add support for the Windows platform.\n>>>\n>>>\n>>>>>>> 5. Typos:\n>>>>>>> tablspace => tablespace\n>>>>>>> safly => safely\n>>>>>>>\n>>>>>>> Done.\n>>>\n>>>\n>>>> 6. parallel_backup_run() needs some comments explaining the states it\n>>>>>>> goes\n>>>>>>> through PB_* states.\n>>>>>>>\n>>>>>>> 7.\n>>>>>>> + case PB_FETCH_REL_FILES: /* fetch files from server\n>>>>>>> */\n>>>>>>> + if (backupinfo->activeworkers == 0)\n>>>>>>> + {\n>>>>>>> + backupinfo->backupstate = PB_STOP_BACKUP;\n>>>>>>> + free_filelist(backupinfo);\n>>>>>>> + }\n>>>>>>> + break;\n>>>>>>> + case PB_FETCH_WAL_FILES: /* fetch WAL files from\n>>>>>>> server */\n>>>>>>> + if (backupinfo->activeworkers == 0)\n>>>>>>> + {\n>>>>>>> + backupinfo->backupstate = PB_BACKUP_COMPLETE;\n>>>>>>> + }\n>>>>>>> + break;\n>>>>>>>\n>>>>>> Done.\n>>>\n>>>\n>>>>\n>>>>>>> Why free_filelist() is not called in PB_FETCH_WAL_FILES case?\n>>>>>>>\n>>>>>> Done.\n>>>\n>>> The corrupted tablespace and crash, reported by Rajkumar, have been\n>>> fixed. A pointer\n>>> variable remained uninitialized which in turn caused the system to\n>>> misbehave.\n>>>\n>>> Attached is the updated set of patches. AFAIK, to complete parallel\n>>> backup feature\n>>> set, there remain three sub-features:\n>>>\n>>> 1- parallel backup does not work with a standby server. In parallel\n>>> backup, the server\n>>> spawns multiple processes and there is no shared state being maintained.\n>>> So currently,\n>>> no way to tell multiple processes if the standby was promoted during the\n>>> backup since\n>>> the START_BACKUP was called.\n>>>\n>>> 2- throttling. Robert previously suggested that we implement\n>>> throttling on the client-side.\n>>> However, I found a previous discussion where it was advocated to be\n>>> added to the\n>>> backend instead[1].\n>>>\n>>> So, it was better to have a consensus before moving the throttle\n>>> function to the client.\n>>> That’s why for the time being I have disabled it and have asked for\n>>> suggestions on it\n>>> to move forward.\n>>>\n>>> It seems to me that we have to maintain a shared state in order to\n>>> support taking backup\n>>> from standby. Also, there is a new feature recently committed for backup\n>>> progress\n>>> reporting in the backend (pg_stat_progress_basebackup). This\n>>> functionality was recently\n>>> added via this commit ID: e65497df. For parallel backup to update these\n>>> stats, a shared\n>>> state will be required.\n>>>\n>>> Since multiple pg_basebackup can be running at the same time,\n>>> maintaining a shared state\n>>> can become a little complex, unless we disallow taking multiple parallel\n>>> backups.\n>>>\n>>> So proceeding on with this patch, I will be working on:\n>>> - throttling to be implemented on the client-side.\n>>> - adding a shared state to handle backup from the standby.\n>>>\n>>>\n>>>\n>>> [1]\n>>> https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af\n>>>\n>>>\n>>> --\n>>> Asif Rehman\n>>> Highgo Software (Canada/China/Pakistan)\n>>> URL : www.highgo.ca\n>>>\n>>>\n>\n> --\n> Highgo Software (Canada/China/Pakistan)\n> URL : http://www.highgo.ca\n> ADDR: 10318 WHALLEY BLVD, Surrey, BC\n> EMAIL: mailto: ahsan.hadi@highgo.ca\n>\n\nHi Asif,My colleague Kashif Zeeshan reported an issue off-list, posting here, please take a look.When executing two backups at the same time, getting FATAL error due to max_wal_senders and instead of exit  Backup got completedAnd when tried to start the server from the backup cluster, getting error.[edb@localhost bin]$ ./pgbench -i -s 200 -h localhost -p 5432 postgres[edb@localhost bin]$ ./pg_basebackup -v -j 8 -D  /home/edb/Desktop/backup/pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C2000270 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_57849\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (3) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (4) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (5) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (6) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (7) createdpg_basebackup: write-ahead log end point: 0/C3000050pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: syncing data to disk ...pg_basebackup: base backup completed[edb@localhost bin]$ ./pg_basebackup -v -j 8 -D  /home/edb/Desktop/backup1/pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C20001C0 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_57848\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (3) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (4) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (5) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (6) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (7) createdpg_basebackup: write-ahead log end point: 0/C2000348pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: syncing data to disk ...pg_basebackup: base backup completed[edb@localhost bin]$ ./pg_ctl -D /home/edb/Desktop/backup1/  -o \"-p 5438\" startpg_ctl: directory \"/home/edb/Desktop/backup1\" is not a database cluster directoryThanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 30, 2020 at 6:28 PM Ahsan Hadi <ahsan.hadi@gmail.com> wrote:On Mon, Mar 30, 2020 at 3:44 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Thanks Asif,I have re-verified reported issue. expect standby backup, others are fixed.Yes As Asif mentioned he is working on the standby issue and adding bandwidth throttling functionality to parallel backup.It would be good to get some feedback on Asif previous email from Robert on the design considerations for stand-by server support and throttling. I believe all the other points mentioned by Robert in this thread are addressed by Asif so it would be good to hear about any other concerns that are not addressed. Thanks,-- AhsanThanks & Regards,Rajkumar RaghuwanshiOn Fri, Mar 27, 2020 at 11:04 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Wed, Mar 25, 2020 at 12:22 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,While testing further I observed parallel backup is not able to take backup of standby server.mkdir /tmp/archive_direcho \"archive_mode='on'\">> data/postgresql.confecho \"archive_command='cp %p /tmp/archive_dir/%f'\">> data/postgresql.conf./pg_ctl -D data -l logs start./pg_basebackup -p 5432 -Fp -R -D /tmp/slaveecho \"primary_conninfo='host=127.0.0.1 port=5432 user=edb'\">> /tmp/slave/postgresql.confecho \"restore_command='cp /tmp/archive_dir/%f %p'\">> /tmp/slave/postgresql.confecho \"promote_trigger_file='/tmp/failover.log'\">> /tmp/slave/postgresql.conf./pg_ctl -D /tmp/slave -l /tmp/slave_logs -o \"-p 5433\" start -c [edb@localhost bin]$ ./psql postgres -p 5432 -c \"select pg_is_in_recovery();\" pg_is_in_recovery ------------------- f(1 row)[edb@localhost bin]$ ./psql postgres -p 5433 -c \"select pg_is_in_recovery();\" pg_is_in_recovery ------------------- t(1 row)[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 6pg_basebackup: error: could not list backup files: ERROR:  the standby was promoted during online backupHINT:  This means that the backup being taken is corrupt and should not be used. Try taking another online backup.pg_basebackup: removing data directory \"/tmp/bkp_s\"#same is working fine without parallel backup[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 1[edb@localhost bin]$ ls /tmp/bkp_s/PG_VERSION/tmp/bkp_s/PG_VERSIONThanks & Regards,Rajkumar RaghuwanshiOn Thu, Mar 19, 2020 at 4:11 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,In another scenarios, bkp data is corrupted for tablespace. again this is not reproducible everytime,but If I am running the same set of commands I am getting the same error.[edb@localhost bin]$ ./pg_ctl -D data -l logfile startwaiting for server to start.... doneserver started[edb@localhost bin]$ [edb@localhost bin]$ mkdir /tmp/tblsp[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace tblsp location '/tmp/tblsp';\"CREATE TABLESPACE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create database testdb tablespace tblsp;\"CREATE DATABASE[edb@localhost bin]$ ./psql testdb -p 5432 -c \"create table testtbl (a text);\"CREATE TABLE[edb@localhost bin]$ ./psql testdb -p 5432 -c \"insert into testtbl values ('parallel_backup with tablespace');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp -T /tmp/tblsp=/tmp/tblsp_bkp --jobs 2 [edb@localhost bin]$ ./pg_ctl -D /tmp/bkp -l /tmp/bkp_logs -o \"-p 5555\" startwaiting for server to start.... doneserver started[edb@localhost bin]$ ./psql postgres -p 5555 -c \"select * from pg_tablespace where spcname like 'tblsp%' or spcname = 'pg_default'\";  oid  |  spcname   | spcowner | spcacl | spcoptions -------+------------+----------+--------+------------  1663 | pg_default |       10 |        |  16384 | tblsp      |       10 |        | (2 rows)[edb@localhost bin]$ ./psql testdb -p 5555 -c \"select * from testtbl\";psql: error: could not connect to server: FATAL:  \"pg_tblspc/16384/PG_13_202003051/16385\" is not a valid data directoryDETAIL:  File \"pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\" is missing.[edb@localhost bin]$ [edb@localhost bin]$ ls data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSIONdata/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION[edb@localhost bin]$ ls /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSIONls: cannot access /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION: No such file or directoryThanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 16, 2020 at 6:19 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,On testing further, I found when taking backup with -R, pg_basebackup crashedthis crash is not consistently reproducible.[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a text);\"CREATE TABLE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test values ('parallel_backup with -R recovery-conf');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -RSegmentation fault (core dumped)stack trace looks the same as it was on earlier reported crash with tablespace.--stack trace[edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup Loaded symbols for /lib64/libnss_files.so.2Core was generated by `./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -R'.Program terminated with signal 11, Segmentation fault.#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:31753175\t\t\t\tbackupinfo->curr = fetchfile->next;Missing separate debuginfos, use: debuginfo-install keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64 libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64(gdb) bt#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:3175#1  0x0000000000408a9e in worker_run (arg=0xc1e458) at pg_basebackup.c:2715#2  0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at pthread_create.c:301#3  0x00000039212e8c4d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:115(gdb) Thanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:Hi Asif, Thanks Rajkumar. I have fixed the above issues and have rebased the patch to the latest master (b7f64c64).(V9 of the patches are attached).I had a further review of the patches and here are my few observations: 1.+/*+ * stop_backup() - ends an online backup+ *+ * The function is called at the end of an online backup. It sends out pg_control+ * file, optionally WAL segments and ending WAL location.+ */Comments seem out-dated.Fixed. 2. With parallel jobs, maxrate is now not supported. Since we are now askingdata in multiple threads throttling seems important here. Can you pleaseexplain why have you disabled that?3. As we are always fetching a single file and as Robert suggested, let renameSEND_FILES to SEND_FILE instead.Yes, we are fetching a single file. However, SEND_FILES is still capable of fetching multiple files in onego, that's why the name.4. Does this work on Windows? I mean does pthread_create() work on Windows?I asked this as I see that pgbench has its own implementation forpthread_create() for WIN32 but this patch doesn't.patch is updated to add support for the Windows platform.5. Typos:tablspace => tablespacesafly => safelyDone. 6. parallel_backup_run() needs some comments explaining the states it goesthrough PB_* states.7. +            case PB_FETCH_REL_FILES:    /* fetch files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_STOP_BACKUP;+                    free_filelist(backupinfo);+                }+                break;+            case PB_FETCH_WAL_FILES:    /* fetch WAL files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_BACKUP_COMPLETE;+                }+                break;Done. Why free_filelist() is not called in PB_FETCH_WAL_FILES case?Done.The corrupted tablespace and crash, reported by Rajkumar, have been fixed. A pointervariable remained uninitialized which in turn caused the system to misbehave.Attached is the updated set of patches. AFAIK, to complete parallel backup featureset, there remain three sub-features:1- parallel backup does not work with a standby server. In parallel backup, the serverspawns multiple processes and there is no shared state being maintained. So currently,no way to tell multiple processes if the standby was promoted during the backup sincethe START_BACKUP was called.2- throttling. Robert previously suggested that we implement throttling on the client-side.However, I found a previous discussion where it was advocated to be added to thebackend instead[1].So, it was better to have a consensus before moving the throttle function to the client.That’s why for the time being I have disabled it and have asked for suggestions on itto move forward.It seems to me that we have to maintain a shared state in order to support taking backupfrom standby. Also, there is a new feature recently committed for backup progressreporting in the backend (pg_stat_progress_basebackup). This functionality was recentlyadded via this commit ID: e65497df. For parallel backup to update these stats, a sharedstate will be required.Since multiple pg_basebackup can be running at the same time, maintaining a shared statecan become a little complex, unless we disallow taking multiple parallel backups.So proceeding on with this patch, I will be working on:- throttling to be implemented on the client-side.- adding a shared state to handle backup from the standby.[1] https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n\n-- Highgo Software (Canada/China/Pakistan)URL : http://www.highgo.caADDR: 10318 WHALLEY BLVD, Surrey, BCEMAIL: mailto: ahsan.hadi@highgo.ca", "msg_date": "Thu, 2 Apr 2020 15:27:52 +0530", "msg_from": "Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif\n\nThe backup failed with errors \"error: could not connect to server: could\nnot look up local user ID 1000: Too many open files\" when the\nmax_wal_senders was set to 2000.\nThe errors generated for the workers starting from backup worke=1017.\nPlease note that the backup directory was also not cleaned after the backup\nwas failed.\n\n\nSteps\n=======\n1) Generate data in DB\n ./pgbench -i -s 600 -h localhost -p 5432 postgres\n2) Set max_wal_senders = 2000 in postgresql.\n3) Generate the backup\n\n\n[edb@localhost bin]$\n^[[A[edb@localhost bin]$\n[edb@localhost bin]$ ./pg_basebackup -v -j 1990 -D\n /home/edb/Desktop/backup/\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 1/F1000028 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: created temporary replication slot \"pg_basebackup_58692\"\npg_basebackup: backup worker (0) created\n….\n…..\n…..\npg_basebackup: backup worker (1017) created\npg_basebackup: error: could not connect to server: could not look up local\nuser ID 1000: Too many open files\npg_basebackup: backup worker (1018) created\npg_basebackup: error: could not connect to server: could not look up local\nuser ID 1000: Too many open files\n…\n…\n…\npg_basebackup: error: could not connect to server: could not look up local\nuser ID 1000: Too many open files\npg_basebackup: backup worker (1989) created\npg_basebackup: error: could not create file\n\"/home/edb/Desktop/backup//global/4183\": Too many open files\npg_basebackup: error: could not create file\n\"/home/edb/Desktop/backup//global/3592\": Too many open files\npg_basebackup: error: could not create file\n\"/home/edb/Desktop/backup//global/4177\": Too many open files\n[edb@localhost bin]$\n\n\n4) The backup directory is not cleaned\n\n\n[edb@localhost bin]$\n[edb@localhost bin]$ ls /home/edb/Desktop/backup\nbase pg_commit_ts pg_logical pg_notify pg_serial pg_stat\n pg_subtrans pg_twophase pg_xact\nglobal pg_dynshmem pg_multixact pg_replslot pg_snapshots pg_stat_tmp\n pg_tblspc pg_wal\n[edb@localhost bin]$\n\n\nKashif Zeeshan\nEnterpriseDB\n\n\nOn Thu, Apr 2, 2020 at 2:58 PM Rajkumar Raghuwanshi <\nrajkumar.raghuwanshi@enterprisedb.com> wrote:\n\n> Hi Asif,\n>\n> My colleague Kashif Zeeshan reported an issue off-list, posting here,\n> please take a look.\n>\n> When executing two backups at the same time, getting FATAL error due to\n> max_wal_senders and instead of exit Backup got completed\n> And when tried to start the server from the backup cluster, getting error.\n>\n> [edb@localhost bin]$ ./pgbench -i -s 200 -h localhost -p 5432 postgres\n> [edb@localhost bin]$ ./pg_basebackup -v -j 8 -D /home/edb/Desktop/backup/\n> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n> pg_basebackup: checkpoint completed\n> pg_basebackup: write-ahead log start point: 0/C2000270 on timeline 1\n> pg_basebackup: starting background WAL receiver\n> pg_basebackup: created temporary replication slot \"pg_basebackup_57849\"\n> pg_basebackup: backup worker (0) created\n> pg_basebackup: backup worker (1) created\n> pg_basebackup: backup worker (2) created\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: backup worker (3) created\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: backup worker (4) created\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: backup worker (5) created\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: backup worker (6) created\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: backup worker (7) created\n> pg_basebackup: write-ahead log end point: 0/C3000050\n> pg_basebackup: waiting for background process to finish streaming ...\n> pg_basebackup: syncing data to disk ...\n> pg_basebackup: base backup completed\n> [edb@localhost bin]$ ./pg_basebackup -v -j 8 -D\n> /home/edb/Desktop/backup1/\n> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n> pg_basebackup: checkpoint completed\n> pg_basebackup: write-ahead log start point: 0/C20001C0 on timeline 1\n> pg_basebackup: starting background WAL receiver\n> pg_basebackup: created temporary replication slot \"pg_basebackup_57848\"\n> pg_basebackup: backup worker (0) created\n> pg_basebackup: backup worker (1) created\n> pg_basebackup: backup worker (2) created\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: backup worker (3) created\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: backup worker (4) created\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: backup worker (5) created\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: backup worker (6) created\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> pg_basebackup: backup worker (7) created\n> pg_basebackup: write-ahead log end point: 0/C2000348\n> pg_basebackup: waiting for background process to finish streaming ...\n> pg_basebackup: syncing data to disk ...\n> pg_basebackup: base backup completed\n>\n> [edb@localhost bin]$ ./pg_ctl -D /home/edb/Desktop/backup1/ -o \"-p 5438\"\n> start\n> pg_ctl: directory \"/home/edb/Desktop/backup1\" is not a database cluster\n> directory\n>\n> Thanks & Regards,\n> Rajkumar Raghuwanshi\n>\n>\n> On Mon, Mar 30, 2020 at 6:28 PM Ahsan Hadi <ahsan.hadi@gmail.com> wrote:\n>\n>>\n>>\n>> On Mon, Mar 30, 2020 at 3:44 PM Rajkumar Raghuwanshi <\n>> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>>\n>>> Thanks Asif,\n>>>\n>>> I have re-verified reported issue. expect standby backup, others are\n>>> fixed.\n>>>\n>>\n>> Yes As Asif mentioned he is working on the standby issue and adding\n>> bandwidth throttling functionality to parallel backup.\n>>\n>> It would be good to get some feedback on Asif previous email from Robert\n>> on the design considerations for stand-by server support and throttling. I\n>> believe all the other points mentioned by Robert in this thread are\n>> addressed by Asif so it would be good to hear about any other concerns that\n>> are not addressed.\n>>\n>> Thanks,\n>>\n>> -- Ahsan\n>>\n>>\n>>> Thanks & Regards,\n>>> Rajkumar Raghuwanshi\n>>>\n>>>\n>>> On Fri, Mar 27, 2020 at 11:04 PM Asif Rehman <asifr.rehman@gmail.com>\n>>> wrote:\n>>>\n>>>>\n>>>>\n>>>> On Wed, Mar 25, 2020 at 12:22 PM Rajkumar Raghuwanshi <\n>>>> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>>>>\n>>>>> Hi Asif,\n>>>>>\n>>>>> While testing further I observed parallel backup is not able to take\n>>>>> backup of standby server.\n>>>>>\n>>>>> mkdir /tmp/archive_dir\n>>>>> echo \"archive_mode='on'\">> data/postgresql.conf\n>>>>> echo \"archive_command='cp %p /tmp/archive_dir/%f'\">>\n>>>>> data/postgresql.conf\n>>>>>\n>>>>> ./pg_ctl -D data -l logs start\n>>>>> ./pg_basebackup -p 5432 -Fp -R -D /tmp/slave\n>>>>>\n>>>>> echo \"primary_conninfo='host=127.0.0.1 port=5432 user=edb'\">>\n>>>>> /tmp/slave/postgresql.conf\n>>>>> echo \"restore_command='cp /tmp/archive_dir/%f %p'\">>\n>>>>> /tmp/slave/postgresql.conf\n>>>>> echo \"promote_trigger_file='/tmp/failover.log'\">>\n>>>>> /tmp/slave/postgresql.conf\n>>>>>\n>>>>> ./pg_ctl -D /tmp/slave -l /tmp/slave_logs -o \"-p 5433\" start -c\n>>>>>\n>>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"select\n>>>>> pg_is_in_recovery();\"\n>>>>> pg_is_in_recovery\n>>>>> -------------------\n>>>>> f\n>>>>> (1 row)\n>>>>>\n>>>>> [edb@localhost bin]$ ./psql postgres -p 5433 -c \"select\n>>>>> pg_is_in_recovery();\"\n>>>>> pg_is_in_recovery\n>>>>> -------------------\n>>>>> t\n>>>>> (1 row)\n>>>>>\n>>>>>\n>>>>>\n>>>>>\n>>>>> *[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs\n>>>>> 6pg_basebackup: error: could not list backup files: ERROR: the standby was\n>>>>> promoted during online backupHINT: This means that the backup being taken\n>>>>> is corrupt and should not be used. Try taking another online\n>>>>> backup.pg_basebackup: removing data directory \"/tmp/bkp_s\"*\n>>>>>\n>>>>> #same is working fine without parallel backup\n>>>>> [edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 1\n>>>>> [edb@localhost bin]$ ls /tmp/bkp_s/PG_VERSION\n>>>>> /tmp/bkp_s/PG_VERSION\n>>>>>\n>>>>> Thanks & Regards,\n>>>>> Rajkumar Raghuwanshi\n>>>>>\n>>>>>\n>>>>> On Thu, Mar 19, 2020 at 4:11 PM Rajkumar Raghuwanshi <\n>>>>> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>>>>>\n>>>>>> Hi Asif,\n>>>>>>\n>>>>>> In another scenarios, bkp data is corrupted for tablespace. again\n>>>>>> this is not reproducible everytime,\n>>>>>> but If I am running the same set of commands I am getting the same\n>>>>>> error.\n>>>>>>\n>>>>>> [edb@localhost bin]$ ./pg_ctl -D data -l logfile start\n>>>>>> waiting for server to start.... done\n>>>>>> server started\n>>>>>> [edb@localhost bin]$\n>>>>>> [edb@localhost bin]$ mkdir /tmp/tblsp\n>>>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace\n>>>>>> tblsp location '/tmp/tblsp';\"\n>>>>>> CREATE TABLESPACE\n>>>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create database\n>>>>>> testdb tablespace tblsp;\"\n>>>>>> CREATE DATABASE\n>>>>>> [edb@localhost bin]$ ./psql testdb -p 5432 -c \"create table testtbl\n>>>>>> (a text);\"\n>>>>>> CREATE TABLE\n>>>>>> [edb@localhost bin]$ ./psql testdb -p 5432 -c \"insert into testtbl\n>>>>>> values ('parallel_backup with tablespace');\"\n>>>>>> INSERT 0 1\n>>>>>> [edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp -T\n>>>>>> /tmp/tblsp=/tmp/tblsp_bkp --jobs 2\n>>>>>> [edb@localhost bin]$ ./pg_ctl -D /tmp/bkp -l /tmp/bkp_logs -o \"-p\n>>>>>> 5555\" start\n>>>>>> waiting for server to start.... done\n>>>>>> server started\n>>>>>> [edb@localhost bin]$ ./psql postgres -p 5555 -c \"select * from\n>>>>>> pg_tablespace where spcname like 'tblsp%' or spcname = 'pg_default'\";\n>>>>>> oid | spcname | spcowner | spcacl | spcoptions\n>>>>>> -------+------------+----------+--------+------------\n>>>>>> 1663 | pg_default | 10 | |\n>>>>>> 16384 | tblsp | 10 | |\n>>>>>> (2 rows)\n>>>>>>\n>>>>>> [edb@localhost bin]$ ./psql testdb -p 5555 -c \"select * from\n>>>>>> testtbl\";\n>>>>>> psql: error: could not connect to server: FATAL:\n>>>>>> \"pg_tblspc/16384/PG_13_202003051/16385\" is not a valid data directory\n>>>>>> DETAIL: File \"pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\" is\n>>>>>> missing.\n>>>>>> [edb@localhost bin]$\n>>>>>> [edb@localhost bin]$ ls\n>>>>>> data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>>>>>> data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>>>>>> [edb@localhost bin]$ ls\n>>>>>> /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\n>>>>>> ls: cannot access\n>>>>>> /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION: No such file or\n>>>>>> directory\n>>>>>>\n>>>>>>\n>>>>>> Thanks & Regards,\n>>>>>> Rajkumar Raghuwanshi\n>>>>>>\n>>>>>>\n>>>>>> On Mon, Mar 16, 2020 at 6:19 PM Rajkumar Raghuwanshi <\n>>>>>> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>>>>>>\n>>>>>>> Hi Asif,\n>>>>>>>\n>>>>>>> On testing further, I found when taking backup with -R,\n>>>>>>> pg_basebackup crashed\n>>>>>>> this crash is not consistently reproducible.\n>>>>>>>\n>>>>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test\n>>>>>>> (a text);\"\n>>>>>>> CREATE TABLE\n>>>>>>> [edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test\n>>>>>>> values ('parallel_backup with -R recovery-conf');\"\n>>>>>>> INSERT 0 1\n>>>>>>> [edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D\n>>>>>>> /tmp/test_bkp/bkp -R\n>>>>>>> Segmentation fault (core dumped)\n>>>>>>>\n>>>>>>> stack trace looks the same as it was on earlier reported crash with\n>>>>>>> tablespace.\n>>>>>>> --stack trace\n>>>>>>> [edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup\n>>>>>>> Loaded symbols for /lib64/libnss_files.so.2\n>>>>>>> Core was generated by `./pg_basebackup -p 5432 -j 2 -D\n>>>>>>> /tmp/test_bkp/bkp -R'.\n>>>>>>> Program terminated with signal 11, Segmentation fault.\n>>>>>>> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n>>>>>>> pg_basebackup.c:3175\n>>>>>>> 3175 backupinfo->curr = fetchfile->next;\n>>>>>>> Missing separate debuginfos, use: debuginfo-install\n>>>>>>> keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\n>>>>>>> libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\n>>>>>>> openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n>>>>>>> (gdb) bt\n>>>>>>> #0 0x00000000004099ee in worker_get_files (wstate=0xc1e458) at\n>>>>>>> pg_basebackup.c:3175\n>>>>>>> #1 0x0000000000408a9e in worker_run (arg=0xc1e458) at\n>>>>>>> pg_basebackup.c:2715\n>>>>>>> #2 0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at\n>>>>>>> pthread_create.c:301\n>>>>>>> #3 0x00000039212e8c4d in clone () at\n>>>>>>> ../sysdeps/unix/sysv/linux/x86_64/clone.S:115\n>>>>>>> (gdb)\n>>>>>>>\n>>>>>>> Thanks & Regards,\n>>>>>>> Rajkumar Raghuwanshi\n>>>>>>>\n>>>>>>>\n>>>>>>> On Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <\n>>>>>>> jeevan.chalke@enterprisedb.com> wrote:\n>>>>>>>\n>>>>>>>> Hi Asif,\n>>>>>>>>\n>>>>>>>>\n>>>>>>>>> Thanks Rajkumar. I have fixed the above issues and have rebased\n>>>>>>>>> the patch to the latest master (b7f64c64).\n>>>>>>>>> (V9 of the patches are attached).\n>>>>>>>>>\n>>>>>>>>\n>>>>>>>> I had a further review of the patches and here are my few\n>>>>>>>> observations:\n>>>>>>>>\n>>>>>>>> 1.\n>>>>>>>> +/*\n>>>>>>>> + * stop_backup() - ends an online backup\n>>>>>>>> + *\n>>>>>>>> + * The function is called at the end of an online backup. It sends\n>>>>>>>> out pg_control\n>>>>>>>> + * file, optionally WAL segments and ending WAL location.\n>>>>>>>> + */\n>>>>>>>>\n>>>>>>>> Comments seem out-dated.\n>>>>>>>>\n>>>>>>>\n>>>> Fixed.\n>>>>\n>>>>\n>>>>>\n>>>>>>>> 2. With parallel jobs, maxrate is now not supported. Since we are\n>>>>>>>> now asking\n>>>>>>>> data in multiple threads throttling seems important here. Can you\n>>>>>>>> please\n>>>>>>>> explain why have you disabled that?\n>>>>>>>>\n>>>>>>>> 3. As we are always fetching a single file and as Robert suggested,\n>>>>>>>> let rename\n>>>>>>>> SEND_FILES to SEND_FILE instead.\n>>>>>>>>\n>>>>>>>\n>>>> Yes, we are fetching a single file. However, SEND_FILES is still\n>>>> capable of fetching multiple files in one\n>>>> go, that's why the name.\n>>>>\n>>>>\n>>>>>>>> 4. Does this work on Windows? I mean does pthread_create() work on\n>>>>>>>> Windows?\n>>>>>>>> I asked this as I see that pgbench has its own implementation for\n>>>>>>>> pthread_create() for WIN32 but this patch doesn't.\n>>>>>>>>\n>>>>>>>\n>>>> patch is updated to add support for the Windows platform.\n>>>>\n>>>>\n>>>>>>>> 5. Typos:\n>>>>>>>> tablspace => tablespace\n>>>>>>>> safly => safely\n>>>>>>>>\n>>>>>>>> Done.\n>>>>\n>>>>\n>>>>> 6. parallel_backup_run() needs some comments explaining the states it\n>>>>>>>> goes\n>>>>>>>> through PB_* states.\n>>>>>>>>\n>>>>>>>> 7.\n>>>>>>>> + case PB_FETCH_REL_FILES: /* fetch files from server\n>>>>>>>> */\n>>>>>>>> + if (backupinfo->activeworkers == 0)\n>>>>>>>> + {\n>>>>>>>> + backupinfo->backupstate = PB_STOP_BACKUP;\n>>>>>>>> + free_filelist(backupinfo);\n>>>>>>>> + }\n>>>>>>>> + break;\n>>>>>>>> + case PB_FETCH_WAL_FILES: /* fetch WAL files from\n>>>>>>>> server */\n>>>>>>>> + if (backupinfo->activeworkers == 0)\n>>>>>>>> + {\n>>>>>>>> + backupinfo->backupstate = PB_BACKUP_COMPLETE;\n>>>>>>>> + }\n>>>>>>>> + break;\n>>>>>>>>\n>>>>>>> Done.\n>>>>\n>>>>\n>>>>>\n>>>>>>>> Why free_filelist() is not called in PB_FETCH_WAL_FILES case?\n>>>>>>>>\n>>>>>>> Done.\n>>>>\n>>>> The corrupted tablespace and crash, reported by Rajkumar, have been\n>>>> fixed. A pointer\n>>>> variable remained uninitialized which in turn caused the system to\n>>>> misbehave.\n>>>>\n>>>> Attached is the updated set of patches. AFAIK, to complete parallel\n>>>> backup feature\n>>>> set, there remain three sub-features:\n>>>>\n>>>> 1- parallel backup does not work with a standby server. In parallel\n>>>> backup, the server\n>>>> spawns multiple processes and there is no shared state being\n>>>> maintained. So currently,\n>>>> no way to tell multiple processes if the standby was promoted during\n>>>> the backup since\n>>>> the START_BACKUP was called.\n>>>>\n>>>> 2- throttling. Robert previously suggested that we implement\n>>>> throttling on the client-side.\n>>>> However, I found a previous discussion where it was advocated to be\n>>>> added to the\n>>>> backend instead[1].\n>>>>\n>>>> So, it was better to have a consensus before moving the throttle\n>>>> function to the client.\n>>>> That’s why for the time being I have disabled it and have asked for\n>>>> suggestions on it\n>>>> to move forward.\n>>>>\n>>>> It seems to me that we have to maintain a shared state in order to\n>>>> support taking backup\n>>>> from standby. Also, there is a new feature recently committed for\n>>>> backup progress\n>>>> reporting in the backend (pg_stat_progress_basebackup). This\n>>>> functionality was recently\n>>>> added via this commit ID: e65497df. For parallel backup to update these\n>>>> stats, a shared\n>>>> state will be required.\n>>>>\n>>>> Since multiple pg_basebackup can be running at the same time,\n>>>> maintaining a shared state\n>>>> can become a little complex, unless we disallow taking multiple\n>>>> parallel backups.\n>>>>\n>>>> So proceeding on with this patch, I will be working on:\n>>>> - throttling to be implemented on the client-side.\n>>>> - adding a shared state to handle backup from the standby.\n>>>>\n>>>>\n>>>>\n>>>> [1]\n>>>> https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af\n>>>>\n>>>>\n>>>> --\n>>>> Asif Rehman\n>>>> Highgo Software (Canada/China/Pakistan)\n>>>> URL : www.highgo.ca\n>>>>\n>>>>\n>>\n>> --\n>> Highgo Software (Canada/China/Pakistan)\n>> URL : http://www.highgo.ca\n>> ADDR: 10318 WHALLEY BLVD, Surrey, BC\n>> EMAIL: mailto: ahsan.hadi@highgo.ca\n>>\n>\n\n-- \nRegards\n====================================\nKashif Zeeshan\nLead Quality Assurance Engineer / Manager\n\nEnterpriseDB Corporation\nThe Enterprise Postgres Company\n\nHi AsifThe backup failed with errors \"error: could not connect to server: could not look up local user ID 1000: Too many open files\" when the max_wal_senders was set to 2000. The errors generated for the workers starting from backup worke=1017. Please note that the backup directory was also not cleaned after the backup was failed.Steps=======1) Generate data in DB ./pgbench -i -s 600 -h localhost  -p 5432 postgres2) Set max_wal_senders = 2000 in postgresql.3) Generate the backup[edb@localhost bin]$ ^[[A[edb@localhost bin]$ [edb@localhost bin]$ ./pg_basebackup -v -j 1990 -D  /home/edb/Desktop/backup/pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 1/F1000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_58692\"pg_basebackup: backup worker (0) created….…..…..pg_basebackup: backup worker (1017) createdpg_basebackup: error: could not connect to server: could not look up local user ID 1000: Too many open filespg_basebackup: backup worker (1018) createdpg_basebackup: error: could not connect to server: could not look up local user ID 1000: Too many open files………pg_basebackup: error: could not connect to server: could not look up local user ID 1000: Too many open filespg_basebackup: backup worker (1989) createdpg_basebackup: error: could not create file \"/home/edb/Desktop/backup//global/4183\": Too many open filespg_basebackup: error: could not create file \"/home/edb/Desktop/backup//global/3592\": Too many open filespg_basebackup: error: could not create file \"/home/edb/Desktop/backup//global/4177\": Too many open files[edb@localhost bin]$ 4) The backup directory is not cleaned [edb@localhost bin]$ [edb@localhost bin]$ ls  /home/edb/Desktop/backupbase    pg_commit_ts  pg_logical    pg_notify    pg_serial     pg_stat      pg_subtrans  pg_twophase  pg_xactglobal  pg_dynshmem   pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    pg_wal[edb@localhost bin]$ Kashif ZeeshanEnterpriseDB On Thu, Apr 2, 2020 at 2:58 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,My colleague Kashif Zeeshan reported an issue off-list, posting here, please take a look.When executing two backups at the same time, getting FATAL error due to max_wal_senders and instead of exit  Backup got completedAnd when tried to start the server from the backup cluster, getting error.[edb@localhost bin]$ ./pgbench -i -s 200 -h localhost -p 5432 postgres[edb@localhost bin]$ ./pg_basebackup -v -j 8 -D  /home/edb/Desktop/backup/pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C2000270 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_57849\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (3) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (4) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (5) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (6) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (7) createdpg_basebackup: write-ahead log end point: 0/C3000050pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: syncing data to disk ...pg_basebackup: base backup completed[edb@localhost bin]$ ./pg_basebackup -v -j 8 -D  /home/edb/Desktop/backup1/pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C20001C0 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_57848\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (3) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (4) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (5) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (6) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)pg_basebackup: backup worker (7) createdpg_basebackup: write-ahead log end point: 0/C2000348pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: syncing data to disk ...pg_basebackup: base backup completed[edb@localhost bin]$ ./pg_ctl -D /home/edb/Desktop/backup1/  -o \"-p 5438\" startpg_ctl: directory \"/home/edb/Desktop/backup1\" is not a database cluster directoryThanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 30, 2020 at 6:28 PM Ahsan Hadi <ahsan.hadi@gmail.com> wrote:On Mon, Mar 30, 2020 at 3:44 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Thanks Asif,I have re-verified reported issue. expect standby backup, others are fixed.Yes As Asif mentioned he is working on the standby issue and adding bandwidth throttling functionality to parallel backup.It would be good to get some feedback on Asif previous email from Robert on the design considerations for stand-by server support and throttling. I believe all the other points mentioned by Robert in this thread are addressed by Asif so it would be good to hear about any other concerns that are not addressed. Thanks,-- AhsanThanks & Regards,Rajkumar RaghuwanshiOn Fri, Mar 27, 2020 at 11:04 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Wed, Mar 25, 2020 at 12:22 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,While testing further I observed parallel backup is not able to take backup of standby server.mkdir /tmp/archive_direcho \"archive_mode='on'\">> data/postgresql.confecho \"archive_command='cp %p /tmp/archive_dir/%f'\">> data/postgresql.conf./pg_ctl -D data -l logs start./pg_basebackup -p 5432 -Fp -R -D /tmp/slaveecho \"primary_conninfo='host=127.0.0.1 port=5432 user=edb'\">> /tmp/slave/postgresql.confecho \"restore_command='cp /tmp/archive_dir/%f %p'\">> /tmp/slave/postgresql.confecho \"promote_trigger_file='/tmp/failover.log'\">> /tmp/slave/postgresql.conf./pg_ctl -D /tmp/slave -l /tmp/slave_logs -o \"-p 5433\" start -c [edb@localhost bin]$ ./psql postgres -p 5432 -c \"select pg_is_in_recovery();\" pg_is_in_recovery ------------------- f(1 row)[edb@localhost bin]$ ./psql postgres -p 5433 -c \"select pg_is_in_recovery();\" pg_is_in_recovery ------------------- t(1 row)[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 6pg_basebackup: error: could not list backup files: ERROR:  the standby was promoted during online backupHINT:  This means that the backup being taken is corrupt and should not be used. Try taking another online backup.pg_basebackup: removing data directory \"/tmp/bkp_s\"#same is working fine without parallel backup[edb@localhost bin]$ ./pg_basebackup -p 5433 -D /tmp/bkp_s --jobs 1[edb@localhost bin]$ ls /tmp/bkp_s/PG_VERSION/tmp/bkp_s/PG_VERSIONThanks & Regards,Rajkumar RaghuwanshiOn Thu, Mar 19, 2020 at 4:11 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,In another scenarios, bkp data is corrupted for tablespace. again this is not reproducible everytime,but If I am running the same set of commands I am getting the same error.[edb@localhost bin]$ ./pg_ctl -D data -l logfile startwaiting for server to start.... doneserver started[edb@localhost bin]$ [edb@localhost bin]$ mkdir /tmp/tblsp[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace tblsp location '/tmp/tblsp';\"CREATE TABLESPACE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create database testdb tablespace tblsp;\"CREATE DATABASE[edb@localhost bin]$ ./psql testdb -p 5432 -c \"create table testtbl (a text);\"CREATE TABLE[edb@localhost bin]$ ./psql testdb -p 5432 -c \"insert into testtbl values ('parallel_backup with tablespace');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/bkp -T /tmp/tblsp=/tmp/tblsp_bkp --jobs 2 [edb@localhost bin]$ ./pg_ctl -D /tmp/bkp -l /tmp/bkp_logs -o \"-p 5555\" startwaiting for server to start.... doneserver started[edb@localhost bin]$ ./psql postgres -p 5555 -c \"select * from pg_tablespace where spcname like 'tblsp%' or spcname = 'pg_default'\";  oid  |  spcname   | spcowner | spcacl | spcoptions -------+------------+----------+--------+------------  1663 | pg_default |       10 |        |  16384 | tblsp      |       10 |        | (2 rows)[edb@localhost bin]$ ./psql testdb -p 5555 -c \"select * from testtbl\";psql: error: could not connect to server: FATAL:  \"pg_tblspc/16384/PG_13_202003051/16385\" is not a valid data directoryDETAIL:  File \"pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION\" is missing.[edb@localhost bin]$ [edb@localhost bin]$ ls data/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSIONdata/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION[edb@localhost bin]$ ls /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSIONls: cannot access /tmp/bkp/pg_tblspc/16384/PG_13_202003051/16385/PG_VERSION: No such file or directoryThanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 16, 2020 at 6:19 PM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:Hi Asif,On testing further, I found when taking backup with -R, pg_basebackup crashedthis crash is not consistently reproducible.[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a text);\"CREATE TABLE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test values ('parallel_backup with -R recovery-conf');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -RSegmentation fault (core dumped)stack trace looks the same as it was on earlier reported crash with tablespace.--stack trace[edb@localhost bin]$ gdb -q -c core.37915 pg_basebackup Loaded symbols for /lib64/libnss_files.so.2Core was generated by `./pg_basebackup -p 5432 -j 2 -D /tmp/test_bkp/bkp -R'.Program terminated with signal 11, Segmentation fault.#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:31753175\t\t\t\tbackupinfo->curr = fetchfile->next;Missing separate debuginfos, use: debuginfo-install keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64 libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64(gdb) bt#0  0x00000000004099ee in worker_get_files (wstate=0xc1e458) at pg_basebackup.c:3175#1  0x0000000000408a9e in worker_run (arg=0xc1e458) at pg_basebackup.c:2715#2  0x0000003921a07aa1 in start_thread (arg=0x7f72207c0700) at pthread_create.c:301#3  0x00000039212e8c4d in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:115(gdb) Thanks & Regards,Rajkumar RaghuwanshiOn Mon, Mar 16, 2020 at 2:14 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:Hi Asif, Thanks Rajkumar. I have fixed the above issues and have rebased the patch to the latest master (b7f64c64).(V9 of the patches are attached).I had a further review of the patches and here are my few observations: 1.+/*+ * stop_backup() - ends an online backup+ *+ * The function is called at the end of an online backup. It sends out pg_control+ * file, optionally WAL segments and ending WAL location.+ */Comments seem out-dated.Fixed. 2. With parallel jobs, maxrate is now not supported. Since we are now askingdata in multiple threads throttling seems important here. Can you pleaseexplain why have you disabled that?3. As we are always fetching a single file and as Robert suggested, let renameSEND_FILES to SEND_FILE instead.Yes, we are fetching a single file. However, SEND_FILES is still capable of fetching multiple files in onego, that's why the name.4. Does this work on Windows? I mean does pthread_create() work on Windows?I asked this as I see that pgbench has its own implementation forpthread_create() for WIN32 but this patch doesn't.patch is updated to add support for the Windows platform.5. Typos:tablspace => tablespacesafly => safelyDone. 6. parallel_backup_run() needs some comments explaining the states it goesthrough PB_* states.7. +            case PB_FETCH_REL_FILES:    /* fetch files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_STOP_BACKUP;+                    free_filelist(backupinfo);+                }+                break;+            case PB_FETCH_WAL_FILES:    /* fetch WAL files from server */+                if (backupinfo->activeworkers == 0)+                {+                    backupinfo->backupstate = PB_BACKUP_COMPLETE;+                }+                break;Done. Why free_filelist() is not called in PB_FETCH_WAL_FILES case?Done.The corrupted tablespace and crash, reported by Rajkumar, have been fixed. A pointervariable remained uninitialized which in turn caused the system to misbehave.Attached is the updated set of patches. AFAIK, to complete parallel backup featureset, there remain three sub-features:1- parallel backup does not work with a standby server. In parallel backup, the serverspawns multiple processes and there is no shared state being maintained. So currently,no way to tell multiple processes if the standby was promoted during the backup sincethe START_BACKUP was called.2- throttling. Robert previously suggested that we implement throttling on the client-side.However, I found a previous discussion where it was advocated to be added to thebackend instead[1].So, it was better to have a consensus before moving the throttle function to the client.That’s why for the time being I have disabled it and have asked for suggestions on itto move forward.It seems to me that we have to maintain a shared state in order to support taking backupfrom standby. Also, there is a new feature recently committed for backup progressreporting in the backend (pg_stat_progress_basebackup). This functionality was recentlyadded via this commit ID: e65497df. For parallel backup to update these stats, a sharedstate will be required.Since multiple pg_basebackup can be running at the same time, maintaining a shared statecan become a little complex, unless we disallow taking multiple parallel backups.So proceeding on with this patch, I will be working on:- throttling to be implemented on the client-side.- adding a shared state to handle backup from the standby.[1] https://www.postgresql.org/message-id/flat/521B4B29.20009%402ndquadrant.com#189bf840c87de5908c0b4467d31b50af--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n\n-- Highgo Software (Canada/China/Pakistan)URL : http://www.highgo.caADDR: 10318 WHALLEY BLVD, Surrey, BCEMAIL: mailto: ahsan.hadi@highgo.ca\n\n-- Regards====================================Kashif ZeeshanLead Quality Assurance Engineer / ManagerEnterpriseDB CorporationThe Enterprise Postgres Company", "msg_date": "Thu, 2 Apr 2020 16:29:47 +0500", "msg_from": "Kashif Zeeshan <kashif.zeeshan@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Fri, Mar 27, 2020 at 1:34 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> Yes, we are fetching a single file. However, SEND_FILES is still capable of fetching multiple files in one\n> go, that's why the name.\n\nI don't see why it should work that way. If we're fetching individual\nfiles, why have an unused capability to fetch multiple files?\n\n> 1- parallel backup does not work with a standby server. In parallel backup, the server\n> spawns multiple processes and there is no shared state being maintained. So currently,\n> no way to tell multiple processes if the standby was promoted during the backup since\n> the START_BACKUP was called.\n\nWhy would you need to do that? As long as the process where\nSTOP_BACKUP can do the check, that seems good enough.\n\n> 2- throttling. Robert previously suggested that we implement throttling on the client-side.\n> However, I found a previous discussion where it was advocated to be added to the\n> backend instead[1].\n>\n> So, it was better to have a consensus before moving the throttle function to the client.\n> That’s why for the time being I have disabled it and have asked for suggestions on it\n> to move forward.\n>\n> It seems to me that we have to maintain a shared state in order to support taking backup\n> from standby. Also, there is a new feature recently committed for backup progress\n> reporting in the backend (pg_stat_progress_basebackup). This functionality was recently\n> added via this commit ID: e65497df. For parallel backup to update these stats, a shared\n> state will be required.\n\nI've come around to the view that a shared state is a good idea and\nthat throttling on the server-side makes more sense. I'm not clear on\nwhether we need shared state only for throttling or whether we need it\nfor more than that. Another possible reason might be for the\nprogress-reporting stuff that just got added.\n\n> Since multiple pg_basebackup can be running at the same time, maintaining a shared state\n> can become a little complex, unless we disallow taking multiple parallel backups.\n\nI do not see why it would be necessary to disallow taking multiple\nparallel backups. You just need to have multiple copies of the shared\nstate and a way to decide which one to use for any particular backup.\nI guess that is a little complex, but only a little.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 2 Apr 2020 07:46:51 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Apr 2, 2020 at 7:30 AM Kashif Zeeshan <\nkashif.zeeshan@enterprisedb.com> wrote:\n\n> The backup failed with errors \"error: could not connect to server: could\n> not look up local user ID 1000: Too many open files\" when the\n> max_wal_senders was set to 2000.\n> The errors generated for the workers starting from backup worke=1017.\n>\n\nIt wasn't the fact that you set max_wal_senders to 2000. It was the fact\nthat you specified 1990 parallel workers. By so doing, you overloaded the\nmachine, which is why everything failed. That's to be expected.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\nOn Thu, Apr 2, 2020 at 7:30 AM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:The backup failed with errors \"error: could not connect to server: could not look up local user ID 1000: Too many open files\" when the max_wal_senders was set to 2000. The errors generated for the workers starting from backup worke=1017. It wasn't the fact that you set max_wal_senders to 2000. It was the fact that you specified 1990 parallel workers. By so doing, you overloaded the machine, which is why everything failed. That's to be expected.-- Robert HaasEnterpriseDB: http://www.enterprisedb.comThe Enterprise PostgreSQL Company", "msg_date": "Thu, 2 Apr 2020 07:48:33 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Apr 2, 2020 at 4:48 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Thu, Apr 2, 2020 at 7:30 AM Kashif Zeeshan <\n> kashif.zeeshan@enterprisedb.com> wrote:\n>\n>> The backup failed with errors \"error: could not connect to server: could\n>> not look up local user ID 1000: Too many open files\" when the\n>> max_wal_senders was set to 2000.\n>> The errors generated for the workers starting from backup worke=1017.\n>>\n>\n> It wasn't the fact that you set max_wal_senders to 2000. It was the fact\n> that you specified 1990 parallel workers. By so doing, you overloaded the\n> machine, which is why everything failed. That's to be expected.\n>\n> Thanks alot Robert,\nIn this case the backup folder was not being emptied as the backup was\nfailed, the cleanup should be done in this case too.\n\n\n> --\n> Robert Haas\n> EnterpriseDB: http://www.enterprisedb.com\n> The Enterprise PostgreSQL Company\n>\n\n\n-- \nRegards\n====================================\nKashif Zeeshan\nLead Quality Assurance Engineer / Manager\n\nEnterpriseDB Corporation\nThe Enterprise Postgres Company\n\nOn Thu, Apr 2, 2020 at 4:48 PM Robert Haas <robertmhaas@gmail.com> wrote:On Thu, Apr 2, 2020 at 7:30 AM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:The backup failed with errors \"error: could not connect to server: could not look up local user ID 1000: Too many open files\" when the max_wal_senders was set to 2000. The errors generated for the workers starting from backup worke=1017. It wasn't the fact that you set max_wal_senders to 2000. It was the fact that you specified 1990 parallel workers. By so doing, you overloaded the machine, which is why everything failed. That's to be expected.Thanks alot Robert,In this case the backup folder was not being emptied as the backup was failed, the cleanup should be done in this case too. -- Robert HaasEnterpriseDB: http://www.enterprisedb.comThe Enterprise PostgreSQL Company\n-- Regards====================================Kashif ZeeshanLead Quality Assurance Engineer / ManagerEnterpriseDB CorporationThe Enterprise Postgres Company", "msg_date": "Thu, 2 Apr 2020 16:54:49 +0500", "msg_from": "Kashif Zeeshan <kashif.zeeshan@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Apr 2, 2020 at 7:55 AM Kashif Zeeshan\n<kashif.zeeshan@enterprisedb.com> wrote:\n> Thanks alot Robert,\n> In this case the backup folder was not being emptied as the backup was failed, the cleanup should be done in this case too.\n\nDoes it fail to clean up the backup folder in all cases where the\nbackup failed, or just in this case?\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 2 Apr 2020 09:23:21 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Apr 2, 2020 at 6:23 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Thu, Apr 2, 2020 at 7:55 AM Kashif Zeeshan\n> <kashif.zeeshan@enterprisedb.com> wrote:\n> > Thanks alot Robert,\n> > In this case the backup folder was not being emptied as the backup was\n> failed, the cleanup should be done in this case too.\n>\n> Does it fail to clean up the backup folder in all cases where the\n> backup failed, or just in this case?\n>\nThe cleanup is done in the cases I have seen so far with base pg_basebackup\nfunctionality (not including the parallel backup feature) with the message\n\"pg_basebackup: removing contents of data directory\"\nA similar case was also fixed for parallel backup reported by Rajkumar\nwhere the contents of the backup folder were not cleaned up after the error.\n\n>\n> --\n> Robert Haas\n> EnterpriseDB: http://www.enterprisedb.com\n> The Enterprise PostgreSQL Company\n>\n\n\n-- \nRegards\n====================================\nKashif Zeeshan\nLead Quality Assurance Engineer / Manager\n\nEnterpriseDB Corporation\nThe Enterprise Postgres Company\n\nOn Thu, Apr 2, 2020 at 6:23 PM Robert Haas <robertmhaas@gmail.com> wrote:On Thu, Apr 2, 2020 at 7:55 AM Kashif Zeeshan\n<kashif.zeeshan@enterprisedb.com> wrote:\n> Thanks alot Robert,\n> In this case the backup folder was not being emptied as the backup was failed, the cleanup should be done in this case too.\n\nDoes it fail to clean up the backup folder in all cases where the\nbackup failed, or just in this case?The cleanup is done in the cases I have seen so far with base pg_basebackup functionality (not including the parallel backup feature) with the message \"pg_basebackup: removing contents of data directory\" A similar case was also fixed for parallel backup reported by Rajkumar where the contents of the backup folder were not cleaned up after the error.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n-- Regards====================================Kashif ZeeshanLead Quality Assurance Engineer / ManagerEnterpriseDB CorporationThe Enterprise Postgres Company", "msg_date": "Thu, 2 Apr 2020 18:46:15 +0500", "msg_from": "Kashif Zeeshan <kashif.zeeshan@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Apr 2, 2020 at 9:46 AM Kashif Zeeshan <\nkashif.zeeshan@enterprisedb.com> wrote:\n\n> Does it fail to clean up the backup folder in all cases where the\n>> backup failed, or just in this case?\n>>\n> The cleanup is done in the cases I have seen so far with base\n> pg_basebackup functionality (not including the parallel backup feature)\n> with the message \"pg_basebackup: removing contents of data directory\"\n> A similar case was also fixed for parallel backup reported by Rajkumar\n> where the contents of the backup folder were not cleaned up after the error.\n>\n\nWhat I'm saying is that it's unclear whether there's a bug here or whether\nit just failed because of the very extreme test scenario you created.\nSpawning >1000 processes on a small machine can easily make a lot of things\nfail.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\nOn Thu, Apr 2, 2020 at 9:46 AM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:Does it fail to clean up the backup folder in all cases where the\nbackup failed, or just in this case?The cleanup is done in the cases I have seen so far with base pg_basebackup functionality (not including the parallel backup feature) with the message \"pg_basebackup: removing contents of data directory\" A similar case was also fixed for parallel backup reported by Rajkumar where the contents of the backup folder were not cleaned up after the error.What I'm saying is that it's unclear whether there's a bug here or whether it just failed because of the very extreme test scenario you created. Spawning >1000 processes on a small machine can easily make a lot of things fail. -- Robert HaasEnterpriseDB: http://www.enterprisedb.comThe Enterprise PostgreSQL Company", "msg_date": "Thu, 2 Apr 2020 10:20:15 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Apr 2, 2020 at 4:47 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Fri, Mar 27, 2020 at 1:34 PM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n> > Yes, we are fetching a single file. However, SEND_FILES is still capable\n> of fetching multiple files in one\n> > go, that's why the name.\n>\n> I don't see why it should work that way. If we're fetching individual\n> files, why have an unused capability to fetch multiple files?\n>\n\nOkay will rename and will modify the function to send a single file as well.\n\n\n> > 1- parallel backup does not work with a standby server. In parallel\n> backup, the server\n> > spawns multiple processes and there is no shared state being maintained.\n> So currently,\n> > no way to tell multiple processes if the standby was promoted during the\n> backup since\n> > the START_BACKUP was called.\n>\n> Why would you need to do that? As long as the process where\n> STOP_BACKUP can do the check, that seems good enough.\n>\n\n\nYes, but the user will get the error only after the STOP_BACKUP, not while\nthe backup is\nin progress. So if the backup is a large one, early error detection would\nbe much beneficial.\nThis is the current behavior of non-parallel backup as well.\n\n\n>\n> > 2- throttling. Robert previously suggested that we implement throttling\n> on the client-side.\n> > However, I found a previous discussion where it was advocated to be\n> added to the\n> > backend instead[1].\n> >\n> > So, it was better to have a consensus before moving the throttle\n> function to the client.\n> > That’s why for the time being I have disabled it and have asked for\n> suggestions on it\n> > to move forward.\n> >\n> > It seems to me that we have to maintain a shared state in order to\n> support taking backup\n> > from standby. Also, there is a new feature recently committed for backup\n> progress\n> > reporting in the backend (pg_stat_progress_basebackup). This\n> functionality was recently\n> > added via this commit ID: e65497df. For parallel backup to update these\n> stats, a shared\n> > state will be required.\n>\n> I've come around to the view that a shared state is a good idea and\n> that throttling on the server-side makes more sense. I'm not clear on\n> whether we need shared state only for throttling or whether we need it\n> for more than that. Another possible reason might be for the\n> progress-reporting stuff that just got added.\n>\n\nOkay, then I will add the shared state. And since we are adding the shared\nstate, we can use\nthat for throttling, progress-reporting and standby early error checking.\n\n\n> > Since multiple pg_basebackup can be running at the same time,\n> maintaining a shared state\n> > can become a little complex, unless we disallow taking multiple parallel\n> backups.\n>\n> I do not see why it would be necessary to disallow taking multiple\n> parallel backups. You just need to have multiple copies of the shared\n> state and a way to decide which one to use for any particular backup.\n> I guess that is a little complex, but only a little.\n>\n\nThere are two possible options:\n\n(1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n(2) (Preferred Option) Use the WAL start location as the BackupID.\n\n\nThis BackupID should be given back as a response to start backup command.\nAll client workers\n\nmust append this ID to all parallel backup replication commands. So that we\ncan use this identifier\n\nto search for that particular backup. Does that sound good?\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nOn Thu, Apr 2, 2020 at 4:47 PM Robert Haas <robertmhaas@gmail.com> wrote:On Fri, Mar 27, 2020 at 1:34 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> Yes, we are fetching a single file. However, SEND_FILES is still capable of fetching multiple files in one\n> go, that's why the name.\n\nI don't see why it should work that way. If we're fetching individual\nfiles, why have an unused capability to fetch multiple files?Okay will rename and will modify the function to send a single file as well.\n\n> 1- parallel backup does not work with a standby server. In parallel backup, the server\n> spawns multiple processes and there is no shared state being maintained. So currently,\n> no way to tell multiple processes if the standby was promoted during the backup since\n> the START_BACKUP was called.\n\nWhy would you need to do that? As long as the process where\nSTOP_BACKUP can do the check, that seems good enough.Yes, but the user will get the error only after the STOP_BACKUP, not while the backup isin progress. So if the backup is a large one, early error detection would be much beneficial.This is the current behavior of non-parallel backup as well. \n\n> 2- throttling. Robert previously suggested that we implement throttling on the client-side.\n> However, I found a previous discussion where it was advocated to be added to the\n> backend instead[1].\n>\n> So, it was better to have a consensus before moving the throttle function to the client.\n> That’s why for the time being I have disabled it and have asked for suggestions on it\n> to move forward.\n>\n> It seems to me that we have to maintain a shared state in order to support taking backup\n> from standby. Also, there is a new feature recently committed for backup progress\n> reporting in the backend (pg_stat_progress_basebackup). This functionality was recently\n> added via this commit ID: e65497df. For parallel backup to update these stats, a shared\n> state will be required.\n\nI've come around to the view that a shared state is a good idea and\nthat throttling on the server-side makes more sense. I'm not clear on\nwhether we need shared state only for throttling or whether we need it\nfor more than that. Another possible reason might be for the\nprogress-reporting stuff that just got added.Okay, then I will add the shared state. And since we are adding the shared state, we can usethat for throttling, progress-reporting and standby early error checking.\n\n> Since multiple pg_basebackup can be running at the same time, maintaining a shared state\n> can become a little complex, unless we disallow taking multiple parallel backups.\n\nI do not see why it would be necessary to disallow taking multiple\nparallel backups. You just need to have multiple copies of the shared\nstate and a way to decide which one to use for any particular backup.\nI guess that is a little complex, but only a little.There are two possible options:(1) Server may generate a unique ID i.e. BackupID=<unique_string> OR(2) (Preferred Option) Use the WAL start location as the BackupID.This BackupID should be given back as a response to start backup command. All client workersmust append this ID to all parallel backup replication commands. So that we can use this identifierto search for that particular backup. Does that sound good?  --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Thu, 2 Apr 2020 20:16:57 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>> Why would you need to do that? As long as the process where\n>> STOP_BACKUP can do the check, that seems good enough.\n>\n> Yes, but the user will get the error only after the STOP_BACKUP, not while the backup is\n> in progress. So if the backup is a large one, early error detection would be much beneficial.\n> This is the current behavior of non-parallel backup as well.\n\nBecause non-parallel backup does not feature early detection of this\nerror, it is not necessary to make parallel backup do so. Indeed, it\nis undesirable. If you want to fix that problem, do it on a separate\nthread in a separate patch. A patch proposing to make parallel backup\ninconsistent in behavior with non-parallel backup will be rejected, at\nleast if I have anything to say about it.\n\nTBH, fixing this doesn't seem like an urgent problem to me. The\ncurrent situation is not great, but promotions ought to be relatively\ninfrequent, so I'm not sure it's a huge problem in practice. It is\nalso worth considering whether the right fix is to figure out how to\nmake that case actually work, rather than just making it fail quicker.\nI don't currently understand the reason for the prohibition so I can't\nexpress an intelligent opinion on what the right answer is here, but\nit seems like it ought to be investigated before somebody goes and\nbuilds a bunch of infrastructure to make the error more timely.\n\n> Okay, then I will add the shared state. And since we are adding the shared state, we can use\n> that for throttling, progress-reporting and standby early error checking.\n\nPlease propose a grammar here for all the new replication commands you\nplan to add before going and implement everything. That will make it\neasier to hash out the design without forcing you to keep changing the\ncode. Your design should include a sketch of how several sets of\ncoordinating backends taking several concurrent parallel backups will\nend up with one shared state per parallel backup.\n\n> There are two possible options:\n>\n> (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n> (2) (Preferred Option) Use the WAL start location as the BackupID.\n>\n> This BackupID should be given back as a response to start backup command. All client workers\n> must append this ID to all parallel backup replication commands. So that we can use this identifier\n> to search for that particular backup. Does that sound good?\n\nUsing the WAL start location as the backup ID seems like it might be\nproblematic -- could a single checkpoint not end up as the start\nlocation for multiple backups started at the same time? Whether that's\npossible now or not, it seems unwise to hard-wire that assumption into\nthe wire protocol.\n\nI was thinking that perhaps the client should generate a unique backup\nID, e.g. leader does:\n\nSTART_BACKUP unique_backup_id [options]...\n\nAnd then others do:\n\nJOIN_BACKUP unique_backup_id\n\nMy thought is that you will have a number of shared memory structure\nequal to max_wal_senders, each one large enough to hold the shared\nstate for one backup. The shared state will include\nchar[NAMEDATALEN-or-something] which will be used to hold the backup\nID. START_BACKUP would allocate one and copy the name into it;\nJOIN_BACKUP would search for one by name.\n\nIf you want to generate the name on the server side, then I suppose\nSTART_BACKUP would return a result set that includes the backup ID,\nand clients would have to specify that same backup ID when invoking\nJOIN_BACKUP. The rest would stay the same. I am not sure which way is\nbetter. Either way, the backup ID should be something long and hard to\nguess, not e.g. the leader processes' PID. I think we should generate\nit using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\nresult to get a string. That way there's almost no risk of two backup\nIDs colliding accidentally, and even if we somehow had a malicious\nuser trying to screw up somebody else's parallel backup by choosing a\ncolliding backup ID, it would be pretty hard to have any success. A\nuser with enough access to do that sort of thing can probably cause a\nlot worse problems anyway, but it seems pretty easy to guard against\nintentional collisions robustly here, so I think we should.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 2 Apr 2020 11:44:59 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n> >> Why would you need to do that? As long as the process where\n> >> STOP_BACKUP can do the check, that seems good enough.\n> >\n> > Yes, but the user will get the error only after the STOP_BACKUP, not\n> while the backup is\n> > in progress. So if the backup is a large one, early error detection\n> would be much beneficial.\n> > This is the current behavior of non-parallel backup as well.\n>\n> Because non-parallel backup does not feature early detection of this\n> error, it is not necessary to make parallel backup do so. Indeed, it\n> is undesirable. If you want to fix that problem, do it on a separate\n> thread in a separate patch. A patch proposing to make parallel backup\n> inconsistent in behavior with non-parallel backup will be rejected, at\n> least if I have anything to say about it.\n>\n> TBH, fixing this doesn't seem like an urgent problem to me. The\n> current situation is not great, but promotions ought to be relatively\n> infrequent, so I'm not sure it's a huge problem in practice. It is\n> also worth considering whether the right fix is to figure out how to\n> make that case actually work, rather than just making it fail quicker.\n> I don't currently understand the reason for the prohibition so I can't\n> express an intelligent opinion on what the right answer is here, but\n> it seems like it ought to be investigated before somebody goes and\n> builds a bunch of infrastructure to make the error more timely.\n>\n\nNon-parallel backup already does the early error checking. I only intended\n\nto make parallel behave the same as non-parallel here. So, I agree with\n\nyou that the behavior of parallel backup should be consistent with the\n\nnon-parallel one. Please see the code snippet below from\n\nbasebackup.c:sendDir()\n\n\n/*\n>\n> * Check if the postmaster has signaled us to exit, and abort with an\n>\n> * error in that case. The error handler further up will call\n>\n> * do_pg_abort_backup() for us. Also check that if the backup was\n>\n> * started while still in recovery, the server wasn't promoted.\n>\n> * do_pg_stop_backup() will check that too, but it's better to stop\n>\n> * the backup early than continue to the end and fail there.\n>\n> */\n>\n> CHECK_FOR_INTERRUPTS();\n>\n> *if* (RecoveryInProgress() != backup_started_in_recovery)\n>\n> ereport(ERROR,\n>\n> (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n>\n> errmsg(\"the standby was promoted during online backup\"),\n>\n> errhint(\"This means that the backup being taken is corrupt \"\n>\n> \"and should not be used. \"\n>\n> \"Try taking another online backup.\")));\n>\n>\n> > Okay, then I will add the shared state. And since we are adding the\n> shared state, we can use\n> > that for throttling, progress-reporting and standby early error checking.\n>\n> Please propose a grammar here for all the new replication commands you\n> plan to add before going and implement everything. That will make it\n> easier to hash out the design without forcing you to keep changing the\n> code. Your design should include a sketch of how several sets of\n> coordinating backends taking several concurrent parallel backups will\n> end up with one shared state per parallel backup.\n>\n> > There are two possible options:\n> >\n> > (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n> > (2) (Preferred Option) Use the WAL start location as the BackupID.\n> >\n> > This BackupID should be given back as a response to start backup\n> command. All client workers\n> > must append this ID to all parallel backup replication commands. So that\n> we can use this identifier\n> > to search for that particular backup. Does that sound good?\n>\n> Using the WAL start location as the backup ID seems like it might be\n> problematic -- could a single checkpoint not end up as the start\n> location for multiple backups started at the same time? Whether that's\n> possible now or not, it seems unwise to hard-wire that assumption into\n> the wire protocol.\n>\n> I was thinking that perhaps the client should generate a unique backup\n> ID, e.g. leader does:\n>\n> START_BACKUP unique_backup_id [options]...\n>\n> And then others do:\n>\n> JOIN_BACKUP unique_backup_id\n>\n> My thought is that you will have a number of shared memory structure\n> equal to max_wal_senders, each one large enough to hold the shared\n> state for one backup. The shared state will include\n> char[NAMEDATALEN-or-something] which will be used to hold the backup\n> ID. START_BACKUP would allocate one and copy the name into it;\n> JOIN_BACKUP would search for one by name.\n>\n> If you want to generate the name on the server side, then I suppose\n> START_BACKUP would return a result set that includes the backup ID,\n> and clients would have to specify that same backup ID when invoking\n> JOIN_BACKUP. The rest would stay the same. I am not sure which way is\n> better. Either way, the backup ID should be something long and hard to\n> guess, not e.g. the leader processes' PID. I think we should generate\n> it using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\n> result to get a string. That way there's almost no risk of two backup\n> IDs colliding accidentally, and even if we somehow had a malicious\n> user trying to screw up somebody else's parallel backup by choosing a\n> colliding backup ID, it would be pretty hard to have any success. A\n> user with enough access to do that sort of thing can probably cause a\n> lot worse problems anyway, but it seems pretty easy to guard against\n> intentional collisions robustly here, so I think we should.\n>\n>\nOkay so If we are to add another replication command ‘JOIN_BACKUP\nunique_backup_id’\nto make workers find the relevant shared state. There won't be any need for\nchanging\nthe grammar for any other command. The START_BACKUP can return the\nunique_backup_id\nin the result set.\n\nI am thinking of the following struct for shared state:\n\n> *typedef* *struct*\n>\n> {\n>\n> *char* backupid[NAMEDATALEN];\n>\n> XLogRecPtr startptr;\n>\n>\n> slock_t lock;\n>\n> int64 throttling_counter;\n>\n> *bool* backup_started_in_recovery;\n>\n> } BackupSharedState;\n>\n>\nThe shared state structure entries would be maintained by a shared hash\ntable.\nThere will be one structure per parallel backup. Since a single parallel\nbackup\ncan engage more than one wal sender, so I think max_wal_senders might be a\nlittle\ntoo much; perhaps max_wal_senders/2 since there will be at least 2\nconnections\nper parallel backup? Alternatively, we can set a new GUC that defines the\nmaximum\nnumber of for concurrent parallel backups i.e.\n‘max_concurent_backups_allowed = 10’\nperhaps, or we can make it user-configurable.\n\nThe key would be “backupid=hex_encode(pg_random_strong(16))”\n\nChecking for Standby Promotion:\nAt the START_BACKUP command, we initialize\nBackupSharedState.backup_started_in_recovery\nand keep checking it whenever send_file () is called to send a new file.\n\nThrottling:\nBackupSharedState.throttling_counter - The throttling logic remains the same\nas for non-parallel backup with the exception that multiple threads will\nnow be\nupdating it. So in parallel backup, this will represent the overall bytes\nthat\nhave been transferred. So the workers would sleep if they have exceeded the\nlimit. Hence, the shared state carries a lock to safely update the\nthrottling\nvalue atomically.\n\nProgress Reporting:\nAlthough I think we should add progress-reporting for parallel backup as a\nseparate patch. The relevant entries for progress-reporting such as\n‘backup_total’ and ‘backup_streamed’ would be then added to this structure\nas well.\n\n\nGrammar:\nThere is a change in the resultset being returned for START_BACKUP command;\nunique_backup_id is added. Additionally, JOIN_BACKUP replication command is\nadded. SEND_FILES has been renamed to SEND_FILE. There are no other changes\nto the grammar.\n\nSTART_BACKUP [LABEL '<label>'] [FAST]\n - returns startptr, tli, backup_label, unique_backup_id\nSTOP_BACKUP [NOWAIT]\n - returns startptr, tli, backup_label\nJOIN_BACKUP ‘unique_backup_id’\n - attaches a shared state identified by ‘unique_backup_id’ to a backend\nprocess.\n\nLIST_TABLESPACES [PROGRESS]\nLIST_FILES [TABLESPACE]\nLIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\nSEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nOn Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com> wrote:On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>> Why would you need to do that? As long as the process where\n>> STOP_BACKUP can do the check, that seems good enough.\n>\n> Yes, but the user will get the error only after the STOP_BACKUP, not while the backup is\n> in progress. So if the backup is a large one, early error detection would be much beneficial.\n> This is the current behavior of non-parallel backup as well.\n\nBecause non-parallel backup does not feature early detection of this\nerror, it is not necessary to make parallel backup do so. Indeed, it\nis undesirable. If you want to fix that problem, do it on a separate\nthread in a separate patch. A patch proposing to make parallel backup\ninconsistent in behavior with non-parallel backup will be rejected, at\nleast if I have anything to say about it.\n\nTBH, fixing this doesn't seem like an urgent problem to me. The\ncurrent situation is not great, but promotions ought to be relatively\ninfrequent, so I'm not sure it's a huge problem in practice. It is\nalso worth considering whether the right fix is to figure out how to\nmake that case actually work, rather than just making it fail quicker.\nI don't currently understand the reason for the prohibition so I can't\nexpress an intelligent opinion on what the right answer is here, but\nit seems like it ought to be investigated before somebody goes and\nbuilds a bunch of infrastructure to make the error more timely.Non-parallel backup already does the early error checking. I only intendedto make parallel behave the same as non-parallel here. So, I agree withyou that the behavior of parallel backup should be consistent with thenon-parallel one.  Please see the code snippet below from basebackup.c:sendDir()/*\n * Check if the postmaster has signaled us to exit, and abort with an\n * error in that case. The error handler further up will call\n * do_pg_abort_backup() for us. Also check that if the backup was\n * started while still in recovery, the server wasn't promoted.\n * do_pg_stop_backup() will check that too, but it's better to stop\n * the backup early than continue to the end and fail there.\n */\nCHECK_FOR_INTERRUPTS();\nif (RecoveryInProgress() != backup_started_in_recovery)\n ereport(ERROR,\n (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n errmsg(\"the standby was promoted during online backup\"),\n errhint(\"This means that the backup being taken is corrupt \"\n \"and should not be used. \"\n \"Try taking another online backup.\"))); \n\n> Okay, then I will add the shared state. And since we are adding the shared state, we can use\n> that for throttling, progress-reporting and standby early error checking.\n\nPlease propose a grammar here for all the new replication commands you\nplan to add before going and implement everything. That will make it\neasier to hash out the design without forcing you to keep changing the\ncode. Your design should include a sketch of how several sets of\ncoordinating backends taking several concurrent parallel backups will\nend up with one shared state per parallel backup.\n\n> There are two possible options:\n>\n> (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n> (2) (Preferred Option) Use the WAL start location as the BackupID.\n>\n> This BackupID should be given back as a response to start backup command. All client workers\n> must append this ID to all parallel backup replication commands. So that we can use this identifier\n> to search for that particular backup. Does that sound good?\n\nUsing the WAL start location as the backup ID seems like it might be\nproblematic -- could a single checkpoint not end up as the start\nlocation for multiple backups started at the same time? Whether that's\npossible now or not, it seems unwise to hard-wire that assumption into\nthe wire protocol.\n\nI was thinking that perhaps the client should generate a unique backup\nID, e.g. leader does:\n\nSTART_BACKUP unique_backup_id [options]...\n\nAnd then others do:\n\nJOIN_BACKUP unique_backup_id\n\nMy thought is that you will have a number of shared memory structure\nequal to max_wal_senders, each one large enough to hold the shared\nstate for one backup. The shared state will include\nchar[NAMEDATALEN-or-something] which will be used to hold the backup\nID. START_BACKUP would allocate one and copy the name into it;\nJOIN_BACKUP would search for one by name.\n\nIf you want to generate the name on the server side, then I suppose\nSTART_BACKUP would return a result set that includes the backup ID,\nand clients would have to specify that same backup ID when invoking\nJOIN_BACKUP. The rest would stay the same. I am not sure which way is\nbetter. Either way, the backup ID should be something long and hard to\nguess, not e.g. the leader processes' PID. I think we should generate\nit using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\nresult to get a string. That way there's almost no risk of two backup\nIDs colliding accidentally, and even if we somehow had a malicious\nuser trying to screw up somebody else's parallel backup by choosing a\ncolliding backup ID, it would be pretty hard to have any success. A\nuser with enough access to do that sort of thing can probably cause a\nlot worse problems anyway, but it seems pretty easy to guard against\nintentional collisions robustly here, so I think we should.\nOkay so If we are to add another replication command ‘JOIN_BACKUP unique_backup_id’to make workers find the relevant shared state. There won't be any need for changingthe grammar for any other command. The START_BACKUP can return the unique_backup_idin the result set.I am thinking of the following struct for shared state:typedef struct\n{\n char backupid[NAMEDATALEN];\n XLogRecPtr startptr;\n\n slock_t lock;\n int64 throttling_counter;\n bool backup_started_in_recovery;\n} BackupSharedState;The shared state structure entries would be maintained by a shared hash table.There will be one structure per parallel backup. Since a single parallel backupcan engage more than one wal sender, so I think max_wal_senders might be a littletoo much; perhaps max_wal_senders/2 since there will be at least 2 connectionsper parallel backup? Alternatively, we can set a new GUC that defines the maximumnumber of for concurrent parallel backups i.e. ‘max_concurent_backups_allowed = 10’ perhaps, or we can make it user-configurable.The key would be “backupid=hex_encode(pg_random_strong(16))”Checking for Standby Promotion:At the START_BACKUP command, we initialize BackupSharedState.backup_started_in_recovery and keep checking it whenever send_file () is called to send a new file.Throttling:BackupSharedState.throttling_counter - The throttling logic remains the sameas for non-parallel backup with the exception that multiple threads will now beupdating it. So in parallel backup, this will represent the overall bytes thathave been transferred. So the workers would sleep if they have exceeded thelimit. Hence, the shared state carries a lock to safely update the throttlingvalue atomically. Progress Reporting:Although I think we should add progress-reporting for parallel backup as aseparate patch. The relevant entries for progress-reporting such as ‘backup_total’ and ‘backup_streamed’ would be then added to this structureas well.  Grammar:There is a change in the resultset being returned for START_BACKUP command; unique_backup_id is added. Additionally, JOIN_BACKUP replication command isadded. SEND_FILES has been renamed to SEND_FILE. There are no other changesto the grammar.START_BACKUP [LABEL '<label>'] [FAST]  - returns startptr, tli, backup_label, unique_backup_idSTOP_BACKUP [NOWAIT]  - returns startptr, tli, backup_labelJOIN_BACKUP ‘unique_backup_id’  - attaches a shared state identified by ‘unique_backup_id’ to a backend process. LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Fri, 3 Apr 2020 13:45:23 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif\n\nWhen a non-existent slot is used with tablespace then correct error is\ndisplayed but then the backup folder is not cleaned and leaves a corrupt\nbackup.\n\nSteps\n=======\n\nedb@localhost bin]$\n[edb@localhost bin]$ mkdir /home/edb/tbl1\n[edb@localhost bin]$ mkdir /home/edb/tbl_res\n[edb@localhost bin]$\npostgres=# create tablespace tbl1 location '/home/edb/tbl1';\nCREATE TABLESPACE\npostgres=#\npostgres=# create table t1 (a int) tablespace tbl1;\nCREATE TABLE\npostgres=# insert into t1 values(100);\nINSERT 0 1\npostgres=# insert into t1 values(200);\nINSERT 0 1\npostgres=# insert into t1 values(300);\nINSERT 0 1\npostgres=#\n\n\n[edb@localhost bin]$\n[edb@localhost bin]$ ./pg_basebackup -v -j 2 -D /home/edb/Desktop/backup/\n-T /home/edb/tbl1=/home/edb/tbl_res -S test\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: error: could not send replication command\n\"START_REPLICATION\": ERROR: replication slot \"test\" does not exist\npg_basebackup: backup worker (0) created\npg_basebackup: backup worker (1) created\npg_basebackup: write-ahead log end point: 0/2E000100\npg_basebackup: waiting for background process to finish streaming ...\npg_basebackup: error: child thread exited with error 1\n[edb@localhost bin]$\n\nbackup folder not cleaned\n\n[edb@localhost bin]$\n[edb@localhost bin]$\n[edb@localhost bin]$\n[edb@localhost bin]$ ls /home/edb/Desktop/backup\nbackup_label global pg_dynshmem pg_ident.conf pg_multixact\n pg_replslot pg_snapshots pg_stat_tmp pg_tblspc PG_VERSION pg_xact\n postgresql.conf\nbase pg_commit_ts pg_hba.conf pg_logical pg_notify\npg_serial pg_stat pg_subtrans pg_twophase pg_wal\n postgresql.auto.conf\n[edb@localhost bin]$\n\n\n\n\nIf the same case is executed without the parallel backup patch then the\nbackup folder is cleaned after the error is displayed.\n\n[edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/ -T\n/home/edb/tbl1=/home/edb/tbl_res -S test999\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: error: could not send replication command\n\"START_REPLICATION\": ERROR: replication slot \"test999\" does not exist\npg_basebackup: write-ahead log end point: 0/2B000100\npg_basebackup: waiting for background process to finish streaming ...\npg_basebackup: error: child process exited with exit code 1\n*pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"*\npg_basebackup: changes to tablespace directories will not be undone\n\n\nOn Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n>> On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>> >> Why would you need to do that? As long as the process where\n>> >> STOP_BACKUP can do the check, that seems good enough.\n>> >\n>> > Yes, but the user will get the error only after the STOP_BACKUP, not\n>> while the backup is\n>> > in progress. So if the backup is a large one, early error detection\n>> would be much beneficial.\n>> > This is the current behavior of non-parallel backup as well.\n>>\n>> Because non-parallel backup does not feature early detection of this\n>> error, it is not necessary to make parallel backup do so. Indeed, it\n>> is undesirable. If you want to fix that problem, do it on a separate\n>> thread in a separate patch. A patch proposing to make parallel backup\n>> inconsistent in behavior with non-parallel backup will be rejected, at\n>> least if I have anything to say about it.\n>>\n>> TBH, fixing this doesn't seem like an urgent problem to me. The\n>> current situation is not great, but promotions ought to be relatively\n>> infrequent, so I'm not sure it's a huge problem in practice. It is\n>> also worth considering whether the right fix is to figure out how to\n>> make that case actually work, rather than just making it fail quicker.\n>> I don't currently understand the reason for the prohibition so I can't\n>> express an intelligent opinion on what the right answer is here, but\n>> it seems like it ought to be investigated before somebody goes and\n>> builds a bunch of infrastructure to make the error more timely.\n>>\n>\n> Non-parallel backup already does the early error checking. I only intended\n>\n> to make parallel behave the same as non-parallel here. So, I agree with\n>\n> you that the behavior of parallel backup should be consistent with the\n>\n> non-parallel one. Please see the code snippet below from\n>\n> basebackup.c:sendDir()\n>\n>\n> /*\n>>\n>> * Check if the postmaster has signaled us to exit, and abort with an\n>>\n>> * error in that case. The error handler further up will call\n>>\n>> * do_pg_abort_backup() for us. Also check that if the backup was\n>>\n>> * started while still in recovery, the server wasn't promoted.\n>>\n>> * do_pg_stop_backup() will check that too, but it's better to stop\n>>\n>> * the backup early than continue to the end and fail there.\n>>\n>> */\n>>\n>> CHECK_FOR_INTERRUPTS();\n>>\n>> *if* (RecoveryInProgress() != backup_started_in_recovery)\n>>\n>> ereport(ERROR,\n>>\n>> (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n>>\n>> errmsg(\"the standby was promoted during online backup\"),\n>>\n>> errhint(\"This means that the backup being taken is corrupt \"\n>>\n>> \"and should not be used. \"\n>>\n>> \"Try taking another online backup.\")));\n>>\n>>\n>> > Okay, then I will add the shared state. And since we are adding the\n>> shared state, we can use\n>> > that for throttling, progress-reporting and standby early error\n>> checking.\n>>\n>> Please propose a grammar here for all the new replication commands you\n>> plan to add before going and implement everything. That will make it\n>> easier to hash out the design without forcing you to keep changing the\n>> code. Your design should include a sketch of how several sets of\n>> coordinating backends taking several concurrent parallel backups will\n>> end up with one shared state per parallel backup.\n>>\n>> > There are two possible options:\n>> >\n>> > (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n>> > (2) (Preferred Option) Use the WAL start location as the BackupID.\n>> >\n>> > This BackupID should be given back as a response to start backup\n>> command. All client workers\n>> > must append this ID to all parallel backup replication commands. So\n>> that we can use this identifier\n>> > to search for that particular backup. Does that sound good?\n>>\n>> Using the WAL start location as the backup ID seems like it might be\n>> problematic -- could a single checkpoint not end up as the start\n>> location for multiple backups started at the same time? Whether that's\n>> possible now or not, it seems unwise to hard-wire that assumption into\n>> the wire protocol.\n>>\n>> I was thinking that perhaps the client should generate a unique backup\n>> ID, e.g. leader does:\n>>\n>> START_BACKUP unique_backup_id [options]...\n>>\n>> And then others do:\n>>\n>> JOIN_BACKUP unique_backup_id\n>>\n>> My thought is that you will have a number of shared memory structure\n>> equal to max_wal_senders, each one large enough to hold the shared\n>> state for one backup. The shared state will include\n>> char[NAMEDATALEN-or-something] which will be used to hold the backup\n>> ID. START_BACKUP would allocate one and copy the name into it;\n>> JOIN_BACKUP would search for one by name.\n>>\n>> If you want to generate the name on the server side, then I suppose\n>> START_BACKUP would return a result set that includes the backup ID,\n>> and clients would have to specify that same backup ID when invoking\n>> JOIN_BACKUP. The rest would stay the same. I am not sure which way is\n>> better. Either way, the backup ID should be something long and hard to\n>> guess, not e.g. the leader processes' PID. I think we should generate\n>> it using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\n>> result to get a string. That way there's almost no risk of two backup\n>> IDs colliding accidentally, and even if we somehow had a malicious\n>> user trying to screw up somebody else's parallel backup by choosing a\n>> colliding backup ID, it would be pretty hard to have any success. A\n>> user with enough access to do that sort of thing can probably cause a\n>> lot worse problems anyway, but it seems pretty easy to guard against\n>> intentional collisions robustly here, so I think we should.\n>>\n>>\n> Okay so If we are to add another replication command ‘JOIN_BACKUP\n> unique_backup_id’\n> to make workers find the relevant shared state. There won't be any need\n> for changing\n> the grammar for any other command. The START_BACKUP can return the\n> unique_backup_id\n> in the result set.\n>\n> I am thinking of the following struct for shared state:\n>\n>> *typedef* *struct*\n>>\n>> {\n>>\n>> *char* backupid[NAMEDATALEN];\n>>\n>> XLogRecPtr startptr;\n>>\n>>\n>> slock_t lock;\n>>\n>> int64 throttling_counter;\n>>\n>> *bool* backup_started_in_recovery;\n>>\n>> } BackupSharedState;\n>>\n>>\n> The shared state structure entries would be maintained by a shared hash\n> table.\n> There will be one structure per parallel backup. Since a single parallel\n> backup\n> can engage more than one wal sender, so I think max_wal_senders might be a\n> little\n> too much; perhaps max_wal_senders/2 since there will be at least 2\n> connections\n> per parallel backup? Alternatively, we can set a new GUC that defines the\n> maximum\n> number of for concurrent parallel backups i.e.\n> ‘max_concurent_backups_allowed = 10’\n> perhaps, or we can make it user-configurable.\n>\n> The key would be “backupid=hex_encode(pg_random_strong(16))”\n>\n> Checking for Standby Promotion:\n> At the START_BACKUP command, we initialize\n> BackupSharedState.backup_started_in_recovery\n> and keep checking it whenever send_file () is called to send a new file.\n>\n> Throttling:\n> BackupSharedState.throttling_counter - The throttling logic remains the\n> same\n> as for non-parallel backup with the exception that multiple threads will\n> now be\n> updating it. So in parallel backup, this will represent the overall bytes\n> that\n> have been transferred. So the workers would sleep if they have exceeded the\n> limit. Hence, the shared state carries a lock to safely update the\n> throttling\n> value atomically.\n>\n> Progress Reporting:\n> Although I think we should add progress-reporting for parallel backup as a\n> separate patch. The relevant entries for progress-reporting such as\n> ‘backup_total’ and ‘backup_streamed’ would be then added to this structure\n> as well.\n>\n>\n> Grammar:\n> There is a change in the resultset being returned for START_BACKUP\n> command;\n> unique_backup_id is added. Additionally, JOIN_BACKUP replication command is\n> added. SEND_FILES has been renamed to SEND_FILE. There are no other changes\n> to the grammar.\n>\n> START_BACKUP [LABEL '<label>'] [FAST]\n> - returns startptr, tli, backup_label, unique_backup_id\n> STOP_BACKUP [NOWAIT]\n> - returns startptr, tli, backup_label\n> JOIN_BACKUP ‘unique_backup_id’\n> - attaches a shared state identified by ‘unique_backup_id’ to a backend\n> process.\n>\n> LIST_TABLESPACES [PROGRESS]\n> LIST_FILES [TABLESPACE]\n> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n> SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\n>\n>\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\n-- \nRegards\n====================================\nKashif Zeeshan\nLead Quality Assurance Engineer / Manager\n\nEnterpriseDB Corporation\nThe Enterprise Postgres Company\n\nHi AsifWhen a non-existent slot is used with tablespace then correct error is displayed but then the backup folder is not cleaned and leaves a corrupt backup.Steps=======edb@localhost bin]$ [edb@localhost bin]$ mkdir /home/edb/tbl1[edb@localhost bin]$ mkdir /home/edb/tbl_res[edb@localhost bin]$ postgres=#  create tablespace tbl1 location '/home/edb/tbl1';CREATE TABLESPACEpostgres=# postgres=# create table t1 (a int) tablespace tbl1;CREATE TABLEpostgres=# insert into t1 values(100);INSERT 0 1postgres=# insert into t1 values(200);INSERT 0 1postgres=# insert into t1 values(300);INSERT 0 1postgres=# [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -j 2 -D  /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S testpg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test\" does not existpg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: write-ahead log end point: 0/2E000100pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: error: child thread exited with error 1[edb@localhost bin]$ backup folder not cleaned[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ ls /home/edb/Desktop/backupbackup_label  global        pg_dynshmem  pg_ident.conf  pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    PG_VERSION  pg_xact               postgresql.confbase          pg_commit_ts  pg_hba.conf  pg_logical     pg_notify     pg_serial    pg_stat       pg_subtrans  pg_twophase  pg_wal      postgresql.auto.conf[edb@localhost bin]$ If the same case is executed without the parallel backup patch then the backup folder is cleaned after the error is displayed.[edb@localhost bin]$ ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test999pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test999\" does not existpg_basebackup: write-ahead log end point: 0/2B000100pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: error: child process exited with exit code 1pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"pg_basebackup: changes to tablespace directories will not be undoneOn Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com> wrote:On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>> Why would you need to do that? As long as the process where\n>> STOP_BACKUP can do the check, that seems good enough.\n>\n> Yes, but the user will get the error only after the STOP_BACKUP, not while the backup is\n> in progress. So if the backup is a large one, early error detection would be much beneficial.\n> This is the current behavior of non-parallel backup as well.\n\nBecause non-parallel backup does not feature early detection of this\nerror, it is not necessary to make parallel backup do so. Indeed, it\nis undesirable. If you want to fix that problem, do it on a separate\nthread in a separate patch. A patch proposing to make parallel backup\ninconsistent in behavior with non-parallel backup will be rejected, at\nleast if I have anything to say about it.\n\nTBH, fixing this doesn't seem like an urgent problem to me. The\ncurrent situation is not great, but promotions ought to be relatively\ninfrequent, so I'm not sure it's a huge problem in practice. It is\nalso worth considering whether the right fix is to figure out how to\nmake that case actually work, rather than just making it fail quicker.\nI don't currently understand the reason for the prohibition so I can't\nexpress an intelligent opinion on what the right answer is here, but\nit seems like it ought to be investigated before somebody goes and\nbuilds a bunch of infrastructure to make the error more timely.Non-parallel backup already does the early error checking. I only intendedto make parallel behave the same as non-parallel here. So, I agree withyou that the behavior of parallel backup should be consistent with thenon-parallel one.  Please see the code snippet below from basebackup.c:sendDir()/*\n * Check if the postmaster has signaled us to exit, and abort with an\n * error in that case. The error handler further up will call\n * do_pg_abort_backup() for us. Also check that if the backup was\n * started while still in recovery, the server wasn't promoted.\n * do_pg_stop_backup() will check that too, but it's better to stop\n * the backup early than continue to the end and fail there.\n */\nCHECK_FOR_INTERRUPTS();\nif (RecoveryInProgress() != backup_started_in_recovery)\n ereport(ERROR,\n (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n errmsg(\"the standby was promoted during online backup\"),\n errhint(\"This means that the backup being taken is corrupt \"\n \"and should not be used. \"\n \"Try taking another online backup.\"))); \n\n> Okay, then I will add the shared state. And since we are adding the shared state, we can use\n> that for throttling, progress-reporting and standby early error checking.\n\nPlease propose a grammar here for all the new replication commands you\nplan to add before going and implement everything. That will make it\neasier to hash out the design without forcing you to keep changing the\ncode. Your design should include a sketch of how several sets of\ncoordinating backends taking several concurrent parallel backups will\nend up with one shared state per parallel backup.\n\n> There are two possible options:\n>\n> (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n> (2) (Preferred Option) Use the WAL start location as the BackupID.\n>\n> This BackupID should be given back as a response to start backup command. All client workers\n> must append this ID to all parallel backup replication commands. So that we can use this identifier\n> to search for that particular backup. Does that sound good?\n\nUsing the WAL start location as the backup ID seems like it might be\nproblematic -- could a single checkpoint not end up as the start\nlocation for multiple backups started at the same time? Whether that's\npossible now or not, it seems unwise to hard-wire that assumption into\nthe wire protocol.\n\nI was thinking that perhaps the client should generate a unique backup\nID, e.g. leader does:\n\nSTART_BACKUP unique_backup_id [options]...\n\nAnd then others do:\n\nJOIN_BACKUP unique_backup_id\n\nMy thought is that you will have a number of shared memory structure\nequal to max_wal_senders, each one large enough to hold the shared\nstate for one backup. The shared state will include\nchar[NAMEDATALEN-or-something] which will be used to hold the backup\nID. START_BACKUP would allocate one and copy the name into it;\nJOIN_BACKUP would search for one by name.\n\nIf you want to generate the name on the server side, then I suppose\nSTART_BACKUP would return a result set that includes the backup ID,\nand clients would have to specify that same backup ID when invoking\nJOIN_BACKUP. The rest would stay the same. I am not sure which way is\nbetter. Either way, the backup ID should be something long and hard to\nguess, not e.g. the leader processes' PID. I think we should generate\nit using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\nresult to get a string. That way there's almost no risk of two backup\nIDs colliding accidentally, and even if we somehow had a malicious\nuser trying to screw up somebody else's parallel backup by choosing a\ncolliding backup ID, it would be pretty hard to have any success. A\nuser with enough access to do that sort of thing can probably cause a\nlot worse problems anyway, but it seems pretty easy to guard against\nintentional collisions robustly here, so I think we should.\nOkay so If we are to add another replication command ‘JOIN_BACKUP unique_backup_id’to make workers find the relevant shared state. There won't be any need for changingthe grammar for any other command. The START_BACKUP can return the unique_backup_idin the result set.I am thinking of the following struct for shared state:typedef struct\n{\n char backupid[NAMEDATALEN];\n XLogRecPtr startptr;\n\n slock_t lock;\n int64 throttling_counter;\n bool backup_started_in_recovery;\n} BackupSharedState;The shared state structure entries would be maintained by a shared hash table.There will be one structure per parallel backup. Since a single parallel backupcan engage more than one wal sender, so I think max_wal_senders might be a littletoo much; perhaps max_wal_senders/2 since there will be at least 2 connectionsper parallel backup? Alternatively, we can set a new GUC that defines the maximumnumber of for concurrent parallel backups i.e. ‘max_concurent_backups_allowed = 10’ perhaps, or we can make it user-configurable.The key would be “backupid=hex_encode(pg_random_strong(16))”Checking for Standby Promotion:At the START_BACKUP command, we initialize BackupSharedState.backup_started_in_recovery and keep checking it whenever send_file () is called to send a new file.Throttling:BackupSharedState.throttling_counter - The throttling logic remains the sameas for non-parallel backup with the exception that multiple threads will now beupdating it. So in parallel backup, this will represent the overall bytes thathave been transferred. So the workers would sleep if they have exceeded thelimit. Hence, the shared state carries a lock to safely update the throttlingvalue atomically. Progress Reporting:Although I think we should add progress-reporting for parallel backup as aseparate patch. The relevant entries for progress-reporting such as ‘backup_total’ and ‘backup_streamed’ would be then added to this structureas well.  Grammar:There is a change in the resultset being returned for START_BACKUP command; unique_backup_id is added. Additionally, JOIN_BACKUP replication command isadded. SEND_FILES has been renamed to SEND_FILE. There are no other changesto the grammar.START_BACKUP [LABEL '<label>'] [FAST]  - returns startptr, tli, backup_label, unique_backup_idSTOP_BACKUP [NOWAIT]  - returns startptr, tli, backup_labelJOIN_BACKUP ‘unique_backup_id’  - attaches a shared state identified by ‘unique_backup_id’ to a backend process. LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- Regards====================================Kashif ZeeshanLead Quality Assurance Engineer / ManagerEnterpriseDB CorporationThe Enterprise Postgres Company", "msg_date": "Fri, 3 Apr 2020 15:01:17 +0500", "msg_from": "Kashif Zeeshan <kashif.zeeshan@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Asif,\n\nAfter recent backup manifest addition, patches needed to rebase and\nreconsideration of a few things like making sure that parallel backup\ncreates\na manifest file correctly or not etc.\n\n-- \nJeevan Chalke\nAssociate Database Architect & Team Lead, Product Development\nEnterpriseDB Corporation\nThe Enterprise PostgreSQL Company\n\nAsif,After recent backup manifest addition, patches needed to rebase andreconsideration of a few things like making sure that parallel backup createsa manifest file correctly or not etc.-- Jeevan ChalkeAssociate Database Architect & Team Lead, Product DevelopmentEnterpriseDB CorporationThe Enterprise PostgreSQL Company", "msg_date": "Tue, 7 Apr 2020 09:45:00 +0530", "msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Fri, Apr 3, 2020 at 3:01 PM Kashif Zeeshan <\nkashif.zeeshan@enterprisedb.com> wrote:\n\n> Hi Asif\n>\n> When a non-existent slot is used with tablespace then correct error is\n> displayed but then the backup folder is not cleaned and leaves a corrupt\n> backup.\n>\n> Steps\n> =======\n>\n> edb@localhost bin]$\n> [edb@localhost bin]$ mkdir /home/edb/tbl1\n> [edb@localhost bin]$ mkdir /home/edb/tbl_res\n> [edb@localhost bin]$\n> postgres=# create tablespace tbl1 location '/home/edb/tbl1';\n> CREATE TABLESPACE\n> postgres=#\n> postgres=# create table t1 (a int) tablespace tbl1;\n> CREATE TABLE\n> postgres=# insert into t1 values(100);\n> INSERT 0 1\n> postgres=# insert into t1 values(200);\n> INSERT 0 1\n> postgres=# insert into t1 values(300);\n> INSERT 0 1\n> postgres=#\n>\n>\n> [edb@localhost bin]$\n> [edb@localhost bin]$ ./pg_basebackup -v -j 2 -D\n> /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test\n> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n> pg_basebackup: checkpoint completed\n> pg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1\n> pg_basebackup: starting background WAL receiver\n> pg_basebackup: error: could not send replication command\n> \"START_REPLICATION\": ERROR: replication slot \"test\" does not exist\n> pg_basebackup: backup worker (0) created\n> pg_basebackup: backup worker (1) created\n> pg_basebackup: write-ahead log end point: 0/2E000100\n> pg_basebackup: waiting for background process to finish streaming ...\n> pg_basebackup: error: child thread exited with error 1\n> [edb@localhost bin]$\n>\n> backup folder not cleaned\n>\n> [edb@localhost bin]$\n> [edb@localhost bin]$\n> [edb@localhost bin]$\n> [edb@localhost bin]$ ls /home/edb/Desktop/backup\n> backup_label global pg_dynshmem pg_ident.conf pg_multixact\n> pg_replslot pg_snapshots pg_stat_tmp pg_tblspc PG_VERSION pg_xact\n> postgresql.conf\n> base pg_commit_ts pg_hba.conf pg_logical pg_notify\n> pg_serial pg_stat pg_subtrans pg_twophase pg_wal\n> postgresql.auto.conf\n> [edb@localhost bin]$\n>\n>\n>\n>\n> If the same case is executed without the parallel backup patch then the\n> backup folder is cleaned after the error is displayed.\n>\n> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/ -T\n> /home/edb/tbl1=/home/edb/tbl_res -S test999\n> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n> pg_basebackup: checkpoint completed\n> pg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1\n> pg_basebackup: starting background WAL receiver\n> pg_basebackup: error: could not send replication command\n> \"START_REPLICATION\": ERROR: replication slot \"test999\" does not exist\n> pg_basebackup: write-ahead log end point: 0/2B000100\n> pg_basebackup: waiting for background process to finish streaming ...\n> pg_basebackup: error: child process exited with exit code 1\n> *pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"*\n> pg_basebackup: changes to tablespace directories will not be undone\n>\n\n\nHi Asif\n\nA similar case is when DB Server is shut down while the Parallel Backup is\nin progress then the correct error is displayed but then the backup folder\nis not cleaned and leaves a corrupt backup. I think one bug fix will solve\nall these cases where clean up is not done when parallel backup is failed.\n\n[edb@localhost bin]$\n[edb@localhost bin]$\n[edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/ -j 8\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 0/C1000028 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: created temporary replication slot \"pg_basebackup_57337\"\npg_basebackup: backup worker (0) created\npg_basebackup: backup worker (1) created\npg_basebackup: backup worker (2) created\npg_basebackup: backup worker (3) created\npg_basebackup: backup worker (4) created\npg_basebackup: backup worker (5) created\npg_basebackup: backup worker (6) created\npg_basebackup: backup worker (7) created\npg_basebackup: error: could not read COPY data: server closed the\nconnection unexpectedly\nThis probably means the server terminated abnormally\nbefore or while processing the request.\npg_basebackup: error: could not read COPY data: server closed the\nconnection unexpectedly\nThis probably means the server terminated abnormally\nbefore or while processing the request.\n[edb@localhost bin]$\n[edb@localhost bin]$\n\nSame case when executed on pg_basebackup without the Parallel backup patch\nthen proper clean up is done.\n\n[edb@localhost bin]$\n[edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 0/C5000028 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: created temporary replication slot \"pg_basebackup_5590\"\npg_basebackup: error: could not read COPY data: server closed the\nconnection unexpectedly\nThis probably means the server terminated abnormally\nbefore or while processing the request.\npg_basebackup: removing contents of data directory\n\"/home/edb/Desktop/backup/\"\n[edb@localhost bin]$\n\nThanks\n\n\n>\n> On Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>\n>>\n>>\n>> On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>>\n>>> On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com>\n>>> wrote:\n>>> >> Why would you need to do that? As long as the process where\n>>> >> STOP_BACKUP can do the check, that seems good enough.\n>>> >\n>>> > Yes, but the user will get the error only after the STOP_BACKUP, not\n>>> while the backup is\n>>> > in progress. So if the backup is a large one, early error detection\n>>> would be much beneficial.\n>>> > This is the current behavior of non-parallel backup as well.\n>>>\n>>> Because non-parallel backup does not feature early detection of this\n>>> error, it is not necessary to make parallel backup do so. Indeed, it\n>>> is undesirable. If you want to fix that problem, do it on a separate\n>>> thread in a separate patch. A patch proposing to make parallel backup\n>>> inconsistent in behavior with non-parallel backup will be rejected, at\n>>> least if I have anything to say about it.\n>>>\n>>> TBH, fixing this doesn't seem like an urgent problem to me. The\n>>> current situation is not great, but promotions ought to be relatively\n>>> infrequent, so I'm not sure it's a huge problem in practice. It is\n>>> also worth considering whether the right fix is to figure out how to\n>>> make that case actually work, rather than just making it fail quicker.\n>>> I don't currently understand the reason for the prohibition so I can't\n>>> express an intelligent opinion on what the right answer is here, but\n>>> it seems like it ought to be investigated before somebody goes and\n>>> builds a bunch of infrastructure to make the error more timely.\n>>>\n>>\n>> Non-parallel backup already does the early error checking. I only intended\n>>\n>> to make parallel behave the same as non-parallel here. So, I agree with\n>>\n>> you that the behavior of parallel backup should be consistent with the\n>>\n>> non-parallel one. Please see the code snippet below from\n>>\n>> basebackup.c:sendDir()\n>>\n>>\n>> /*\n>>>\n>>> * Check if the postmaster has signaled us to exit, and abort with an\n>>>\n>>> * error in that case. The error handler further up will call\n>>>\n>>> * do_pg_abort_backup() for us. Also check that if the backup was\n>>>\n>>> * started while still in recovery, the server wasn't promoted.\n>>>\n>>> * do_pg_stop_backup() will check that too, but it's better to stop\n>>>\n>>> * the backup early than continue to the end and fail there.\n>>>\n>>> */\n>>>\n>>> CHECK_FOR_INTERRUPTS();\n>>>\n>>> *if* (RecoveryInProgress() != backup_started_in_recovery)\n>>>\n>>> ereport(ERROR,\n>>>\n>>> (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n>>>\n>>> errmsg(\"the standby was promoted during online backup\"),\n>>>\n>>> errhint(\"This means that the backup being taken is corrupt \"\n>>>\n>>> \"and should not be used. \"\n>>>\n>>> \"Try taking another online backup.\")));\n>>>\n>>>\n>>> > Okay, then I will add the shared state. And since we are adding the\n>>> shared state, we can use\n>>> > that for throttling, progress-reporting and standby early error\n>>> checking.\n>>>\n>>> Please propose a grammar here for all the new replication commands you\n>>> plan to add before going and implement everything. That will make it\n>>> easier to hash out the design without forcing you to keep changing the\n>>> code. Your design should include a sketch of how several sets of\n>>> coordinating backends taking several concurrent parallel backups will\n>>> end up with one shared state per parallel backup.\n>>>\n>>> > There are two possible options:\n>>> >\n>>> > (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n>>> > (2) (Preferred Option) Use the WAL start location as the BackupID.\n>>> >\n>>> > This BackupID should be given back as a response to start backup\n>>> command. All client workers\n>>> > must append this ID to all parallel backup replication commands. So\n>>> that we can use this identifier\n>>> > to search for that particular backup. Does that sound good?\n>>>\n>>> Using the WAL start location as the backup ID seems like it might be\n>>> problematic -- could a single checkpoint not end up as the start\n>>> location for multiple backups started at the same time? Whether that's\n>>> possible now or not, it seems unwise to hard-wire that assumption into\n>>> the wire protocol.\n>>>\n>>> I was thinking that perhaps the client should generate a unique backup\n>>> ID, e.g. leader does:\n>>>\n>>> START_BACKUP unique_backup_id [options]...\n>>>\n>>> And then others do:\n>>>\n>>> JOIN_BACKUP unique_backup_id\n>>>\n>>> My thought is that you will have a number of shared memory structure\n>>> equal to max_wal_senders, each one large enough to hold the shared\n>>> state for one backup. The shared state will include\n>>> char[NAMEDATALEN-or-something] which will be used to hold the backup\n>>> ID. START_BACKUP would allocate one and copy the name into it;\n>>> JOIN_BACKUP would search for one by name.\n>>>\n>>> If you want to generate the name on the server side, then I suppose\n>>> START_BACKUP would return a result set that includes the backup ID,\n>>> and clients would have to specify that same backup ID when invoking\n>>> JOIN_BACKUP. The rest would stay the same. I am not sure which way is\n>>> better. Either way, the backup ID should be something long and hard to\n>>> guess, not e.g. the leader processes' PID. I think we should generate\n>>> it using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\n>>> result to get a string. That way there's almost no risk of two backup\n>>> IDs colliding accidentally, and even if we somehow had a malicious\n>>> user trying to screw up somebody else's parallel backup by choosing a\n>>> colliding backup ID, it would be pretty hard to have any success. A\n>>> user with enough access to do that sort of thing can probably cause a\n>>> lot worse problems anyway, but it seems pretty easy to guard against\n>>> intentional collisions robustly here, so I think we should.\n>>>\n>>>\n>> Okay so If we are to add another replication command ‘JOIN_BACKUP\n>> unique_backup_id’\n>> to make workers find the relevant shared state. There won't be any need\n>> for changing\n>> the grammar for any other command. The START_BACKUP can return the\n>> unique_backup_id\n>> in the result set.\n>>\n>> I am thinking of the following struct for shared state:\n>>\n>>> *typedef* *struct*\n>>>\n>>> {\n>>>\n>>> *char* backupid[NAMEDATALEN];\n>>>\n>>> XLogRecPtr startptr;\n>>>\n>>>\n>>> slock_t lock;\n>>>\n>>> int64 throttling_counter;\n>>>\n>>> *bool* backup_started_in_recovery;\n>>>\n>>> } BackupSharedState;\n>>>\n>>>\n>> The shared state structure entries would be maintained by a shared hash\n>> table.\n>> There will be one structure per parallel backup. Since a single parallel\n>> backup\n>> can engage more than one wal sender, so I think max_wal_senders might be\n>> a little\n>> too much; perhaps max_wal_senders/2 since there will be at least 2\n>> connections\n>> per parallel backup? Alternatively, we can set a new GUC that defines the\n>> maximum\n>> number of for concurrent parallel backups i.e.\n>> ‘max_concurent_backups_allowed = 10’\n>> perhaps, or we can make it user-configurable.\n>>\n>> The key would be “backupid=hex_encode(pg_random_strong(16))”\n>>\n>> Checking for Standby Promotion:\n>> At the START_BACKUP command, we initialize\n>> BackupSharedState.backup_started_in_recovery\n>> and keep checking it whenever send_file () is called to send a new file.\n>>\n>> Throttling:\n>> BackupSharedState.throttling_counter - The throttling logic remains the\n>> same\n>> as for non-parallel backup with the exception that multiple threads will\n>> now be\n>> updating it. So in parallel backup, this will represent the overall bytes\n>> that\n>> have been transferred. So the workers would sleep if they have exceeded\n>> the\n>> limit. Hence, the shared state carries a lock to safely update the\n>> throttling\n>> value atomically.\n>>\n>> Progress Reporting:\n>> Although I think we should add progress-reporting for parallel backup as a\n>> separate patch. The relevant entries for progress-reporting such as\n>> ‘backup_total’ and ‘backup_streamed’ would be then added to this structure\n>> as well.\n>>\n>>\n>> Grammar:\n>> There is a change in the resultset being returned for START_BACKUP\n>> command;\n>> unique_backup_id is added. Additionally, JOIN_BACKUP replication command\n>> is\n>> added. SEND_FILES has been renamed to SEND_FILE. There are no other\n>> changes\n>> to the grammar.\n>>\n>> START_BACKUP [LABEL '<label>'] [FAST]\n>> - returns startptr, tli, backup_label, unique_backup_id\n>> STOP_BACKUP [NOWAIT]\n>> - returns startptr, tli, backup_label\n>> JOIN_BACKUP ‘unique_backup_id’\n>> - attaches a shared state identified by ‘unique_backup_id’ to a backend\n>> process.\n>>\n>> LIST_TABLESPACES [PROGRESS]\n>> LIST_FILES [TABLESPACE]\n>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>> SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\n>>\n>>\n>> --\n>> Asif Rehman\n>> Highgo Software (Canada/China/Pakistan)\n>> URL : www.highgo.ca\n>>\n>>\n>\n> --\n> Regards\n> ====================================\n> Kashif Zeeshan\n> Lead Quality Assurance Engineer / Manager\n>\n> EnterpriseDB Corporation\n> The Enterprise Postgres Company\n>\n>\n\n-- \nRegards\n====================================\nKashif Zeeshan\nLead Quality Assurance Engineer / Manager\n\nEnterpriseDB Corporation\nThe Enterprise Postgres Company\n\nOn Fri, Apr 3, 2020 at 3:01 PM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:Hi AsifWhen a non-existent slot is used with tablespace then correct error is displayed but then the backup folder is not cleaned and leaves a corrupt backup.Steps=======edb@localhost bin]$ [edb@localhost bin]$ mkdir /home/edb/tbl1[edb@localhost bin]$ mkdir /home/edb/tbl_res[edb@localhost bin]$ postgres=#  create tablespace tbl1 location '/home/edb/tbl1';CREATE TABLESPACEpostgres=# postgres=# create table t1 (a int) tablespace tbl1;CREATE TABLEpostgres=# insert into t1 values(100);INSERT 0 1postgres=# insert into t1 values(200);INSERT 0 1postgres=# insert into t1 values(300);INSERT 0 1postgres=# [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -j 2 -D  /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S testpg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test\" does not existpg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: write-ahead log end point: 0/2E000100pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: error: child thread exited with error 1[edb@localhost bin]$ backup folder not cleaned[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ ls /home/edb/Desktop/backupbackup_label  global        pg_dynshmem  pg_ident.conf  pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    PG_VERSION  pg_xact               postgresql.confbase          pg_commit_ts  pg_hba.conf  pg_logical     pg_notify     pg_serial    pg_stat       pg_subtrans  pg_twophase  pg_wal      postgresql.auto.conf[edb@localhost bin]$ If the same case is executed without the parallel backup patch then the backup folder is cleaned after the error is displayed.[edb@localhost bin]$ ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test999pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test999\" does not existpg_basebackup: write-ahead log end point: 0/2B000100pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: error: child process exited with exit code 1pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"pg_basebackup: changes to tablespace directories will not be undoneHi AsifA similar case is when DB Server is shut down while the Parallel Backup is in progress then the correct error\n is displayed but then the backup folder is not cleaned and leaves a \ncorrupt backup. I think one bug fix will solve all these cases where clean up is not done when parallel backup is failed.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -j 8pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C1000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_57337\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: backup worker (7) createdpg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.[edb@localhost bin]$ [edb@localhost bin]$ Same case when executed on pg_basebackup without the Parallel backup patch then proper clean up is done.[edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -D  /home/edb/Desktop/backup/ pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C5000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_5590\"pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: removing contents of data directory \"/home/edb/Desktop/backup/\"[edb@localhost bin]$ ThanksOn Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com> wrote:On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>> Why would you need to do that? As long as the process where\n>> STOP_BACKUP can do the check, that seems good enough.\n>\n> Yes, but the user will get the error only after the STOP_BACKUP, not while the backup is\n> in progress. So if the backup is a large one, early error detection would be much beneficial.\n> This is the current behavior of non-parallel backup as well.\n\nBecause non-parallel backup does not feature early detection of this\nerror, it is not necessary to make parallel backup do so. Indeed, it\nis undesirable. If you want to fix that problem, do it on a separate\nthread in a separate patch. A patch proposing to make parallel backup\ninconsistent in behavior with non-parallel backup will be rejected, at\nleast if I have anything to say about it.\n\nTBH, fixing this doesn't seem like an urgent problem to me. The\ncurrent situation is not great, but promotions ought to be relatively\ninfrequent, so I'm not sure it's a huge problem in practice. It is\nalso worth considering whether the right fix is to figure out how to\nmake that case actually work, rather than just making it fail quicker.\nI don't currently understand the reason for the prohibition so I can't\nexpress an intelligent opinion on what the right answer is here, but\nit seems like it ought to be investigated before somebody goes and\nbuilds a bunch of infrastructure to make the error more timely.Non-parallel backup already does the early error checking. I only intendedto make parallel behave the same as non-parallel here. So, I agree withyou that the behavior of parallel backup should be consistent with thenon-parallel one.  Please see the code snippet below from basebackup.c:sendDir()/*\n * Check if the postmaster has signaled us to exit, and abort with an\n * error in that case. The error handler further up will call\n * do_pg_abort_backup() for us. Also check that if the backup was\n * started while still in recovery, the server wasn't promoted.\n * do_pg_stop_backup() will check that too, but it's better to stop\n * the backup early than continue to the end and fail there.\n */\nCHECK_FOR_INTERRUPTS();\nif (RecoveryInProgress() != backup_started_in_recovery)\n ereport(ERROR,\n (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n errmsg(\"the standby was promoted during online backup\"),\n errhint(\"This means that the backup being taken is corrupt \"\n \"and should not be used. \"\n \"Try taking another online backup.\"))); \n\n> Okay, then I will add the shared state. And since we are adding the shared state, we can use\n> that for throttling, progress-reporting and standby early error checking.\n\nPlease propose a grammar here for all the new replication commands you\nplan to add before going and implement everything. That will make it\neasier to hash out the design without forcing you to keep changing the\ncode. Your design should include a sketch of how several sets of\ncoordinating backends taking several concurrent parallel backups will\nend up with one shared state per parallel backup.\n\n> There are two possible options:\n>\n> (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n> (2) (Preferred Option) Use the WAL start location as the BackupID.\n>\n> This BackupID should be given back as a response to start backup command. All client workers\n> must append this ID to all parallel backup replication commands. So that we can use this identifier\n> to search for that particular backup. Does that sound good?\n\nUsing the WAL start location as the backup ID seems like it might be\nproblematic -- could a single checkpoint not end up as the start\nlocation for multiple backups started at the same time? Whether that's\npossible now or not, it seems unwise to hard-wire that assumption into\nthe wire protocol.\n\nI was thinking that perhaps the client should generate a unique backup\nID, e.g. leader does:\n\nSTART_BACKUP unique_backup_id [options]...\n\nAnd then others do:\n\nJOIN_BACKUP unique_backup_id\n\nMy thought is that you will have a number of shared memory structure\nequal to max_wal_senders, each one large enough to hold the shared\nstate for one backup. The shared state will include\nchar[NAMEDATALEN-or-something] which will be used to hold the backup\nID. START_BACKUP would allocate one and copy the name into it;\nJOIN_BACKUP would search for one by name.\n\nIf you want to generate the name on the server side, then I suppose\nSTART_BACKUP would return a result set that includes the backup ID,\nand clients would have to specify that same backup ID when invoking\nJOIN_BACKUP. The rest would stay the same. I am not sure which way is\nbetter. Either way, the backup ID should be something long and hard to\nguess, not e.g. the leader processes' PID. I think we should generate\nit using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\nresult to get a string. That way there's almost no risk of two backup\nIDs colliding accidentally, and even if we somehow had a malicious\nuser trying to screw up somebody else's parallel backup by choosing a\ncolliding backup ID, it would be pretty hard to have any success. A\nuser with enough access to do that sort of thing can probably cause a\nlot worse problems anyway, but it seems pretty easy to guard against\nintentional collisions robustly here, so I think we should.\nOkay so If we are to add another replication command ‘JOIN_BACKUP unique_backup_id’to make workers find the relevant shared state. There won't be any need for changingthe grammar for any other command. The START_BACKUP can return the unique_backup_idin the result set.I am thinking of the following struct for shared state:typedef struct\n{\n char backupid[NAMEDATALEN];\n XLogRecPtr startptr;\n\n slock_t lock;\n int64 throttling_counter;\n bool backup_started_in_recovery;\n} BackupSharedState;The shared state structure entries would be maintained by a shared hash table.There will be one structure per parallel backup. Since a single parallel backupcan engage more than one wal sender, so I think max_wal_senders might be a littletoo much; perhaps max_wal_senders/2 since there will be at least 2 connectionsper parallel backup? Alternatively, we can set a new GUC that defines the maximumnumber of for concurrent parallel backups i.e. ‘max_concurent_backups_allowed = 10’ perhaps, or we can make it user-configurable.The key would be “backupid=hex_encode(pg_random_strong(16))”Checking for Standby Promotion:At the START_BACKUP command, we initialize BackupSharedState.backup_started_in_recovery and keep checking it whenever send_file () is called to send a new file.Throttling:BackupSharedState.throttling_counter - The throttling logic remains the sameas for non-parallel backup with the exception that multiple threads will now beupdating it. So in parallel backup, this will represent the overall bytes thathave been transferred. So the workers would sleep if they have exceeded thelimit. Hence, the shared state carries a lock to safely update the throttlingvalue atomically. Progress Reporting:Although I think we should add progress-reporting for parallel backup as aseparate patch. The relevant entries for progress-reporting such as ‘backup_total’ and ‘backup_streamed’ would be then added to this structureas well.  Grammar:There is a change in the resultset being returned for START_BACKUP command; unique_backup_id is added. Additionally, JOIN_BACKUP replication command isadded. SEND_FILES has been renamed to SEND_FILE. There are no other changesto the grammar.START_BACKUP [LABEL '<label>'] [FAST]  - returns startptr, tli, backup_label, unique_backup_idSTOP_BACKUP [NOWAIT]  - returns startptr, tli, backup_labelJOIN_BACKUP ‘unique_backup_id’  - attaches a shared state identified by ‘unique_backup_id’ to a backend process. LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- Regards====================================Kashif ZeeshanLead Quality Assurance Engineer / ManagerEnterpriseDB CorporationThe Enterprise Postgres Company\n-- Regards====================================Kashif ZeeshanLead Quality Assurance Engineer / ManagerEnterpriseDB CorporationThe Enterprise Postgres Company", "msg_date": "Tue, 7 Apr 2020 16:03:46 +0500", "msg_from": "Kashif Zeeshan <kashif.zeeshan@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi,\n\nThanks, Kashif and Rajkumar. I have fixed the reported issues.\n\nI have added the shared state as previously described. The new grammar\nchanges\nare as follows:\n\nSTART_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]\n - This will generate a unique backupid using pg_strong_random(16) and\nhex-encoded\n it. which is then returned as the result set.\n - It will also create a shared state and add it to the hashtable. The\nhash table size is set\n to BACKUP_HASH_SIZE=10, but since hashtable can expand dynamically, I\nthink it's\n sufficient initial size. max_wal_senders is not used, because it can\nbe set to quite a\n large values.\n\nJOIN_BACKUP 'backup_id'\n - finds 'backup_id' in hashtable and attaches it to server process.\n\n\nSEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]\n - renamed SEND_FILES to SEND_FILE\n - removed START_WAL_LOCATION from this because 'startptr' is now\naccessible through\n shared state.\n\nThere is no change in other commands:\nSTOP_BACKUP [NOWAIT]\nLIST_TABLESPACES [PROGRESS]\nLIST_FILES [TABLESPACE]\nLIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n\nThe current patches (v11) have been rebased to the latest master. The\nbackup manifest is enabled\nby default, so I have disabled it for parallel backup mode and have\ngenerated a warning so that\nuser is aware of it and not expect it in the backup.\n\n\nOn Tue, Apr 7, 2020 at 4:03 PM Kashif Zeeshan <\nkashif.zeeshan@enterprisedb.com> wrote:\n\n>\n>\n> On Fri, Apr 3, 2020 at 3:01 PM Kashif Zeeshan <\n> kashif.zeeshan@enterprisedb.com> wrote:\n>\n>> Hi Asif\n>>\n>> When a non-existent slot is used with tablespace then correct error is\n>> displayed but then the backup folder is not cleaned and leaves a corrupt\n>> backup.\n>>\n>> Steps\n>> =======\n>>\n>> edb@localhost bin]$\n>> [edb@localhost bin]$ mkdir /home/edb/tbl1\n>> [edb@localhost bin]$ mkdir /home/edb/tbl_res\n>> [edb@localhost bin]$\n>> postgres=# create tablespace tbl1 location '/home/edb/tbl1';\n>> CREATE TABLESPACE\n>> postgres=#\n>> postgres=# create table t1 (a int) tablespace tbl1;\n>> CREATE TABLE\n>> postgres=# insert into t1 values(100);\n>> INSERT 0 1\n>> postgres=# insert into t1 values(200);\n>> INSERT 0 1\n>> postgres=# insert into t1 values(300);\n>> INSERT 0 1\n>> postgres=#\n>>\n>>\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ ./pg_basebackup -v -j 2 -D\n>> /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test\n>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>> pg_basebackup: checkpoint completed\n>> pg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1\n>> pg_basebackup: starting background WAL receiver\n>> pg_basebackup: error: could not send replication command\n>> \"START_REPLICATION\": ERROR: replication slot \"test\" does not exist\n>> pg_basebackup: backup worker (0) created\n>> pg_basebackup: backup worker (1) created\n>> pg_basebackup: write-ahead log end point: 0/2E000100\n>> pg_basebackup: waiting for background process to finish streaming ...\n>> pg_basebackup: error: child thread exited with error 1\n>> [edb@localhost bin]$\n>>\n>> backup folder not cleaned\n>>\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ ls /home/edb/Desktop/backup\n>> backup_label global pg_dynshmem pg_ident.conf pg_multixact\n>> pg_replslot pg_snapshots pg_stat_tmp pg_tblspc PG_VERSION pg_xact\n>> postgresql.conf\n>> base pg_commit_ts pg_hba.conf pg_logical pg_notify\n>> pg_serial pg_stat pg_subtrans pg_twophase pg_wal\n>> postgresql.auto.conf\n>> [edb@localhost bin]$\n>>\n>>\n>>\n>>\n>> If the same case is executed without the parallel backup patch then the\n>> backup folder is cleaned after the error is displayed.\n>>\n>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/ -T\n>> /home/edb/tbl1=/home/edb/tbl_res -S test999\n>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>> pg_basebackup: checkpoint completed\n>> pg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1\n>> pg_basebackup: starting background WAL receiver\n>> pg_basebackup: error: could not send replication command\n>> \"START_REPLICATION\": ERROR: replication slot \"test999\" does not exist\n>> pg_basebackup: write-ahead log end point: 0/2B000100\n>> pg_basebackup: waiting for background process to finish streaming ...\n>> pg_basebackup: error: child process exited with exit code 1\n>> *pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"*\n>> pg_basebackup: changes to tablespace directories will not be undone\n>>\n>\n>\n> Hi Asif\n>\n> A similar case is when DB Server is shut down while the Parallel Backup is\n> in progress then the correct error is displayed but then the backup folder\n> is not cleaned and leaves a corrupt backup. I think one bug fix will solve\n> all these cases where clean up is not done when parallel backup is failed.\n>\n> [edb@localhost bin]$\n> [edb@localhost bin]$\n> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/ -j\n> 8\n> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n> pg_basebackup: checkpoint completed\n> pg_basebackup: write-ahead log start point: 0/C1000028 on timeline 1\n> pg_basebackup: starting background WAL receiver\n> pg_basebackup: created temporary replication slot \"pg_basebackup_57337\"\n> pg_basebackup: backup worker (0) created\n> pg_basebackup: backup worker (1) created\n> pg_basebackup: backup worker (2) created\n> pg_basebackup: backup worker (3) created\n> pg_basebackup: backup worker (4) created\n> pg_basebackup: backup worker (5) created\n> pg_basebackup: backup worker (6) created\n> pg_basebackup: backup worker (7) created\n> pg_basebackup: error: could not read COPY data: server closed the\n> connection unexpectedly\n> This probably means the server terminated abnormally\n> before or while processing the request.\n> pg_basebackup: error: could not read COPY data: server closed the\n> connection unexpectedly\n> This probably means the server terminated abnormally\n> before or while processing the request.\n> [edb@localhost bin]$\n> [edb@localhost bin]$\n>\n> Same case when executed on pg_basebackup without the Parallel backup patch\n> then proper clean up is done.\n>\n> [edb@localhost bin]$\n> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n> pg_basebackup: checkpoint completed\n> pg_basebackup: write-ahead log start point: 0/C5000028 on timeline 1\n> pg_basebackup: starting background WAL receiver\n> pg_basebackup: created temporary replication slot \"pg_basebackup_5590\"\n> pg_basebackup: error: could not read COPY data: server closed the\n> connection unexpectedly\n> This probably means the server terminated abnormally\n> before or while processing the request.\n> pg_basebackup: removing contents of data directory\n> \"/home/edb/Desktop/backup/\"\n> [edb@localhost bin]$\n>\n> Thanks\n>\n>\n>>\n>> On Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>>\n>>>\n>>>\n>>> On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com>\n>>> wrote:\n>>>\n>>>> On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com>\n>>>> wrote:\n>>>> >> Why would you need to do that? As long as the process where\n>>>> >> STOP_BACKUP can do the check, that seems good enough.\n>>>> >\n>>>> > Yes, but the user will get the error only after the STOP_BACKUP, not\n>>>> while the backup is\n>>>> > in progress. So if the backup is a large one, early error detection\n>>>> would be much beneficial.\n>>>> > This is the current behavior of non-parallel backup as well.\n>>>>\n>>>> Because non-parallel backup does not feature early detection of this\n>>>> error, it is not necessary to make parallel backup do so. Indeed, it\n>>>> is undesirable. If you want to fix that problem, do it on a separate\n>>>> thread in a separate patch. A patch proposing to make parallel backup\n>>>> inconsistent in behavior with non-parallel backup will be rejected, at\n>>>> least if I have anything to say about it.\n>>>>\n>>>> TBH, fixing this doesn't seem like an urgent problem to me. The\n>>>> current situation is not great, but promotions ought to be relatively\n>>>> infrequent, so I'm not sure it's a huge problem in practice. It is\n>>>> also worth considering whether the right fix is to figure out how to\n>>>> make that case actually work, rather than just making it fail quicker.\n>>>> I don't currently understand the reason for the prohibition so I can't\n>>>> express an intelligent opinion on what the right answer is here, but\n>>>> it seems like it ought to be investigated before somebody goes and\n>>>> builds a bunch of infrastructure to make the error more timely.\n>>>>\n>>>\n>>> Non-parallel backup already does the early error checking. I only\n>>> intended\n>>>\n>>> to make parallel behave the same as non-parallel here. So, I agree with\n>>>\n>>> you that the behavior of parallel backup should be consistent with the\n>>>\n>>> non-parallel one. Please see the code snippet below from\n>>>\n>>> basebackup.c:sendDir()\n>>>\n>>>\n>>> /*\n>>>>\n>>>> * Check if the postmaster has signaled us to exit, and abort with an\n>>>>\n>>>> * error in that case. The error handler further up will call\n>>>>\n>>>> * do_pg_abort_backup() for us. Also check that if the backup was\n>>>>\n>>>> * started while still in recovery, the server wasn't promoted.\n>>>>\n>>>> * do_pg_stop_backup() will check that too, but it's better to stop\n>>>>\n>>>> * the backup early than continue to the end and fail there.\n>>>>\n>>>> */\n>>>>\n>>>> CHECK_FOR_INTERRUPTS();\n>>>>\n>>>> *if* (RecoveryInProgress() != backup_started_in_recovery)\n>>>>\n>>>> ereport(ERROR,\n>>>>\n>>>> (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n>>>>\n>>>> errmsg(\"the standby was promoted during online backup\"),\n>>>>\n>>>> errhint(\"This means that the backup being taken is corrupt \"\n>>>>\n>>>> \"and should not be used. \"\n>>>>\n>>>> \"Try taking another online backup.\")));\n>>>>\n>>>>\n>>>> > Okay, then I will add the shared state. And since we are adding the\n>>>> shared state, we can use\n>>>> > that for throttling, progress-reporting and standby early error\n>>>> checking.\n>>>>\n>>>> Please propose a grammar here for all the new replication commands you\n>>>> plan to add before going and implement everything. That will make it\n>>>> easier to hash out the design without forcing you to keep changing the\n>>>> code. Your design should include a sketch of how several sets of\n>>>> coordinating backends taking several concurrent parallel backups will\n>>>> end up with one shared state per parallel backup.\n>>>>\n>>>> > There are two possible options:\n>>>> >\n>>>> > (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n>>>> > (2) (Preferred Option) Use the WAL start location as the BackupID.\n>>>> >\n>>>> > This BackupID should be given back as a response to start backup\n>>>> command. All client workers\n>>>> > must append this ID to all parallel backup replication commands. So\n>>>> that we can use this identifier\n>>>> > to search for that particular backup. Does that sound good?\n>>>>\n>>>> Using the WAL start location as the backup ID seems like it might be\n>>>> problematic -- could a single checkpoint not end up as the start\n>>>> location for multiple backups started at the same time? Whether that's\n>>>> possible now or not, it seems unwise to hard-wire that assumption into\n>>>> the wire protocol.\n>>>>\n>>>> I was thinking that perhaps the client should generate a unique backup\n>>>> ID, e.g. leader does:\n>>>>\n>>>> START_BACKUP unique_backup_id [options]...\n>>>>\n>>>> And then others do:\n>>>>\n>>>> JOIN_BACKUP unique_backup_id\n>>>>\n>>>> My thought is that you will have a number of shared memory structure\n>>>> equal to max_wal_senders, each one large enough to hold the shared\n>>>> state for one backup. The shared state will include\n>>>> char[NAMEDATALEN-or-something] which will be used to hold the backup\n>>>> ID. START_BACKUP would allocate one and copy the name into it;\n>>>> JOIN_BACKUP would search for one by name.\n>>>>\n>>>> If you want to generate the name on the server side, then I suppose\n>>>> START_BACKUP would return a result set that includes the backup ID,\n>>>> and clients would have to specify that same backup ID when invoking\n>>>> JOIN_BACKUP. The rest would stay the same. I am not sure which way is\n>>>> better. Either way, the backup ID should be something long and hard to\n>>>> guess, not e.g. the leader processes' PID. I think we should generate\n>>>> it using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\n>>>> result to get a string. That way there's almost no risk of two backup\n>>>> IDs colliding accidentally, and even if we somehow had a malicious\n>>>> user trying to screw up somebody else's parallel backup by choosing a\n>>>> colliding backup ID, it would be pretty hard to have any success. A\n>>>> user with enough access to do that sort of thing can probably cause a\n>>>> lot worse problems anyway, but it seems pretty easy to guard against\n>>>> intentional collisions robustly here, so I think we should.\n>>>>\n>>>>\n>>> Okay so If we are to add another replication command ‘JOIN_BACKUP\n>>> unique_backup_id’\n>>> to make workers find the relevant shared state. There won't be any need\n>>> for changing\n>>> the grammar for any other command. The START_BACKUP can return the\n>>> unique_backup_id\n>>> in the result set.\n>>>\n>>> I am thinking of the following struct for shared state:\n>>>\n>>>> *typedef* *struct*\n>>>>\n>>>> {\n>>>>\n>>>> *char* backupid[NAMEDATALEN];\n>>>>\n>>>> XLogRecPtr startptr;\n>>>>\n>>>>\n>>>> slock_t lock;\n>>>>\n>>>> int64 throttling_counter;\n>>>>\n>>>> *bool* backup_started_in_recovery;\n>>>>\n>>>> } BackupSharedState;\n>>>>\n>>>>\n>>> The shared state structure entries would be maintained by a shared hash\n>>> table.\n>>> There will be one structure per parallel backup. Since a single parallel\n>>> backup\n>>> can engage more than one wal sender, so I think max_wal_senders might be\n>>> a little\n>>> too much; perhaps max_wal_senders/2 since there will be at least 2\n>>> connections\n>>> per parallel backup? Alternatively, we can set a new GUC that defines\n>>> the maximum\n>>> number of for concurrent parallel backups i.e.\n>>> ‘max_concurent_backups_allowed = 10’\n>>> perhaps, or we can make it user-configurable.\n>>>\n>>> The key would be “backupid=hex_encode(pg_random_strong(16))”\n>>>\n>>> Checking for Standby Promotion:\n>>> At the START_BACKUP command, we initialize\n>>> BackupSharedState.backup_started_in_recovery\n>>> and keep checking it whenever send_file () is called to send a new file.\n>>>\n>>> Throttling:\n>>> BackupSharedState.throttling_counter - The throttling logic remains the\n>>> same\n>>> as for non-parallel backup with the exception that multiple threads will\n>>> now be\n>>> updating it. So in parallel backup, this will represent the overall\n>>> bytes that\n>>> have been transferred. So the workers would sleep if they have exceeded\n>>> the\n>>> limit. Hence, the shared state carries a lock to safely update the\n>>> throttling\n>>> value atomically.\n>>>\n>>> Progress Reporting:\n>>> Although I think we should add progress-reporting for parallel backup as\n>>> a\n>>> separate patch. The relevant entries for progress-reporting such as\n>>> ‘backup_total’ and ‘backup_streamed’ would be then added to this\n>>> structure\n>>> as well.\n>>>\n>>>\n>>> Grammar:\n>>> There is a change in the resultset being returned for START_BACKUP\n>>> command;\n>>> unique_backup_id is added. Additionally, JOIN_BACKUP replication command\n>>> is\n>>> added. SEND_FILES has been renamed to SEND_FILE. There are no other\n>>> changes\n>>> to the grammar.\n>>>\n>>> START_BACKUP [LABEL '<label>'] [FAST]\n>>> - returns startptr, tli, backup_label, unique_backup_id\n>>> STOP_BACKUP [NOWAIT]\n>>> - returns startptr, tli, backup_label\n>>> JOIN_BACKUP ‘unique_backup_id’\n>>> - attaches a shared state identified by ‘unique_backup_id’ to a\n>>> backend process.\n>>>\n>>> LIST_TABLESPACES [PROGRESS]\n>>> LIST_FILES [TABLESPACE]\n>>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>> SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\n>>>\n>>>\n>>> --\n>>> Asif Rehman\n>>> Highgo Software (Canada/China/Pakistan)\n>>> URL : www.highgo.ca\n>>>\n>>>\n>>\n>> --\n>> Regards\n>> ====================================\n>> Kashif Zeeshan\n>> Lead Quality Assurance Engineer / Manager\n>>\n>> EnterpriseDB Corporation\n>> The Enterprise Postgres Company\n>>\n>>\n>\n> --\n> Regards\n> ====================================\n> Kashif Zeeshan\n> Lead Quality Assurance Engineer / Manager\n>\n> EnterpriseDB Corporation\n> The Enterprise Postgres Company\n>\n>\n\n-- \n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Tue, 7 Apr 2020 21:43:51 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Apr 7, 2020 at 10:14 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n> Hi,\n>\n> Thanks, Kashif and Rajkumar. I have fixed the reported issues.\n>\n> I have added the shared state as previously described. The new grammar\n> changes\n> are as follows:\n>\n> START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]\n> - This will generate a unique backupid using pg_strong_random(16) and\n> hex-encoded\n> it. which is then returned as the result set.\n> - It will also create a shared state and add it to the hashtable. The\n> hash table size is set\n> to BACKUP_HASH_SIZE=10, but since hashtable can expand dynamically,\n> I think it's\n> sufficient initial size. max_wal_senders is not used, because it can\n> be set to quite a\n> large values.\n>\n> JOIN_BACKUP 'backup_id'\n> - finds 'backup_id' in hashtable and attaches it to server process.\n>\n>\n> SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]\n> - renamed SEND_FILES to SEND_FILE\n> - removed START_WAL_LOCATION from this because 'startptr' is now\n> accessible through\n> shared state.\n>\n> There is no change in other commands:\n> STOP_BACKUP [NOWAIT]\n> LIST_TABLESPACES [PROGRESS]\n> LIST_FILES [TABLESPACE]\n> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>\n> The current patches (v11) have been rebased to the latest master. The\n> backup manifest is enabled\n> by default, so I have disabled it for parallel backup mode and have\n> generated a warning so that\n> user is aware of it and not expect it in the backup.\n>\n\nSo, are you working on to make it work? I don't think a parallel backup\nfeature should be creating a backup with no manifest.\n\n\n>\n>\n>\n> --\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\n-- \nJeevan Chalke\nAssociate Database Architect & Team Lead, Product Development\nEnterpriseDB Corporation\nThe Enterprise PostgreSQL Company\n\nOn Tue, Apr 7, 2020 at 10:14 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Hi,Thanks, Kashif and Rajkumar. I have fixed the reported issues.I have added the shared state as previously described. The new grammar changesare as follows:START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]    - This will generate a unique backupid using pg_strong_random(16) and hex-encoded      it. which is then returned as the result set.    - It will also create a shared state and add it to the hashtable. The hash table size is set      to BACKUP_HASH_SIZE=10, but since hashtable can expand dynamically, I think it's      sufficient initial size. max_wal_senders is not used, because it can be set to quite a       large values.JOIN_BACKUP 'backup_id'    - finds 'backup_id' in hashtable and attaches it to server process.SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]    - renamed SEND_FILES to SEND_FILE    - removed START_WAL_LOCATION from this because 'startptr' is now accessible through      shared state.There is no change in other commands:STOP_BACKUP [NOWAIT]LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']The current patches (v11) have been rebased to the latest master. The backup manifest is enabledby default, so I have disabled it for parallel backup mode and have generated a warning so thatuser is aware of it and not expect it in the backup.So, are you working on to make it work? I don't think a parallel backup feature should be creating a backup with no manifest. -- --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- Jeevan ChalkeAssociate Database Architect & Team Lead, Product DevelopmentEnterpriseDB CorporationThe Enterprise PostgreSQL Company", "msg_date": "Tue, 7 Apr 2020 22:32:55 +0530", "msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Apr 7, 2020 at 10:03 PM Jeevan Chalke <\njeevan.chalke@enterprisedb.com> wrote:\n\n>\n>\n> On Tue, Apr 7, 2020 at 10:14 PM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n>\n>> Hi,\n>>\n>> Thanks, Kashif and Rajkumar. I have fixed the reported issues.\n>>\n>> I have added the shared state as previously described. The new grammar\n>> changes\n>> are as follows:\n>>\n>> START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]\n>> - This will generate a unique backupid using pg_strong_random(16) and\n>> hex-encoded\n>> it. which is then returned as the result set.\n>> - It will also create a shared state and add it to the hashtable. The\n>> hash table size is set\n>> to BACKUP_HASH_SIZE=10, but since hashtable can expand dynamically,\n>> I think it's\n>> sufficient initial size. max_wal_senders is not used, because it\n>> can be set to quite a\n>> large values.\n>>\n>> JOIN_BACKUP 'backup_id'\n>> - finds 'backup_id' in hashtable and attaches it to server process.\n>>\n>>\n>> SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]\n>> - renamed SEND_FILES to SEND_FILE\n>> - removed START_WAL_LOCATION from this because 'startptr' is now\n>> accessible through\n>> shared state.\n>>\n>> There is no change in other commands:\n>> STOP_BACKUP [NOWAIT]\n>> LIST_TABLESPACES [PROGRESS]\n>> LIST_FILES [TABLESPACE]\n>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>\n>> The current patches (v11) have been rebased to the latest master. The\n>> backup manifest is enabled\n>> by default, so I have disabled it for parallel backup mode and have\n>> generated a warning so that\n>> user is aware of it and not expect it in the backup.\n>>\n>\n> So, are you working on to make it work? I don't think a parallel backup\n> feature should be creating a backup with no manifest.\n>\n\nI will, however parallel backup is already quite a large patch. So I think\nwe should first\nagree on the current work before adding a backup manifest and\nprogress-reporting support.\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nOn Tue, Apr 7, 2020 at 10:03 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:On Tue, Apr 7, 2020 at 10:14 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Hi,Thanks, Kashif and Rajkumar. I have fixed the reported issues.I have added the shared state as previously described. The new grammar changesare as follows:START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]    - This will generate a unique backupid using pg_strong_random(16) and hex-encoded      it. which is then returned as the result set.    - It will also create a shared state and add it to the hashtable. The hash table size is set      to BACKUP_HASH_SIZE=10, but since hashtable can expand dynamically, I think it's      sufficient initial size. max_wal_senders is not used, because it can be set to quite a       large values.JOIN_BACKUP 'backup_id'    - finds 'backup_id' in hashtable and attaches it to server process.SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]    - renamed SEND_FILES to SEND_FILE    - removed START_WAL_LOCATION from this because 'startptr' is now accessible through      shared state.There is no change in other commands:STOP_BACKUP [NOWAIT]LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']The current patches (v11) have been rebased to the latest master. The backup manifest is enabledby default, so I have disabled it for parallel backup mode and have generated a warning so thatuser is aware of it and not expect it in the backup.So, are you working on to make it work? I don't think a parallel backup feature should be creating a backup with no manifest.I will, however parallel backup is already quite a large patch. So I think we should firstagree on the current work before adding a backup manifest and progress-reporting support.--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Tue, 7 Apr 2020 22:25:05 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Fri, Apr 3, 2020 at 4:46 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> Non-parallel backup already does the early error checking. I only intended\n> to make parallel behave the same as non-parallel here. So, I agree with\n> you that the behavior of parallel backup should be consistent with the\n> non-parallel one. Please see the code snippet below from\n> basebackup.c:sendDir()\n\nOh, OK. So then we need to preserve that behavior, I think. Sorry, I\ndidn't realize the check was happening there.\n\n> I am thinking of the following struct for shared state:\n>> typedef struct\n>> {\n>> char backupid[NAMEDATALEN];\n>> XLogRecPtr startptr;\n>> slock_t lock;\n>> int64 throttling_counter;\n>> bool backup_started_in_recovery;\n>> } BackupSharedState;\n\nLooks broadly reasonable. Can anything other than lock and\nthrottling_counter change while it's running? If not, how about using\npg_atomic_uint64 for the throttling counter, and dropping lock? If\nthat gets too complicated it's OK to keep it as you have it.\n\n> The shared state structure entries would be maintained by a shared hash table.\n> There will be one structure per parallel backup. Since a single parallel backup\n> can engage more than one wal sender, so I think max_wal_senders might be a little\n> too much; perhaps max_wal_senders/2 since there will be at least 2 connections\n> per parallel backup? Alternatively, we can set a new GUC that defines the maximum\n> number of for concurrent parallel backups i.e. ‘max_concurent_backups_allowed = 10’\n> perhaps, or we can make it user-configurable.\n\nI don't think you need a hash table. Linear search should be fine. And\nI see no point in dividing max_wal_senders by 2 either. The default is\n*10*. You'd need to increase that by more than an order of magnitude\nfor a hash table to be needed, and more than that for the shared\nmemory consumption to matter.\n\n> The key would be “backupid=hex_encode(pg_random_strong(16))”\n\nwfm\n\n> Progress Reporting:\n> Although I think we should add progress-reporting for parallel backup as a\n> separate patch. The relevant entries for progress-reporting such as\n> ‘backup_total’ and ‘backup_streamed’ would be then added to this structure\n> as well.\n\nI mean, you can separate it for review if you wish, but it would need\nto be committed together.\n\n> START_BACKUP [LABEL '<label>'] [FAST]\n> - returns startptr, tli, backup_label, unique_backup_id\n\nOK. But what if I want to use this interface for a non-parallel backup?\n\n> STOP_BACKUP [NOWAIT]\n> - returns startptr, tli, backup_label\n\nI don't think it makes sense for STOP_BACKUP to return the same values\nthat START_BACKUP already returned. Presumably STOP_BACKUP should\nreturn the end LSN. It could also return the backup label and\ntablespace map files, as the corresponding SQL function does, unless\nthere's some better way of returning those in this case.\n\n> JOIN_BACKUP ‘unique_backup_id’\n> - attaches a shared state identified by ‘unique_backup_id’ to a backend process.\n\nOK.\n\n> LIST_TABLESPACES [PROGRESS]\n\nOK.\n\n> LIST_FILES [TABLESPACE]\n\nOK.\n\n> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n\nWhy not just LIST_WAL_FILES 'startptr' 'endptr'?\n\n> SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\n\nWhy parens? That seems useless.\n\nMaybe it would make sense to have SEND_DATA_FILE 'datafilename' and\nSEND_WAL_FILE 'walfilename' as separate commands. But not sure.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 7 Apr 2020 13:36:21 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Apr 7, 2020 at 1:25 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> I will, however parallel backup is already quite a large patch. So I think we should first\n> agree on the current work before adding a backup manifest and progress-reporting support.\n\nIt's going to be needed for commit, but it may make sense for us to do\nmore review of what you've got here before we worry about it.\n\nI'm gonna try to find some time for that as soon as I can.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 7 Apr 2020 13:37:30 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif,\n\nThanks for new patches.\n\nPatches need to be rebased on head. Getting a failure while applying the\n0003 patch.\nedb@localhost postgresql]$ git apply\nv11/0003-Parallel-Backup-Backend-Replication-commands.patch\nerror: patch failed: src/backend/storage/ipc/ipci.c:147\nerror: src/backend/storage/ipc/ipci.c: patch does not apply\n\nI have applied v11 patches on commit -\n23ba3b5ee278847e4fad913b80950edb2838fd35 to test further.\n\npg_basebackup has a new option \"--no-estimate-size\", pg_basebackup crashes\nwhen using this option.\n\n[edb@localhost bin]$ ./pg_basebackup -D /tmp/bkp --no-estimate-size --jobs=2\nSegmentation fault (core dumped)\n\n--stacktrace\n[edb@localhost bin]$ gdb -q -c core.80438 pg_basebackup\nLoaded symbols for /lib64/libselinux.so.1\nCore was generated by `./pg_basebackup -D /tmp/bkp --no-estimate-size\n--jobs=2'.\nProgram terminated with signal 11, Segmentation fault.\n#0 ____strtol_l_internal (nptr=0x0, endptr=0x0, base=10, group=<value\noptimized out>, loc=0x392158ee40) at ../stdlib/strtol_l.c:298\n298 while (ISSPACE (*s))\nMissing separate debuginfos, use: debuginfo-install\nkeyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\nlibcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\nopenssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n(gdb) bt\n#0 ____strtol_l_internal (nptr=0x0, endptr=0x0, base=10, group=<value\noptimized out>, loc=0x392158ee40) at ../stdlib/strtol_l.c:298\n#1 0x0000003921233b30 in atoi (nptr=<value optimized out>) at atoi.c:28\n#2 0x000000000040841e in main (argc=5, argv=0x7ffeaa6fb968) at\npg_basebackup.c:2526\n\nThanks & Regards,\nRajkumar Raghuwanshi\n\n\nOn Tue, Apr 7, 2020 at 11:07 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Tue, Apr 7, 2020 at 1:25 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> > I will, however parallel backup is already quite a large patch. So I\n> think we should first\n> > agree on the current work before adding a backup manifest and\n> progress-reporting support.\n>\n> It's going to be needed for commit, but it may make sense for us to do\n> more review of what you've got here before we worry about it.\n>\n> I'm gonna try to find some time for that as soon as I can.\n>\n> --\n> Robert Haas\n> EnterpriseDB: http://www.enterprisedb.com\n> The Enterprise PostgreSQL Company\n>\n\nHi Asif,Thanks for new patches. Patches need to be rebased on head. Getting a failure while applying the 0003 patch.edb@localhost postgresql]$ git apply  v11/0003-Parallel-Backup-Backend-Replication-commands.patch error: patch failed: src/backend/storage/ipc/ipci.c:147error: src/backend/storage/ipc/ipci.c: patch does not applyI have applied v11 patches on commit - 23ba3b5ee278847e4fad913b80950edb2838fd35 to test further.pg_basebackup has a new option \"--no-estimate-size\",  pg_basebackup crashes when using this option.[edb@localhost bin]$ ./pg_basebackup -D /tmp/bkp --no-estimate-size --jobs=2Segmentation fault (core dumped)--stacktrace [edb@localhost bin]$ gdb -q -c core.80438 pg_basebackup Loaded symbols for /lib64/libselinux.so.1Core was generated by `./pg_basebackup -D /tmp/bkp --no-estimate-size --jobs=2'.Program terminated with signal 11, Segmentation fault.#0  ____strtol_l_internal (nptr=0x0, endptr=0x0, base=10, group=<value optimized out>, loc=0x392158ee40) at ../stdlib/strtol_l.c:298298\t  while (ISSPACE (*s))Missing separate debuginfos, use: debuginfo-install keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64 libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64(gdb) bt#0  ____strtol_l_internal (nptr=0x0, endptr=0x0, base=10, group=<value optimized out>, loc=0x392158ee40) at ../stdlib/strtol_l.c:298#1  0x0000003921233b30 in atoi (nptr=<value optimized out>) at atoi.c:28#2  0x000000000040841e in main (argc=5, argv=0x7ffeaa6fb968) at pg_basebackup.c:2526Thanks & Regards,Rajkumar RaghuwanshiOn Tue, Apr 7, 2020 at 11:07 PM Robert Haas <robertmhaas@gmail.com> wrote:On Tue, Apr 7, 2020 at 1:25 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> I will, however parallel backup is already quite a large patch. So I think we should first\n> agree on the current work before adding a backup manifest and progress-reporting support.\n\nIt's going to be needed for commit, but it may make sense for us to do\nmore review of what you've got here before we worry about it.\n\nI'm gonna try to find some time for that as soon as I can.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Wed, 8 Apr 2020 11:18:31 +0530", "msg_from": "Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "rebased and updated to current master (d025cf88ba). v12 is attahced.\n\nAlso, changed the grammar for LIST_WAL_FILES and SEND_FILE to:\n\n- LIST_WAL_FILES 'startptr' 'endptr'\n- SEND_FILE 'FILE' [NOVERIFY_CHECKSUMS]\n\n\nOn Wed, Apr 8, 2020 at 10:48 AM Rajkumar Raghuwanshi <\nrajkumar.raghuwanshi@enterprisedb.com> wrote:\n\n> Hi Asif,\n>\n> Thanks for new patches.\n>\n> Patches need to be rebased on head. Getting a failure while applying the\n> 0003 patch.\n> edb@localhost postgresql]$ git apply\n> v11/0003-Parallel-Backup-Backend-Replication-commands.patch\n> error: patch failed: src/backend/storage/ipc/ipci.c:147\n> error: src/backend/storage/ipc/ipci.c: patch does not apply\n>\n> I have applied v11 patches on commit -\n> 23ba3b5ee278847e4fad913b80950edb2838fd35 to test further.\n>\n> pg_basebackup has a new option \"--no-estimate-size\", pg_basebackup\n> crashes when using this option.\n>\n> [edb@localhost bin]$ ./pg_basebackup -D /tmp/bkp --no-estimate-size\n> --jobs=2\n> Segmentation fault (core dumped)\n>\n> --stacktrace\n> [edb@localhost bin]$ gdb -q -c core.80438 pg_basebackup\n> Loaded symbols for /lib64/libselinux.so.1\n> Core was generated by `./pg_basebackup -D /tmp/bkp --no-estimate-size\n> --jobs=2'.\n> Program terminated with signal 11, Segmentation fault.\n> #0 ____strtol_l_internal (nptr=0x0, endptr=0x0, base=10, group=<value\n> optimized out>, loc=0x392158ee40) at ../stdlib/strtol_l.c:298\n> 298 while (ISSPACE (*s))\n> Missing separate debuginfos, use: debuginfo-install\n> keyutils-libs-1.4-5.el6.x86_64 krb5-libs-1.10.3-65.el6.x86_64\n> libcom_err-1.41.12-24.el6.x86_64 libselinux-2.0.94-7.el6.x86_64\n> openssl-1.0.1e-58.el6_10.x86_64 zlib-1.2.3-29.el6.x86_64\n> (gdb) bt\n> #0 ____strtol_l_internal (nptr=0x0, endptr=0x0, base=10, group=<value\n> optimized out>, loc=0x392158ee40) at ../stdlib/strtol_l.c:298\n> #1 0x0000003921233b30 in atoi (nptr=<value optimized out>) at atoi.c:28\n> #2 0x000000000040841e in main (argc=5, argv=0x7ffeaa6fb968) at\n> pg_basebackup.c:2526\n>\n> Thanks & Regards,\n> Rajkumar Raghuwanshi\n>\n>\n> On Tue, Apr 7, 2020 at 11:07 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n>> On Tue, Apr 7, 2020 at 1:25 PM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>> > I will, however parallel backup is already quite a large patch. So I\n>> think we should first\n>> > agree on the current work before adding a backup manifest and\n>> progress-reporting support.\n>>\n>> It's going to be needed for commit, but it may make sense for us to do\n>> more review of what you've got here before we worry about it.\n>>\n>> I'm gonna try to find some time for that as soon as I can.\n>>\n>> --\n>> Robert Haas\n>> EnterpriseDB: http://www.enterprisedb.com\n>> The Enterprise PostgreSQL Company\n>>\n>\n\n-- \n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Wed, 8 Apr 2020 12:09:20 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Apr 7, 2020 at 9:44 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n> Hi,\n>\n> Thanks, Kashif and Rajkumar. I have fixed the reported issues.\n>\n> I have added the shared state as previously described. The new grammar\n> changes\n> are as follows:\n>\n> START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]\n> - This will generate a unique backupid using pg_strong_random(16) and\n> hex-encoded\n> it. which is then returned as the result set.\n> - It will also create a shared state and add it to the hashtable. The\n> hash table size is set\n> to BACKUP_HASH_SIZE=10, but since hashtable can expand dynamically,\n> I think it's\n> sufficient initial size. max_wal_senders is not used, because it can\n> be set to quite a\n> large values.\n>\n> JOIN_BACKUP 'backup_id'\n> - finds 'backup_id' in hashtable and attaches it to server process.\n>\n>\n> SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]\n> - renamed SEND_FILES to SEND_FILE\n> - removed START_WAL_LOCATION from this because 'startptr' is now\n> accessible through\n> shared state.\n>\n> There is no change in other commands:\n> STOP_BACKUP [NOWAIT]\n> LIST_TABLESPACES [PROGRESS]\n> LIST_FILES [TABLESPACE]\n> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>\n> The current patches (v11) have been rebased to the latest master. The\n> backup manifest is enabled\n> by default, so I have disabled it for parallel backup mode and have\n> generated a warning so that\n> user is aware of it and not expect it in the backup.\n>\n> Hi Asif\n\nI have verified the bug fixes, one bug is fixed and working now as expected\n\nFor the verification of the other bug fixes faced following issues, please\nhave a look.\n\n\n1) Following bug fixes mentioned below are generating segmentation fault.\n\nPlease note for reference I have added a description only as steps were\ngiven in previous emails of each bug I tried to verify the fix. Backtrace\nis also added with each case which points to one bug for both the cases.\n\na) The backup failed with errors \"error: could not connect to server: could\nnot look up local user ID 1000: Too many open files\" when the\nmax_wal_senders was set to 2000.\n\n\n[edb@localhost bin]$ ./pg_basebackup -v -j 1990 -D\n /home/edb/Desktop/backup/\npg_basebackup: warning: backup manifest is disabled in parallel backup mode\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 0/2000028 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: created temporary replication slot \"pg_basebackup_9925\"\npg_basebackup: backup worker (0) created\npg_basebackup: backup worker (1) created\npg_basebackup: backup worker (2) created\npg_basebackup: backup worker (3) created\n….\n….\npg_basebackup: backup worker (1014) created\npg_basebackup: backup worker (1015) created\npg_basebackup: backup worker (1016) created\npg_basebackup: backup worker (1017) created\npg_basebackup: error: could not connect to server: could not look up local\nuser ID 1000: Too many open files\nSegmentation fault\n[edb@localhost bin]$\n\n\n[edb@localhost bin]$\n[edb@localhost bin]$ gdb pg_basebackup\n/tmp/cores/core.pg_basebackup.13219.localhost.localdomain.1586349551\nGNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7\nCopyright (C) 2013 Free Software Foundation, Inc.\nLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html\n>\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law. Type \"show copying\"\nand \"show warranty\" for details.\nThis GDB was configured as \"x86_64-redhat-linux-gnu\".\nFor bug reporting instructions, please see:\n<http://www.gnu.org/software/gdb/bugs/>...\nReading symbols from\n/home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.\n[New LWP 13219]\n[New LWP 13222]\n[Thread debugging using libthread_db enabled]\nUsing host libthread_db library \"/lib64/libthread_db.so.1\".\nCore was generated by `./pg_basebackup -v -j 1990 -D\n/home/edb/Desktop/backup/'.\nProgram terminated with signal 11, Segmentation fault.\n#0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n47 if (INVALID_NOT_TERMINATED_TD_P (pd))\n(gdb) bt\n#0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n#1 0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978\n#2 0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332\n#3 0x00007f2226f76a49 in __run_exit_handlers (status=1,\nlistp=0x7f22272f86c8 <__exit_funcs>,\nrun_list_atexit=run_list_atexit@entry=true)\nat exit.c:77\n#4 0x00007f2226f76a95 in __GI_exit (status=<optimized out>) at exit.c:99\n#5 0x0000000000408c54 in create_parallel_workers (backupinfo=0x952ca0) at\npg_basebackup.c:2811\n#6 0x000000000040798f in BaseBackup () at pg_basebackup.c:2211\n#7 0x0000000000408b4d in main (argc=6, argv=0x7ffe3dabc718) at\npg_basebackup.c:2765\n(gdb)\n\n\n\n\nb) When executing two backups at the same time, getting FATAL error due to\nmax_wal_senders and instead of exit Backup got completed.\n\n[edb@localhost bin]$\n[edb@localhost bin]$\n[edb@localhost bin]$ ./pg_basebackup -v -j 8 -D /home/edb/Desktop/backup1/\npg_basebackup: warning: backup manifest is disabled in parallel backup mode\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 1/DA000028 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: created temporary replication slot \"pg_basebackup_17066\"\npg_basebackup: backup worker (0) created\npg_basebackup: backup worker (1) created\npg_basebackup: backup worker (2) created\npg_basebackup: backup worker (3) created\npg_basebackup: backup worker (4) created\npg_basebackup: backup worker (5) created\npg_basebackup: backup worker (6) created\npg_basebackup: error: could not connect to server: FATAL: number of\nrequested standby connections exceeds max_wal_senders (currently 10)\nSegmentation fault (core dumped)\n[edb@localhost bin]$\n[edb@localhost bin]$\n[edb@localhost bin]$ gdb pg_basebackup\n/tmp/cores/core.pg_basebackup.17041.localhost.localdomain.1586353696\nGNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7\nCopyright (C) 2013 Free Software Foundation, Inc.\nLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html\n>\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law. Type \"show copying\"\nand \"show warranty\" for details.\nThis GDB was configured as \"x86_64-redhat-linux-gnu\".\nFor bug reporting instructions, please see:\n<http://www.gnu.org/software/gdb/bugs/>...\nReading symbols from\n/home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.\n[New LWP 17041]\n[New LWP 17067]\n[Thread debugging using libthread_db enabled]\nUsing host libthread_db library \"/lib64/libthread_db.so.1\".\nCore was generated by `./pg_basebackup -v -j 8 -D\n/home/edb/Desktop/backup1/'.\nProgram terminated with signal 11, Segmentation fault.\n#0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n47 if (INVALID_NOT_TERMINATED_TD_P (pd))\n(gdb) bt\n#0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n#1 0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978\n#2 0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332\n#3 0x00007f051edc1a49 in __run_exit_handlers (status=1,\nlistp=0x7f051f1436c8 <__exit_funcs>,\nrun_list_atexit=run_list_atexit@entry=true)\nat exit.c:77\n#4 0x00007f051edc1a95 in __GI_exit (status=<optimized out>) at exit.c:99\n#5 0x0000000000408c54 in create_parallel_workers (backupinfo=0x1c6dca0) at\npg_basebackup.c:2811\n#6 0x000000000040798f in BaseBackup () at pg_basebackup.c:2211\n#7 0x0000000000408b4d in main (argc=6, argv=0x7ffdb76a6d68) at\npg_basebackup.c:2765\n(gdb)\n\n\n\n\n2) The following bug is not fixed yet\n\nA similar case is when DB Server is shut down while the Parallel Backup is\nin progress then the correct error is displayed but then the backup folder\nis not cleaned and leaves a corrupt backup.\n\n[edb@localhost bin]$\n[edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/ -j 8\npg_basebackup: warning: backup manifest is disabled in parallel backup mode\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 0/A0000028 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: created temporary replication slot \"pg_basebackup_16235\"\npg_basebackup: backup worker (0) created\npg_basebackup: backup worker (1) created\npg_basebackup: backup worker (2) created\npg_basebackup: backup worker (3) created\npg_basebackup: backup worker (4) created\npg_basebackup: backup worker (5) created\npg_basebackup: backup worker (6) created\npg_basebackup: backup worker (7) created\npg_basebackup: error: could not read COPY data: server closed the\nconnection unexpectedly\nThis probably means the server terminated abnormally\nbefore or while processing the request.\npg_basebackup: error: could not read COPY data: server closed the\nconnection unexpectedly\nThis probably means the server terminated abnormally\nbefore or while processing the request.\npg_basebackup: removing contents of data directory\n\"/home/edb/Desktop/backup/\"\npg_basebackup: error: could not read COPY data: server closed the\nconnection unexpectedly\nThis probably means the server terminated abnormally\nbefore or while processing the request.\n[edb@localhost bin]$\n[edb@localhost bin]$\n[edb@localhost bin]$\n\n\n\n[edb@localhost bin]$\n[edb@localhost bin]$ ls /home/edb/Desktop/backup\nbase pg_hba.conf pg_logical pg_notify pg_serial\npg_stat pg_subtrans pg_twophase pg_xact postgresql.conf\npg_dynshmem pg_ident.conf pg_multixact pg_replslot pg_snapshots\n pg_stat_tmp pg_tblspc PG_VERSION postgresql.auto.conf\n[edb@localhost bin]$\n[edb@localhost bin]$\n\n\n\n\nThanks\nKashif Zeeshan\n\n>\n>\n> On Tue, Apr 7, 2020 at 4:03 PM Kashif Zeeshan <\n> kashif.zeeshan@enterprisedb.com> wrote:\n>\n>>\n>>\n>> On Fri, Apr 3, 2020 at 3:01 PM Kashif Zeeshan <\n>> kashif.zeeshan@enterprisedb.com> wrote:\n>>\n>>> Hi Asif\n>>>\n>>> When a non-existent slot is used with tablespace then correct error is\n>>> displayed but then the backup folder is not cleaned and leaves a corrupt\n>>> backup.\n>>>\n>>> Steps\n>>> =======\n>>>\n>>> edb@localhost bin]$\n>>> [edb@localhost bin]$ mkdir /home/edb/tbl1\n>>> [edb@localhost bin]$ mkdir /home/edb/tbl_res\n>>> [edb@localhost bin]$\n>>> postgres=# create tablespace tbl1 location '/home/edb/tbl1';\n>>> CREATE TABLESPACE\n>>> postgres=#\n>>> postgres=# create table t1 (a int) tablespace tbl1;\n>>> CREATE TABLE\n>>> postgres=# insert into t1 values(100);\n>>> INSERT 0 1\n>>> postgres=# insert into t1 values(200);\n>>> INSERT 0 1\n>>> postgres=# insert into t1 values(300);\n>>> INSERT 0 1\n>>> postgres=#\n>>>\n>>>\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$ ./pg_basebackup -v -j 2 -D\n>>> /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test\n>>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>>> pg_basebackup: checkpoint completed\n>>> pg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1\n>>> pg_basebackup: starting background WAL receiver\n>>> pg_basebackup: error: could not send replication command\n>>> \"START_REPLICATION\": ERROR: replication slot \"test\" does not exist\n>>> pg_basebackup: backup worker (0) created\n>>> pg_basebackup: backup worker (1) created\n>>> pg_basebackup: write-ahead log end point: 0/2E000100\n>>> pg_basebackup: waiting for background process to finish streaming ...\n>>> pg_basebackup: error: child thread exited with error 1\n>>> [edb@localhost bin]$\n>>>\n>>> backup folder not cleaned\n>>>\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$ ls /home/edb/Desktop/backup\n>>> backup_label global pg_dynshmem pg_ident.conf pg_multixact\n>>> pg_replslot pg_snapshots pg_stat_tmp pg_tblspc PG_VERSION pg_xact\n>>> postgresql.conf\n>>> base pg_commit_ts pg_hba.conf pg_logical pg_notify\n>>> pg_serial pg_stat pg_subtrans pg_twophase pg_wal\n>>> postgresql.auto.conf\n>>> [edb@localhost bin]$\n>>>\n>>>\n>>>\n>>>\n>>> If the same case is executed without the parallel backup patch then the\n>>> backup folder is cleaned after the error is displayed.\n>>>\n>>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>>> -T /home/edb/tbl1=/home/edb/tbl_res -S test999\n>>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>>> pg_basebackup: checkpoint completed\n>>> pg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1\n>>> pg_basebackup: starting background WAL receiver\n>>> pg_basebackup: error: could not send replication command\n>>> \"START_REPLICATION\": ERROR: replication slot \"test999\" does not exist\n>>> pg_basebackup: write-ahead log end point: 0/2B000100\n>>> pg_basebackup: waiting for background process to finish streaming ...\n>>> pg_basebackup: error: child process exited with exit code 1\n>>> *pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"*\n>>> pg_basebackup: changes to tablespace directories will not be undone\n>>>\n>>\n>>\n>> Hi Asif\n>>\n>> A similar case is when DB Server is shut down while the Parallel Backup\n>> is in progress then the correct error is displayed but then the backup\n>> folder is not cleaned and leaves a corrupt backup. I think one bug fix will\n>> solve all these cases where clean up is not done when parallel backup is\n>> failed.\n>>\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>> -j 8\n>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>> pg_basebackup: checkpoint completed\n>> pg_basebackup: write-ahead log start point: 0/C1000028 on timeline 1\n>> pg_basebackup: starting background WAL receiver\n>> pg_basebackup: created temporary replication slot \"pg_basebackup_57337\"\n>> pg_basebackup: backup worker (0) created\n>> pg_basebackup: backup worker (1) created\n>> pg_basebackup: backup worker (2) created\n>> pg_basebackup: backup worker (3) created\n>> pg_basebackup: backup worker (4) created\n>> pg_basebackup: backup worker (5) created\n>> pg_basebackup: backup worker (6) created\n>> pg_basebackup: backup worker (7) created\n>> pg_basebackup: error: could not read COPY data: server closed the\n>> connection unexpectedly\n>> This probably means the server terminated abnormally\n>> before or while processing the request.\n>> pg_basebackup: error: could not read COPY data: server closed the\n>> connection unexpectedly\n>> This probably means the server terminated abnormally\n>> before or while processing the request.\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>>\n>> Same case when executed on pg_basebackup without the Parallel backup\n>> patch then proper clean up is done.\n>>\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>> pg_basebackup: checkpoint completed\n>> pg_basebackup: write-ahead log start point: 0/C5000028 on timeline 1\n>> pg_basebackup: starting background WAL receiver\n>> pg_basebackup: created temporary replication slot \"pg_basebackup_5590\"\n>> pg_basebackup: error: could not read COPY data: server closed the\n>> connection unexpectedly\n>> This probably means the server terminated abnormally\n>> before or while processing the request.\n>> pg_basebackup: removing contents of data directory\n>> \"/home/edb/Desktop/backup/\"\n>> [edb@localhost bin]$\n>>\n>> Thanks\n>>\n>>\n>>>\n>>> On Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com>\n>>> wrote:\n>>>\n>>>>\n>>>>\n>>>> On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com>\n>>>> wrote:\n>>>>\n>>>>> On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com>\n>>>>> wrote:\n>>>>> >> Why would you need to do that? As long as the process where\n>>>>> >> STOP_BACKUP can do the check, that seems good enough.\n>>>>> >\n>>>>> > Yes, but the user will get the error only after the STOP_BACKUP, not\n>>>>> while the backup is\n>>>>> > in progress. So if the backup is a large one, early error detection\n>>>>> would be much beneficial.\n>>>>> > This is the current behavior of non-parallel backup as well.\n>>>>>\n>>>>> Because non-parallel backup does not feature early detection of this\n>>>>> error, it is not necessary to make parallel backup do so. Indeed, it\n>>>>> is undesirable. If you want to fix that problem, do it on a separate\n>>>>> thread in a separate patch. A patch proposing to make parallel backup\n>>>>> inconsistent in behavior with non-parallel backup will be rejected, at\n>>>>> least if I have anything to say about it.\n>>>>>\n>>>>> TBH, fixing this doesn't seem like an urgent problem to me. The\n>>>>> current situation is not great, but promotions ought to be relatively\n>>>>> infrequent, so I'm not sure it's a huge problem in practice. It is\n>>>>> also worth considering whether the right fix is to figure out how to\n>>>>> make that case actually work, rather than just making it fail quicker.\n>>>>> I don't currently understand the reason for the prohibition so I can't\n>>>>> express an intelligent opinion on what the right answer is here, but\n>>>>> it seems like it ought to be investigated before somebody goes and\n>>>>> builds a bunch of infrastructure to make the error more timely.\n>>>>>\n>>>>\n>>>> Non-parallel backup already does the early error checking. I only\n>>>> intended\n>>>>\n>>>> to make parallel behave the same as non-parallel here. So, I agree with\n>>>>\n>>>> you that the behavior of parallel backup should be consistent with the\n>>>>\n>>>> non-parallel one. Please see the code snippet below from\n>>>>\n>>>> basebackup.c:sendDir()\n>>>>\n>>>>\n>>>> /*\n>>>>>\n>>>>> * Check if the postmaster has signaled us to exit, and abort with an\n>>>>>\n>>>>> * error in that case. The error handler further up will call\n>>>>>\n>>>>> * do_pg_abort_backup() for us. Also check that if the backup was\n>>>>>\n>>>>> * started while still in recovery, the server wasn't promoted.\n>>>>>\n>>>>> * do_pg_stop_backup() will check that too, but it's better to stop\n>>>>>\n>>>>> * the backup early than continue to the end and fail there.\n>>>>>\n>>>>> */\n>>>>>\n>>>>> CHECK_FOR_INTERRUPTS();\n>>>>>\n>>>>> *if* (RecoveryInProgress() != backup_started_in_recovery)\n>>>>>\n>>>>> ereport(ERROR,\n>>>>>\n>>>>> (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n>>>>>\n>>>>> errmsg(\"the standby was promoted during online backup\"),\n>>>>>\n>>>>> errhint(\"This means that the backup being taken is corrupt \"\n>>>>>\n>>>>> \"and should not be used. \"\n>>>>>\n>>>>> \"Try taking another online backup.\")));\n>>>>>\n>>>>>\n>>>>> > Okay, then I will add the shared state. And since we are adding the\n>>>>> shared state, we can use\n>>>>> > that for throttling, progress-reporting and standby early error\n>>>>> checking.\n>>>>>\n>>>>> Please propose a grammar here for all the new replication commands you\n>>>>> plan to add before going and implement everything. That will make it\n>>>>> easier to hash out the design without forcing you to keep changing the\n>>>>> code. Your design should include a sketch of how several sets of\n>>>>> coordinating backends taking several concurrent parallel backups will\n>>>>> end up with one shared state per parallel backup.\n>>>>>\n>>>>> > There are two possible options:\n>>>>> >\n>>>>> > (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n>>>>> > (2) (Preferred Option) Use the WAL start location as the BackupID.\n>>>>> >\n>>>>> > This BackupID should be given back as a response to start backup\n>>>>> command. All client workers\n>>>>> > must append this ID to all parallel backup replication commands. So\n>>>>> that we can use this identifier\n>>>>> > to search for that particular backup. Does that sound good?\n>>>>>\n>>>>> Using the WAL start location as the backup ID seems like it might be\n>>>>> problematic -- could a single checkpoint not end up as the start\n>>>>> location for multiple backups started at the same time? Whether that's\n>>>>> possible now or not, it seems unwise to hard-wire that assumption into\n>>>>> the wire protocol.\n>>>>>\n>>>>> I was thinking that perhaps the client should generate a unique backup\n>>>>> ID, e.g. leader does:\n>>>>>\n>>>>> START_BACKUP unique_backup_id [options]...\n>>>>>\n>>>>> And then others do:\n>>>>>\n>>>>> JOIN_BACKUP unique_backup_id\n>>>>>\n>>>>> My thought is that you will have a number of shared memory structure\n>>>>> equal to max_wal_senders, each one large enough to hold the shared\n>>>>> state for one backup. The shared state will include\n>>>>> char[NAMEDATALEN-or-something] which will be used to hold the backup\n>>>>> ID. START_BACKUP would allocate one and copy the name into it;\n>>>>> JOIN_BACKUP would search for one by name.\n>>>>>\n>>>>> If you want to generate the name on the server side, then I suppose\n>>>>> START_BACKUP would return a result set that includes the backup ID,\n>>>>> and clients would have to specify that same backup ID when invoking\n>>>>> JOIN_BACKUP. The rest would stay the same. I am not sure which way is\n>>>>> better. Either way, the backup ID should be something long and hard to\n>>>>> guess, not e.g. the leader processes' PID. I think we should generate\n>>>>> it using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\n>>>>> result to get a string. That way there's almost no risk of two backup\n>>>>> IDs colliding accidentally, and even if we somehow had a malicious\n>>>>> user trying to screw up somebody else's parallel backup by choosing a\n>>>>> colliding backup ID, it would be pretty hard to have any success. A\n>>>>> user with enough access to do that sort of thing can probably cause a\n>>>>> lot worse problems anyway, but it seems pretty easy to guard against\n>>>>> intentional collisions robustly here, so I think we should.\n>>>>>\n>>>>>\n>>>> Okay so If we are to add another replication command ‘JOIN_BACKUP\n>>>> unique_backup_id’\n>>>> to make workers find the relevant shared state. There won't be any need\n>>>> for changing\n>>>> the grammar for any other command. The START_BACKUP can return the\n>>>> unique_backup_id\n>>>> in the result set.\n>>>>\n>>>> I am thinking of the following struct for shared state:\n>>>>\n>>>>> *typedef* *struct*\n>>>>>\n>>>>> {\n>>>>>\n>>>>> *char* backupid[NAMEDATALEN];\n>>>>>\n>>>>> XLogRecPtr startptr;\n>>>>>\n>>>>>\n>>>>> slock_t lock;\n>>>>>\n>>>>> int64 throttling_counter;\n>>>>>\n>>>>> *bool* backup_started_in_recovery;\n>>>>>\n>>>>> } BackupSharedState;\n>>>>>\n>>>>>\n>>>> The shared state structure entries would be maintained by a shared hash\n>>>> table.\n>>>> There will be one structure per parallel backup. Since a single\n>>>> parallel backup\n>>>> can engage more than one wal sender, so I think max_wal_senders might\n>>>> be a little\n>>>> too much; perhaps max_wal_senders/2 since there will be at least 2\n>>>> connections\n>>>> per parallel backup? Alternatively, we can set a new GUC that defines\n>>>> the maximum\n>>>> number of for concurrent parallel backups i.e.\n>>>> ‘max_concurent_backups_allowed = 10’\n>>>> perhaps, or we can make it user-configurable.\n>>>>\n>>>> The key would be “backupid=hex_encode(pg_random_strong(16))”\n>>>>\n>>>> Checking for Standby Promotion:\n>>>> At the START_BACKUP command, we initialize\n>>>> BackupSharedState.backup_started_in_recovery\n>>>> and keep checking it whenever send_file () is called to send a new file.\n>>>>\n>>>> Throttling:\n>>>> BackupSharedState.throttling_counter - The throttling logic remains the\n>>>> same\n>>>> as for non-parallel backup with the exception that multiple threads\n>>>> will now be\n>>>> updating it. So in parallel backup, this will represent the overall\n>>>> bytes that\n>>>> have been transferred. So the workers would sleep if they have exceeded\n>>>> the\n>>>> limit. Hence, the shared state carries a lock to safely update the\n>>>> throttling\n>>>> value atomically.\n>>>>\n>>>> Progress Reporting:\n>>>> Although I think we should add progress-reporting for parallel backup\n>>>> as a\n>>>> separate patch. The relevant entries for progress-reporting such as\n>>>> ‘backup_total’ and ‘backup_streamed’ would be then added to this\n>>>> structure\n>>>> as well.\n>>>>\n>>>>\n>>>> Grammar:\n>>>> There is a change in the resultset being returned for START_BACKUP\n>>>> command;\n>>>> unique_backup_id is added. Additionally, JOIN_BACKUP replication\n>>>> command is\n>>>> added. SEND_FILES has been renamed to SEND_FILE. There are no other\n>>>> changes\n>>>> to the grammar.\n>>>>\n>>>> START_BACKUP [LABEL '<label>'] [FAST]\n>>>> - returns startptr, tli, backup_label, unique_backup_id\n>>>> STOP_BACKUP [NOWAIT]\n>>>> - returns startptr, tli, backup_label\n>>>> JOIN_BACKUP ‘unique_backup_id’\n>>>> - attaches a shared state identified by ‘unique_backup_id’ to a\n>>>> backend process.\n>>>>\n>>>> LIST_TABLESPACES [PROGRESS]\n>>>> LIST_FILES [TABLESPACE]\n>>>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>>> SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\n>>>>\n>>>>\n>>>> --\n>>>> Asif Rehman\n>>>> Highgo Software (Canada/China/Pakistan)\n>>>> URL : www.highgo.ca\n>>>>\n>>>>\n>>>\n>>> --\n>>> Regards\n>>> ====================================\n>>> Kashif Zeeshan\n>>> Lead Quality Assurance Engineer / Manager\n>>>\n>>> EnterpriseDB Corporation\n>>> The Enterprise Postgres Company\n>>>\n>>>\n>>\n>> --\n>> Regards\n>> ====================================\n>> Kashif Zeeshan\n>> Lead Quality Assurance Engineer / Manager\n>>\n>> EnterpriseDB Corporation\n>> The Enterprise Postgres Company\n>>\n>>\n>\n> --\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\n-- \nRegards\n====================================\nKashif Zeeshan\nLead Quality Assurance Engineer / Manager\n\nEnterpriseDB Corporation\nThe Enterprise Postgres Company\n\nOn Tue, Apr 7, 2020 at 9:44 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Hi,Thanks, Kashif and Rajkumar. I have fixed the reported issues.I have added the shared state as previously described. The new grammar changesare as follows:START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]    - This will generate a unique backupid using pg_strong_random(16) and hex-encoded      it. which is then returned as the result set.    - It will also create a shared state and add it to the hashtable. The hash table size is set      to BACKUP_HASH_SIZE=10, but since hashtable can expand dynamically, I think it's      sufficient initial size. max_wal_senders is not used, because it can be set to quite a       large values.JOIN_BACKUP 'backup_id'    - finds 'backup_id' in hashtable and attaches it to server process.SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]    - renamed SEND_FILES to SEND_FILE    - removed START_WAL_LOCATION from this because 'startptr' is now accessible through      shared state.There is no change in other commands:STOP_BACKUP [NOWAIT]LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']The current patches (v11) have been rebased to the latest master. The backup manifest is enabledby default, so I have disabled it for parallel backup mode and have generated a warning so thatuser is aware of it and not expect it in the backup.Hi AsifI have verified the bug fixes, one bug is fixed and working now as expected For the verification of the other bug fixes faced following issues, please have a look.1) Following bug fixes mentioned below are generating segmentation fault. Please note for reference I have added a description only as steps were given in previous emails of each bug I tried to verify the fix. Backtrace is also added with each case which points to one bug for both the cases.a) The backup failed with errors \"error: could not connect to server: could not look up local user ID 1000: Too many open files\" when the max_wal_senders was set to 2000. [edb@localhost bin]$ ./pg_basebackup -v -j 1990 -D  /home/edb/Desktop/backup/pg_basebackup: warning: backup manifest is disabled in parallel backup modepg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_9925\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) created….….pg_basebackup: backup worker (1014) createdpg_basebackup: backup worker (1015) createdpg_basebackup: backup worker (1016) createdpg_basebackup: backup worker (1017) createdpg_basebackup: error: could not connect to server: could not look up local user ID 1000: Too many open filesSegmentation fault[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ gdb pg_basebackup /tmp/cores/core.pg_basebackup.13219.localhost.localdomain.1586349551 GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7Copyright (C) 2013 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"and \"show warranty\" for details.This GDB was configured as \"x86_64-redhat-linux-gnu\".For bug reporting instructions, please see:<http://www.gnu.org/software/gdb/bugs/>...Reading symbols from /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.[New LWP 13219][New LWP 13222][Thread debugging using libthread_db enabled]Using host libthread_db library \"/lib64/libthread_db.so.1\".Core was generated by `./pg_basebackup -v -j 1990 -D /home/edb/Desktop/backup/'.Program terminated with signal 11, Segmentation fault.#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:4747\t  if (INVALID_NOT_TERMINATED_TD_P (pd))(gdb) bt#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47#1  0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978#2  0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332#3  0x00007f2226f76a49 in __run_exit_handlers (status=1, listp=0x7f22272f86c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true) at exit.c:77#4  0x00007f2226f76a95 in __GI_exit (status=<optimized out>) at exit.c:99#5  0x0000000000408c54 in create_parallel_workers (backupinfo=0x952ca0) at pg_basebackup.c:2811#6  0x000000000040798f in BaseBackup () at pg_basebackup.c:2211#7  0x0000000000408b4d in main (argc=6, argv=0x7ffe3dabc718) at pg_basebackup.c:2765(gdb) b) When\n executing two backups at the same time, getting FATAL error due to \nmax_wal_senders and instead of exit  Backup got completed.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -j 8 -D  /home/edb/Desktop/backup1/pg_basebackup: warning: backup manifest is disabled in parallel backup modepg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 1/DA000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_17066\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)Segmentation fault (core dumped)[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ gdb pg_basebackup /tmp/cores/core.pg_basebackup.17041.localhost.localdomain.1586353696 GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7Copyright (C) 2013 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"and \"show warranty\" for details.This GDB was configured as \"x86_64-redhat-linux-gnu\".For bug reporting instructions, please see:<http://www.gnu.org/software/gdb/bugs/>...Reading symbols from /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.[New LWP 17041][New LWP 17067][Thread debugging using libthread_db enabled]Using host libthread_db library \"/lib64/libthread_db.so.1\".Core was generated by `./pg_basebackup -v -j 8 -D /home/edb/Desktop/backup1/'.Program terminated with signal 11, Segmentation fault.#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:4747\t  if (INVALID_NOT_TERMINATED_TD_P (pd))(gdb) bt#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47#1  0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978#2  0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332#3  0x00007f051edc1a49 in __run_exit_handlers (status=1, listp=0x7f051f1436c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true) at exit.c:77#4  0x00007f051edc1a95 in __GI_exit (status=<optimized out>) at exit.c:99#5  0x0000000000408c54 in create_parallel_workers (backupinfo=0x1c6dca0) at pg_basebackup.c:2811#6  0x000000000040798f in BaseBackup () at pg_basebackup.c:2211#7  0x0000000000408b4d in main (argc=6, argv=0x7ffdb76a6d68) at pg_basebackup.c:2765(gdb) 2) The following bug is not fixed yetA similar case is when DB Server is shut down while the Parallel Backup is in progress then the correct error\n is displayed but then the backup folder is not cleaned and leaves a \ncorrupt backup. [edb@localhost bin]$ [edb@localhost bin]$ ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -j 8pg_basebackup: warning: backup manifest is disabled in parallel backup modepg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/A0000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_16235\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: backup worker (7) createdpg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: removing contents of data directory \"/home/edb/Desktop/backup/\"pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ ls /home/edb/Desktop/backupbase         pg_hba.conf    pg_logical    pg_notify    pg_serial     pg_stat      pg_subtrans  pg_twophase  pg_xact               postgresql.confpg_dynshmem  pg_ident.conf  pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    PG_VERSION   postgresql.auto.conf[edb@localhost bin]$ [edb@localhost bin]$ ThanksKashif ZeeshanOn Tue, Apr 7, 2020 at 4:03 PM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:On Fri, Apr 3, 2020 at 3:01 PM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:Hi AsifWhen a non-existent slot is used with tablespace then correct error is displayed but then the backup folder is not cleaned and leaves a corrupt backup.Steps=======edb@localhost bin]$ [edb@localhost bin]$ mkdir /home/edb/tbl1[edb@localhost bin]$ mkdir /home/edb/tbl_res[edb@localhost bin]$ postgres=#  create tablespace tbl1 location '/home/edb/tbl1';CREATE TABLESPACEpostgres=# postgres=# create table t1 (a int) tablespace tbl1;CREATE TABLEpostgres=# insert into t1 values(100);INSERT 0 1postgres=# insert into t1 values(200);INSERT 0 1postgres=# insert into t1 values(300);INSERT 0 1postgres=# [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -j 2 -D  /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S testpg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test\" does not existpg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: write-ahead log end point: 0/2E000100pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: error: child thread exited with error 1[edb@localhost bin]$ backup folder not cleaned[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ ls /home/edb/Desktop/backupbackup_label  global        pg_dynshmem  pg_ident.conf  pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    PG_VERSION  pg_xact               postgresql.confbase          pg_commit_ts  pg_hba.conf  pg_logical     pg_notify     pg_serial    pg_stat       pg_subtrans  pg_twophase  pg_wal      postgresql.auto.conf[edb@localhost bin]$ If the same case is executed without the parallel backup patch then the backup folder is cleaned after the error is displayed.[edb@localhost bin]$ ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test999pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test999\" does not existpg_basebackup: write-ahead log end point: 0/2B000100pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: error: child process exited with exit code 1pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"pg_basebackup: changes to tablespace directories will not be undoneHi AsifA similar case is when DB Server is shut down while the Parallel Backup is in progress then the correct error\n is displayed but then the backup folder is not cleaned and leaves a \ncorrupt backup. I think one bug fix will solve all these cases where clean up is not done when parallel backup is failed.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -j 8pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C1000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_57337\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: backup worker (7) createdpg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.[edb@localhost bin]$ [edb@localhost bin]$ Same case when executed on pg_basebackup without the Parallel backup patch then proper clean up is done.[edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -D  /home/edb/Desktop/backup/ pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C5000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_5590\"pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: removing contents of data directory \"/home/edb/Desktop/backup/\"[edb@localhost bin]$ ThanksOn Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com> wrote:On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>> Why would you need to do that? As long as the process where\n>> STOP_BACKUP can do the check, that seems good enough.\n>\n> Yes, but the user will get the error only after the STOP_BACKUP, not while the backup is\n> in progress. So if the backup is a large one, early error detection would be much beneficial.\n> This is the current behavior of non-parallel backup as well.\n\nBecause non-parallel backup does not feature early detection of this\nerror, it is not necessary to make parallel backup do so. Indeed, it\nis undesirable. If you want to fix that problem, do it on a separate\nthread in a separate patch. A patch proposing to make parallel backup\ninconsistent in behavior with non-parallel backup will be rejected, at\nleast if I have anything to say about it.\n\nTBH, fixing this doesn't seem like an urgent problem to me. The\ncurrent situation is not great, but promotions ought to be relatively\ninfrequent, so I'm not sure it's a huge problem in practice. It is\nalso worth considering whether the right fix is to figure out how to\nmake that case actually work, rather than just making it fail quicker.\nI don't currently understand the reason for the prohibition so I can't\nexpress an intelligent opinion on what the right answer is here, but\nit seems like it ought to be investigated before somebody goes and\nbuilds a bunch of infrastructure to make the error more timely.Non-parallel backup already does the early error checking. I only intendedto make parallel behave the same as non-parallel here. So, I agree withyou that the behavior of parallel backup should be consistent with thenon-parallel one.  Please see the code snippet below from basebackup.c:sendDir()/*\n * Check if the postmaster has signaled us to exit, and abort with an\n * error in that case. The error handler further up will call\n * do_pg_abort_backup() for us. Also check that if the backup was\n * started while still in recovery, the server wasn't promoted.\n * do_pg_stop_backup() will check that too, but it's better to stop\n * the backup early than continue to the end and fail there.\n */\nCHECK_FOR_INTERRUPTS();\nif (RecoveryInProgress() != backup_started_in_recovery)\n ereport(ERROR,\n (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n errmsg(\"the standby was promoted during online backup\"),\n errhint(\"This means that the backup being taken is corrupt \"\n \"and should not be used. \"\n \"Try taking another online backup.\"))); \n\n> Okay, then I will add the shared state. And since we are adding the shared state, we can use\n> that for throttling, progress-reporting and standby early error checking.\n\nPlease propose a grammar here for all the new replication commands you\nplan to add before going and implement everything. That will make it\neasier to hash out the design without forcing you to keep changing the\ncode. Your design should include a sketch of how several sets of\ncoordinating backends taking several concurrent parallel backups will\nend up with one shared state per parallel backup.\n\n> There are two possible options:\n>\n> (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n> (2) (Preferred Option) Use the WAL start location as the BackupID.\n>\n> This BackupID should be given back as a response to start backup command. All client workers\n> must append this ID to all parallel backup replication commands. So that we can use this identifier\n> to search for that particular backup. Does that sound good?\n\nUsing the WAL start location as the backup ID seems like it might be\nproblematic -- could a single checkpoint not end up as the start\nlocation for multiple backups started at the same time? Whether that's\npossible now or not, it seems unwise to hard-wire that assumption into\nthe wire protocol.\n\nI was thinking that perhaps the client should generate a unique backup\nID, e.g. leader does:\n\nSTART_BACKUP unique_backup_id [options]...\n\nAnd then others do:\n\nJOIN_BACKUP unique_backup_id\n\nMy thought is that you will have a number of shared memory structure\nequal to max_wal_senders, each one large enough to hold the shared\nstate for one backup. The shared state will include\nchar[NAMEDATALEN-or-something] which will be used to hold the backup\nID. START_BACKUP would allocate one and copy the name into it;\nJOIN_BACKUP would search for one by name.\n\nIf you want to generate the name on the server side, then I suppose\nSTART_BACKUP would return a result set that includes the backup ID,\nand clients would have to specify that same backup ID when invoking\nJOIN_BACKUP. The rest would stay the same. I am not sure which way is\nbetter. Either way, the backup ID should be something long and hard to\nguess, not e.g. the leader processes' PID. I think we should generate\nit using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\nresult to get a string. That way there's almost no risk of two backup\nIDs colliding accidentally, and even if we somehow had a malicious\nuser trying to screw up somebody else's parallel backup by choosing a\ncolliding backup ID, it would be pretty hard to have any success. A\nuser with enough access to do that sort of thing can probably cause a\nlot worse problems anyway, but it seems pretty easy to guard against\nintentional collisions robustly here, so I think we should.\nOkay so If we are to add another replication command ‘JOIN_BACKUP unique_backup_id’to make workers find the relevant shared state. There won't be any need for changingthe grammar for any other command. The START_BACKUP can return the unique_backup_idin the result set.I am thinking of the following struct for shared state:typedef struct\n{\n char backupid[NAMEDATALEN];\n XLogRecPtr startptr;\n\n slock_t lock;\n int64 throttling_counter;\n bool backup_started_in_recovery;\n} BackupSharedState;The shared state structure entries would be maintained by a shared hash table.There will be one structure per parallel backup. Since a single parallel backupcan engage more than one wal sender, so I think max_wal_senders might be a littletoo much; perhaps max_wal_senders/2 since there will be at least 2 connectionsper parallel backup? Alternatively, we can set a new GUC that defines the maximumnumber of for concurrent parallel backups i.e. ‘max_concurent_backups_allowed = 10’ perhaps, or we can make it user-configurable.The key would be “backupid=hex_encode(pg_random_strong(16))”Checking for Standby Promotion:At the START_BACKUP command, we initialize BackupSharedState.backup_started_in_recovery and keep checking it whenever send_file () is called to send a new file.Throttling:BackupSharedState.throttling_counter - The throttling logic remains the sameas for non-parallel backup with the exception that multiple threads will now beupdating it. So in parallel backup, this will represent the overall bytes thathave been transferred. So the workers would sleep if they have exceeded thelimit. Hence, the shared state carries a lock to safely update the throttlingvalue atomically. Progress Reporting:Although I think we should add progress-reporting for parallel backup as aseparate patch. The relevant entries for progress-reporting such as ‘backup_total’ and ‘backup_streamed’ would be then added to this structureas well.  Grammar:There is a change in the resultset being returned for START_BACKUP command; unique_backup_id is added. Additionally, JOIN_BACKUP replication command isadded. SEND_FILES has been renamed to SEND_FILE. There are no other changesto the grammar.START_BACKUP [LABEL '<label>'] [FAST]  - returns startptr, tli, backup_label, unique_backup_idSTOP_BACKUP [NOWAIT]  - returns startptr, tli, backup_labelJOIN_BACKUP ‘unique_backup_id’  - attaches a shared state identified by ‘unique_backup_id’ to a backend process. LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- Regards====================================Kashif ZeeshanLead Quality Assurance Engineer / ManagerEnterpriseDB CorporationThe Enterprise Postgres Company\n-- Regards====================================Kashif ZeeshanLead Quality Assurance Engineer / ManagerEnterpriseDB CorporationThe Enterprise Postgres Company\n-- --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- Regards====================================Kashif ZeeshanLead Quality Assurance Engineer / ManagerEnterpriseDB CorporationThe Enterprise Postgres Company", "msg_date": "Wed, 8 Apr 2020 18:53:14 +0500", "msg_from": "Kashif Zeeshan <kashif.zeeshan@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, Apr 8, 2020 at 6:53 PM Kashif Zeeshan <\nkashif.zeeshan@enterprisedb.com> wrote:\n\n>\n>\n> On Tue, Apr 7, 2020 at 9:44 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>\n>> Hi,\n>>\n>> Thanks, Kashif and Rajkumar. I have fixed the reported issues.\n>>\n>> I have added the shared state as previously described. The new grammar\n>> changes\n>> are as follows:\n>>\n>> START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]\n>> - This will generate a unique backupid using pg_strong_random(16) and\n>> hex-encoded\n>> it. which is then returned as the result set.\n>> - It will also create a shared state and add it to the hashtable. The\n>> hash table size is set\n>> to BACKUP_HASH_SIZE=10, but since hashtable can expand dynamically,\n>> I think it's\n>> sufficient initial size. max_wal_senders is not used, because it\n>> can be set to quite a\n>> large values.\n>>\n>> JOIN_BACKUP 'backup_id'\n>> - finds 'backup_id' in hashtable and attaches it to server process.\n>>\n>>\n>> SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]\n>> - renamed SEND_FILES to SEND_FILE\n>> - removed START_WAL_LOCATION from this because 'startptr' is now\n>> accessible through\n>> shared state.\n>>\n>> There is no change in other commands:\n>> STOP_BACKUP [NOWAIT]\n>> LIST_TABLESPACES [PROGRESS]\n>> LIST_FILES [TABLESPACE]\n>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>\n>> The current patches (v11) have been rebased to the latest master. The\n>> backup manifest is enabled\n>> by default, so I have disabled it for parallel backup mode and have\n>> generated a warning so that\n>> user is aware of it and not expect it in the backup.\n>>\n>> Hi Asif\n>\n> I have verified the bug fixes, one bug is fixed and working now as\n> expected\n>\n> For the verification of the other bug fixes faced following issues, please\n> have a look.\n>\n>\n> 1) Following bug fixes mentioned below are generating segmentation fault.\n>\n> Please note for reference I have added a description only as steps were\n> given in previous emails of each bug I tried to verify the fix. Backtrace\n> is also added with each case which points to one bug for both the cases.\n>\n> a) The backup failed with errors \"error: could not connect to server:\n> could not look up local user ID 1000: Too many open files\" when the\n> max_wal_senders was set to 2000.\n>\n>\n> [edb@localhost bin]$ ./pg_basebackup -v -j 1990 -D\n> /home/edb/Desktop/backup/\n> pg_basebackup: warning: backup manifest is disabled in parallel backup mode\n> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n> pg_basebackup: checkpoint completed\n> pg_basebackup: write-ahead log start point: 0/2000028 on timeline 1\n> pg_basebackup: starting background WAL receiver\n> pg_basebackup: created temporary replication slot \"pg_basebackup_9925\"\n> pg_basebackup: backup worker (0) created\n> pg_basebackup: backup worker (1) created\n> pg_basebackup: backup worker (2) created\n> pg_basebackup: backup worker (3) created\n> ….\n> ….\n> pg_basebackup: backup worker (1014) created\n> pg_basebackup: backup worker (1015) created\n> pg_basebackup: backup worker (1016) created\n> pg_basebackup: backup worker (1017) created\n> pg_basebackup: error: could not connect to server: could not look up local\n> user ID 1000: Too many open files\n> Segmentation fault\n> [edb@localhost bin]$\n>\n>\n> [edb@localhost bin]$\n> [edb@localhost bin]$ gdb pg_basebackup\n> /tmp/cores/core.pg_basebackup.13219.localhost.localdomain.1586349551\n> GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7\n> Copyright (C) 2013 Free Software Foundation, Inc.\n> License GPLv3+: GNU GPL version 3 or later <\n> http://gnu.org/licenses/gpl.html>\n> This is free software: you are free to change and redistribute it.\n> There is NO WARRANTY, to the extent permitted by law. Type \"show copying\"\n> and \"show warranty\" for details.\n> This GDB was configured as \"x86_64-redhat-linux-gnu\".\n> For bug reporting instructions, please see:\n> <http://www.gnu.org/software/gdb/bugs/>...\n> Reading symbols from\n> /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.\n> [New LWP 13219]\n> [New LWP 13222]\n> [Thread debugging using libthread_db enabled]\n> Using host libthread_db library \"/lib64/libthread_db.so.1\".\n> Core was generated by `./pg_basebackup -v -j 1990 -D\n> /home/edb/Desktop/backup/'.\n> Program terminated with signal 11, Segmentation fault.\n> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n> 47 if (INVALID_NOT_TERMINATED_TD_P (pd))\n> (gdb) bt\n> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n> #1 0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978\n> #2 0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332\n> #3 0x00007f2226f76a49 in __run_exit_handlers (status=1,\n> listp=0x7f22272f86c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true)\n> at exit.c:77\n> #4 0x00007f2226f76a95 in __GI_exit (status=<optimized out>) at exit.c:99\n> #5 0x0000000000408c54 in create_parallel_workers (backupinfo=0x952ca0) at\n> pg_basebackup.c:2811\n> #6 0x000000000040798f in BaseBackup () at pg_basebackup.c:2211\n> #7 0x0000000000408b4d in main (argc=6, argv=0x7ffe3dabc718) at\n> pg_basebackup.c:2765\n> (gdb)\n>\n>\n>\n>\n> b) When executing two backups at the same time, getting FATAL error due to\n> max_wal_senders and instead of exit Backup got completed.\n>\n> [edb@localhost bin]$\n> [edb@localhost bin]$\n> [edb@localhost bin]$ ./pg_basebackup -v -j 8 -D\n> /home/edb/Desktop/backup1/\n> pg_basebackup: warning: backup manifest is disabled in parallel backup mode\n> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n> pg_basebackup: checkpoint completed\n> pg_basebackup: write-ahead log start point: 1/DA000028 on timeline 1\n> pg_basebackup: starting background WAL receiver\n> pg_basebackup: created temporary replication slot \"pg_basebackup_17066\"\n> pg_basebackup: backup worker (0) created\n> pg_basebackup: backup worker (1) created\n> pg_basebackup: backup worker (2) created\n> pg_basebackup: backup worker (3) created\n> pg_basebackup: backup worker (4) created\n> pg_basebackup: backup worker (5) created\n> pg_basebackup: backup worker (6) created\n> pg_basebackup: error: could not connect to server: FATAL: number of\n> requested standby connections exceeds max_wal_senders (currently 10)\n> Segmentation fault (core dumped)\n> [edb@localhost bin]$\n> [edb@localhost bin]$\n> [edb@localhost bin]$ gdb pg_basebackup\n> /tmp/cores/core.pg_basebackup.17041.localhost.localdomain.1586353696\n> GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7\n> Copyright (C) 2013 Free Software Foundation, Inc.\n> License GPLv3+: GNU GPL version 3 or later <\n> http://gnu.org/licenses/gpl.html>\n> This is free software: you are free to change and redistribute it.\n> There is NO WARRANTY, to the extent permitted by law. Type \"show copying\"\n> and \"show warranty\" for details.\n> This GDB was configured as \"x86_64-redhat-linux-gnu\".\n> For bug reporting instructions, please see:\n> <http://www.gnu.org/software/gdb/bugs/>...\n> Reading symbols from\n> /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.\n> [New LWP 17041]\n> [New LWP 17067]\n> [Thread debugging using libthread_db enabled]\n> Using host libthread_db library \"/lib64/libthread_db.so.1\".\n> Core was generated by `./pg_basebackup -v -j 8 -D\n> /home/edb/Desktop/backup1/'.\n> Program terminated with signal 11, Segmentation fault.\n> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n> 47 if (INVALID_NOT_TERMINATED_TD_P (pd))\n> (gdb) bt\n> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n> #1 0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978\n> #2 0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332\n> #3 0x00007f051edc1a49 in __run_exit_handlers (status=1,\n> listp=0x7f051f1436c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true)\n> at exit.c:77\n> #4 0x00007f051edc1a95 in __GI_exit (status=<optimized out>) at exit.c:99\n> #5 0x0000000000408c54 in create_parallel_workers (backupinfo=0x1c6dca0)\n> at pg_basebackup.c:2811\n> #6 0x000000000040798f in BaseBackup () at pg_basebackup.c:2211\n> #7 0x0000000000408b4d in main (argc=6, argv=0x7ffdb76a6d68) at\n> pg_basebackup.c:2765\n> (gdb)\n>\n>\n>\n>\n> 2) The following bug is not fixed yet\n>\n> A similar case is when DB Server is shut down while the Parallel Backup is\n> in progress then the correct error is displayed but then the backup folder\n> is not cleaned and leaves a corrupt backup.\n>\n> [edb@localhost bin]$\n> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/ -j 8\n> pg_basebackup: warning: backup manifest is disabled in parallel backup mode\n> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n> pg_basebackup: checkpoint completed\n> pg_basebackup: write-ahead log start point: 0/A0000028 on timeline 1\n> pg_basebackup: starting background WAL receiver\n> pg_basebackup: created temporary replication slot \"pg_basebackup_16235\"\n> pg_basebackup: backup worker (0) created\n> pg_basebackup: backup worker (1) created\n> pg_basebackup: backup worker (2) created\n> pg_basebackup: backup worker (3) created\n> pg_basebackup: backup worker (4) created\n> pg_basebackup: backup worker (5) created\n> pg_basebackup: backup worker (6) created\n> pg_basebackup: backup worker (7) created\n> pg_basebackup: error: could not read COPY data: server closed the\n> connection unexpectedly\n> This probably means the server terminated abnormally\n> before or while processing the request.\n> pg_basebackup: error: could not read COPY data: server closed the\n> connection unexpectedly\n> This probably means the server terminated abnormally\n> before or while processing the request.\n> pg_basebackup: removing contents of data directory\n> \"/home/edb/Desktop/backup/\"\n> pg_basebackup: error: could not read COPY data: server closed the\n> connection unexpectedly\n> This probably means the server terminated abnormally\n> before or while processing the request.\n> [edb@localhost bin]$\n> [edb@localhost bin]$\n> [edb@localhost bin]$\n>\n>\n>\n> [edb@localhost bin]$\n> [edb@localhost bin]$ ls /home/edb/Desktop/backup\n> base pg_hba.conf pg_logical pg_notify pg_serial\n> pg_stat pg_subtrans pg_twophase pg_xact postgresql.conf\n> pg_dynshmem pg_ident.conf pg_multixact pg_replslot pg_snapshots\n> pg_stat_tmp pg_tblspc PG_VERSION postgresql.auto.conf\n> [edb@localhost bin]$\n> [edb@localhost bin]$\n>\n>\n>\n>\n> Thanks\n> Kashif Zeeshan\n>\n>>\n>>\n>> On Tue, Apr 7, 2020 at 4:03 PM Kashif Zeeshan <\n>> kashif.zeeshan@enterprisedb.com> wrote:\n>>\n>>>\n>>>\n>>> On Fri, Apr 3, 2020 at 3:01 PM Kashif Zeeshan <\n>>> kashif.zeeshan@enterprisedb.com> wrote:\n>>>\n>>>> Hi Asif\n>>>>\n>>>> When a non-existent slot is used with tablespace then correct error is\n>>>> displayed but then the backup folder is not cleaned and leaves a corrupt\n>>>> backup.\n>>>>\n>>>> Steps\n>>>> =======\n>>>>\n>>>> edb@localhost bin]$\n>>>> [edb@localhost bin]$ mkdir /home/edb/tbl1\n>>>> [edb@localhost bin]$ mkdir /home/edb/tbl_res\n>>>> [edb@localhost bin]$\n>>>> postgres=# create tablespace tbl1 location '/home/edb/tbl1';\n>>>> CREATE TABLESPACE\n>>>> postgres=#\n>>>> postgres=# create table t1 (a int) tablespace tbl1;\n>>>> CREATE TABLE\n>>>> postgres=# insert into t1 values(100);\n>>>> INSERT 0 1\n>>>> postgres=# insert into t1 values(200);\n>>>> INSERT 0 1\n>>>> postgres=# insert into t1 values(300);\n>>>> INSERT 0 1\n>>>> postgres=#\n>>>>\n>>>>\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$ ./pg_basebackup -v -j 2 -D\n>>>> /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test\n>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>> complete\n>>>> pg_basebackup: checkpoint completed\n>>>> pg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1\n>>>> pg_basebackup: starting background WAL receiver\n>>>> pg_basebackup: error: could not send replication command\n>>>> \"START_REPLICATION\": ERROR: replication slot \"test\" does not exist\n>>>> pg_basebackup: backup worker (0) created\n>>>> pg_basebackup: backup worker (1) created\n>>>> pg_basebackup: write-ahead log end point: 0/2E000100\n>>>> pg_basebackup: waiting for background process to finish streaming ...\n>>>> pg_basebackup: error: child thread exited with error 1\n>>>> [edb@localhost bin]$\n>>>>\n>>>> backup folder not cleaned\n>>>>\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$ ls /home/edb/Desktop/backup\n>>>> backup_label global pg_dynshmem pg_ident.conf pg_multixact\n>>>> pg_replslot pg_snapshots pg_stat_tmp pg_tblspc PG_VERSION pg_xact\n>>>> postgresql.conf\n>>>> base pg_commit_ts pg_hba.conf pg_logical pg_notify\n>>>> pg_serial pg_stat pg_subtrans pg_twophase pg_wal\n>>>> postgresql.auto.conf\n>>>> [edb@localhost bin]$\n>>>>\n>>>>\n>>>>\n>>>>\n>>>> If the same case is executed without the parallel backup patch then the\n>>>> backup folder is cleaned after the error is displayed.\n>>>>\n>>>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>>>> -T /home/edb/tbl1=/home/edb/tbl_res -S test999\n>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>> complete\n>>>> pg_basebackup: checkpoint completed\n>>>> pg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1\n>>>> pg_basebackup: starting background WAL receiver\n>>>> pg_basebackup: error: could not send replication command\n>>>> \"START_REPLICATION\": ERROR: replication slot \"test999\" does not exist\n>>>> pg_basebackup: write-ahead log end point: 0/2B000100\n>>>> pg_basebackup: waiting for background process to finish streaming ...\n>>>> pg_basebackup: error: child process exited with exit code 1\n>>>> *pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"*\n>>>> pg_basebackup: changes to tablespace directories will not be undone\n>>>>\n>>>\n>>>\n>>> Hi Asif\n>>>\n>>> A similar case is when DB Server is shut down while the Parallel Backup\n>>> is in progress then the correct error is displayed but then the backup\n>>> folder is not cleaned and leaves a corrupt backup. I think one bug fix will\n>>> solve all these cases where clean up is not done when parallel backup is\n>>> failed.\n>>>\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>>> -j 8\n>>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>>> pg_basebackup: checkpoint completed\n>>> pg_basebackup: write-ahead log start point: 0/C1000028 on timeline 1\n>>> pg_basebackup: starting background WAL receiver\n>>> pg_basebackup: created temporary replication slot \"pg_basebackup_57337\"\n>>> pg_basebackup: backup worker (0) created\n>>> pg_basebackup: backup worker (1) created\n>>> pg_basebackup: backup worker (2) created\n>>> pg_basebackup: backup worker (3) created\n>>> pg_basebackup: backup worker (4) created\n>>> pg_basebackup: backup worker (5) created\n>>> pg_basebackup: backup worker (6) created\n>>> pg_basebackup: backup worker (7) created\n>>> pg_basebackup: error: could not read COPY data: server closed the\n>>> connection unexpectedly\n>>> This probably means the server terminated abnormally\n>>> before or while processing the request.\n>>> pg_basebackup: error: could not read COPY data: server closed the\n>>> connection unexpectedly\n>>> This probably means the server terminated abnormally\n>>> before or while processing the request.\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$\n>>>\n>>> Same case when executed on pg_basebackup without the Parallel backup\n>>> patch then proper clean up is done.\n>>>\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>>> pg_basebackup: checkpoint completed\n>>> pg_basebackup: write-ahead log start point: 0/C5000028 on timeline 1\n>>> pg_basebackup: starting background WAL receiver\n>>> pg_basebackup: created temporary replication slot \"pg_basebackup_5590\"\n>>> pg_basebackup: error: could not read COPY data: server closed the\n>>> connection unexpectedly\n>>> This probably means the server terminated abnormally\n>>> before or while processing the request.\n>>> pg_basebackup: removing contents of data directory\n>>> \"/home/edb/Desktop/backup/\"\n>>> [edb@localhost bin]$\n>>>\n>>> Thanks\n>>>\n>>>\n>>>>\n>>>> On Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com>\n>>>> wrote:\n>>>>\n>>>>>\n>>>>>\n>>>>> On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com>\n>>>>> wrote:\n>>>>>\n>>>>>> On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com>\n>>>>>> wrote:\n>>>>>> >> Why would you need to do that? As long as the process where\n>>>>>> >> STOP_BACKUP can do the check, that seems good enough.\n>>>>>> >\n>>>>>> > Yes, but the user will get the error only after the STOP_BACKUP,\n>>>>>> not while the backup is\n>>>>>> > in progress. So if the backup is a large one, early error detection\n>>>>>> would be much beneficial.\n>>>>>> > This is the current behavior of non-parallel backup as well.\n>>>>>>\n>>>>>> Because non-parallel backup does not feature early detection of this\n>>>>>> error, it is not necessary to make parallel backup do so. Indeed, it\n>>>>>> is undesirable. If you want to fix that problem, do it on a separate\n>>>>>> thread in a separate patch. A patch proposing to make parallel backup\n>>>>>> inconsistent in behavior with non-parallel backup will be rejected, at\n>>>>>> least if I have anything to say about it.\n>>>>>>\n>>>>>> TBH, fixing this doesn't seem like an urgent problem to me. The\n>>>>>> current situation is not great, but promotions ought to be relatively\n>>>>>> infrequent, so I'm not sure it's a huge problem in practice. It is\n>>>>>> also worth considering whether the right fix is to figure out how to\n>>>>>> make that case actually work, rather than just making it fail quicker.\n>>>>>> I don't currently understand the reason for the prohibition so I can't\n>>>>>> express an intelligent opinion on what the right answer is here, but\n>>>>>> it seems like it ought to be investigated before somebody goes and\n>>>>>> builds a bunch of infrastructure to make the error more timely.\n>>>>>>\n>>>>>\n>>>>> Non-parallel backup already does the early error checking. I only\n>>>>> intended\n>>>>>\n>>>>> to make parallel behave the same as non-parallel here. So, I agree with\n>>>>>\n>>>>> you that the behavior of parallel backup should be consistent with the\n>>>>>\n>>>>> non-parallel one. Please see the code snippet below from\n>>>>>\n>>>>> basebackup.c:sendDir()\n>>>>>\n>>>>>\n>>>>> /*\n>>>>>>\n>>>>>> * Check if the postmaster has signaled us to exit, and abort with an\n>>>>>>\n>>>>>> * error in that case. The error handler further up will call\n>>>>>>\n>>>>>> * do_pg_abort_backup() for us. Also check that if the backup was\n>>>>>>\n>>>>>> * started while still in recovery, the server wasn't promoted.\n>>>>>>\n>>>>>> * do_pg_stop_backup() will check that too, but it's better to stop\n>>>>>>\n>>>>>> * the backup early than continue to the end and fail there.\n>>>>>>\n>>>>>> */\n>>>>>>\n>>>>>> CHECK_FOR_INTERRUPTS();\n>>>>>>\n>>>>>> *if* (RecoveryInProgress() != backup_started_in_recovery)\n>>>>>>\n>>>>>> ereport(ERROR,\n>>>>>>\n>>>>>> (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n>>>>>>\n>>>>>> errmsg(\"the standby was promoted during online backup\"),\n>>>>>>\n>>>>>> errhint(\"This means that the backup being taken is corrupt \"\n>>>>>>\n>>>>>> \"and should not be used. \"\n>>>>>>\n>>>>>> \"Try taking another online backup.\")));\n>>>>>>\n>>>>>>\n>>>>>> > Okay, then I will add the shared state. And since we are adding the\n>>>>>> shared state, we can use\n>>>>>> > that for throttling, progress-reporting and standby early error\n>>>>>> checking.\n>>>>>>\n>>>>>> Please propose a grammar here for all the new replication commands you\n>>>>>> plan to add before going and implement everything. That will make it\n>>>>>> easier to hash out the design without forcing you to keep changing the\n>>>>>> code. Your design should include a sketch of how several sets of\n>>>>>> coordinating backends taking several concurrent parallel backups will\n>>>>>> end up with one shared state per parallel backup.\n>>>>>>\n>>>>>> > There are two possible options:\n>>>>>> >\n>>>>>> > (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n>>>>>> > (2) (Preferred Option) Use the WAL start location as the BackupID.\n>>>>>> >\n>>>>>> > This BackupID should be given back as a response to start backup\n>>>>>> command. All client workers\n>>>>>> > must append this ID to all parallel backup replication commands. So\n>>>>>> that we can use this identifier\n>>>>>> > to search for that particular backup. Does that sound good?\n>>>>>>\n>>>>>> Using the WAL start location as the backup ID seems like it might be\n>>>>>> problematic -- could a single checkpoint not end up as the start\n>>>>>> location for multiple backups started at the same time? Whether that's\n>>>>>> possible now or not, it seems unwise to hard-wire that assumption into\n>>>>>> the wire protocol.\n>>>>>>\n>>>>>> I was thinking that perhaps the client should generate a unique backup\n>>>>>> ID, e.g. leader does:\n>>>>>>\n>>>>>> START_BACKUP unique_backup_id [options]...\n>>>>>>\n>>>>>> And then others do:\n>>>>>>\n>>>>>> JOIN_BACKUP unique_backup_id\n>>>>>>\n>>>>>> My thought is that you will have a number of shared memory structure\n>>>>>> equal to max_wal_senders, each one large enough to hold the shared\n>>>>>> state for one backup. The shared state will include\n>>>>>> char[NAMEDATALEN-or-something] which will be used to hold the backup\n>>>>>> ID. START_BACKUP would allocate one and copy the name into it;\n>>>>>> JOIN_BACKUP would search for one by name.\n>>>>>>\n>>>>>> If you want to generate the name on the server side, then I suppose\n>>>>>> START_BACKUP would return a result set that includes the backup ID,\n>>>>>> and clients would have to specify that same backup ID when invoking\n>>>>>> JOIN_BACKUP. The rest would stay the same. I am not sure which way is\n>>>>>> better. Either way, the backup ID should be something long and hard to\n>>>>>> guess, not e.g. the leader processes' PID. I think we should generate\n>>>>>> it using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\n>>>>>> result to get a string. That way there's almost no risk of two backup\n>>>>>> IDs colliding accidentally, and even if we somehow had a malicious\n>>>>>> user trying to screw up somebody else's parallel backup by choosing a\n>>>>>> colliding backup ID, it would be pretty hard to have any success. A\n>>>>>> user with enough access to do that sort of thing can probably cause a\n>>>>>> lot worse problems anyway, but it seems pretty easy to guard against\n>>>>>> intentional collisions robustly here, so I think we should.\n>>>>>>\n>>>>>>\n>>>>> Okay so If we are to add another replication command ‘JOIN_BACKUP\n>>>>> unique_backup_id’\n>>>>> to make workers find the relevant shared state. There won't be any\n>>>>> need for changing\n>>>>> the grammar for any other command. The START_BACKUP can return the\n>>>>> unique_backup_id\n>>>>> in the result set.\n>>>>>\n>>>>> I am thinking of the following struct for shared state:\n>>>>>\n>>>>>> *typedef* *struct*\n>>>>>>\n>>>>>> {\n>>>>>>\n>>>>>> *char* backupid[NAMEDATALEN];\n>>>>>>\n>>>>>> XLogRecPtr startptr;\n>>>>>>\n>>>>>>\n>>>>>> slock_t lock;\n>>>>>>\n>>>>>> int64 throttling_counter;\n>>>>>>\n>>>>>> *bool* backup_started_in_recovery;\n>>>>>>\n>>>>>> } BackupSharedState;\n>>>>>>\n>>>>>>\n>>>>> The shared state structure entries would be maintained by a shared\n>>>>> hash table.\n>>>>> There will be one structure per parallel backup. Since a single\n>>>>> parallel backup\n>>>>> can engage more than one wal sender, so I think max_wal_senders might\n>>>>> be a little\n>>>>> too much; perhaps max_wal_senders/2 since there will be at least 2\n>>>>> connections\n>>>>> per parallel backup? Alternatively, we can set a new GUC that defines\n>>>>> the maximum\n>>>>> number of for concurrent parallel backups i.e.\n>>>>> ‘max_concurent_backups_allowed = 10’\n>>>>> perhaps, or we can make it user-configurable.\n>>>>>\n>>>>> The key would be “backupid=hex_encode(pg_random_strong(16))”\n>>>>>\n>>>>> Checking for Standby Promotion:\n>>>>> At the START_BACKUP command, we initialize\n>>>>> BackupSharedState.backup_started_in_recovery\n>>>>> and keep checking it whenever send_file () is called to send a new\n>>>>> file.\n>>>>>\n>>>>> Throttling:\n>>>>> BackupSharedState.throttling_counter - The throttling logic remains\n>>>>> the same\n>>>>> as for non-parallel backup with the exception that multiple threads\n>>>>> will now be\n>>>>> updating it. So in parallel backup, this will represent the overall\n>>>>> bytes that\n>>>>> have been transferred. So the workers would sleep if they have\n>>>>> exceeded the\n>>>>> limit. Hence, the shared state carries a lock to safely update the\n>>>>> throttling\n>>>>> value atomically.\n>>>>>\n>>>>> Progress Reporting:\n>>>>> Although I think we should add progress-reporting for parallel backup\n>>>>> as a\n>>>>> separate patch. The relevant entries for progress-reporting such as\n>>>>> ‘backup_total’ and ‘backup_streamed’ would be then added to this\n>>>>> structure\n>>>>> as well.\n>>>>>\n>>>>>\n>>>>> Grammar:\n>>>>> There is a change in the resultset being returned for START_BACKUP\n>>>>> command;\n>>>>> unique_backup_id is added. Additionally, JOIN_BACKUP replication\n>>>>> command is\n>>>>> added. SEND_FILES has been renamed to SEND_FILE. There are no other\n>>>>> changes\n>>>>> to the grammar.\n>>>>>\n>>>>> START_BACKUP [LABEL '<label>'] [FAST]\n>>>>> - returns startptr, tli, backup_label, unique_backup_id\n>>>>> STOP_BACKUP [NOWAIT]\n>>>>> - returns startptr, tli, backup_label\n>>>>> JOIN_BACKUP ‘unique_backup_id’\n>>>>> - attaches a shared state identified by ‘unique_backup_id’ to a\n>>>>> backend process.\n>>>>>\n>>>>> LIST_TABLESPACES [PROGRESS]\n>>>>> LIST_FILES [TABLESPACE]\n>>>>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>>>> SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\n>>>>>\n>>>>>\n>\n\nHi,\n\nrebased and updated to the current master (8128b0c1). v13 is attached.\n\n- Fixes the above reported issues.\n\n- Added progress-reporting support for parallel:\nFor this, 'backup_streamed' is moved to a shared structure (BackupState) as\npg_atomic_uint64 variable. The worker processes will keep incrementing this\nvariable.\n\nWhile files are being transferred from server to client. The main process\nremains\nin an idle state. So after each increment, the worker process will signal\nmaster to\nupdate the stats in pg_stat_progress_basebackup view.\n\nThe 'tablespace_streamed' column is not updated and will remain empty. This\nis\nbecause multiple workers may be copying files from different tablespaces.\n\n\n- Added backup manifest:\nThe backend workers maintain their own manifest file which contains a list\nof files\nthat are being transferred by the work. Once all backup files are\ntransferred, the\nworkers will create a temp file as\n('pg_tempdir/temp_file_prefix_backupid.workerid')\nto write the content of the manifest file from BufFile. The workers won’t\nadd the\nheader, nor the WAL information in their manifest. These two will be added\nby the\nmain process while merging all worker manifest files.\n\nThe main process will read these individual files and concatenate them into\na single file\nwhich is then sent back to the client.\n\nThe manifest file is created when the following command is received:\n\n> BUILD_MANIFEST 'backupid'\n\n\nThis is a new replication command. It is sent when pg_basebackup has copied\nall the\n$PGDATA files including WAL files.\n\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Tue, 14 Apr 2020 17:33:16 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif\n\nGetting the following error on Parallel backup when --no-manifest option is\nused.\n\n[edb@localhost bin]$\n[edb@localhost bin]$\n[edb@localhost bin]$ ./pg_basebackup -v -j 5 -D\n /home/edb/Desktop/backup/ --no-manifest\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 0/2000028 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: created temporary replication slot \"pg_basebackup_10223\"\npg_basebackup: backup worker (0) created\npg_basebackup: backup worker (1) created\npg_basebackup: backup worker (2) created\npg_basebackup: backup worker (3) created\npg_basebackup: backup worker (4) created\npg_basebackup: write-ahead log end point: 0/2000100\npg_basebackup: error: could not get data for 'BUILD_MANIFEST': ERROR:\n could not open file\n\"base/pgsql_tmp/pgsql_tmp_b4ef5ac0fd150b2a28caf626bbb1bef2.1\": No such file\nor directory\npg_basebackup: removing contents of data directory\n\"/home/edb/Desktop/backup/\"\n[edb@localhost bin]$\n\nThanks\n\nOn Tue, Apr 14, 2020 at 5:33 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Wed, Apr 8, 2020 at 6:53 PM Kashif Zeeshan <\n> kashif.zeeshan@enterprisedb.com> wrote:\n>\n>>\n>>\n>> On Tue, Apr 7, 2020 at 9:44 PM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>>\n>>> Hi,\n>>>\n>>> Thanks, Kashif and Rajkumar. I have fixed the reported issues.\n>>>\n>>> I have added the shared state as previously described. The new grammar\n>>> changes\n>>> are as follows:\n>>>\n>>> START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]\n>>> - This will generate a unique backupid using pg_strong_random(16)\n>>> and hex-encoded\n>>> it. which is then returned as the result set.\n>>> - It will also create a shared state and add it to the hashtable.\n>>> The hash table size is set\n>>> to BACKUP_HASH_SIZE=10, but since hashtable can expand\n>>> dynamically, I think it's\n>>> sufficient initial size. max_wal_senders is not used, because it\n>>> can be set to quite a\n>>> large values.\n>>>\n>>> JOIN_BACKUP 'backup_id'\n>>> - finds 'backup_id' in hashtable and attaches it to server process.\n>>>\n>>>\n>>> SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]\n>>> - renamed SEND_FILES to SEND_FILE\n>>> - removed START_WAL_LOCATION from this because 'startptr' is now\n>>> accessible through\n>>> shared state.\n>>>\n>>> There is no change in other commands:\n>>> STOP_BACKUP [NOWAIT]\n>>> LIST_TABLESPACES [PROGRESS]\n>>> LIST_FILES [TABLESPACE]\n>>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>>\n>>> The current patches (v11) have been rebased to the latest master. The\n>>> backup manifest is enabled\n>>> by default, so I have disabled it for parallel backup mode and have\n>>> generated a warning so that\n>>> user is aware of it and not expect it in the backup.\n>>>\n>>> Hi Asif\n>>\n>> I have verified the bug fixes, one bug is fixed and working now as\n>> expected\n>>\n>> For the verification of the other bug fixes faced following issues,\n>> please have a look.\n>>\n>>\n>> 1) Following bug fixes mentioned below are generating segmentation fault.\n>>\n>> Please note for reference I have added a description only as steps were\n>> given in previous emails of each bug I tried to verify the fix. Backtrace\n>> is also added with each case which points to one bug for both the cases.\n>>\n>> a) The backup failed with errors \"error: could not connect to server:\n>> could not look up local user ID 1000: Too many open files\" when the\n>> max_wal_senders was set to 2000.\n>>\n>>\n>> [edb@localhost bin]$ ./pg_basebackup -v -j 1990 -D\n>> /home/edb/Desktop/backup/\n>> pg_basebackup: warning: backup manifest is disabled in parallel backup\n>> mode\n>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>> pg_basebackup: checkpoint completed\n>> pg_basebackup: write-ahead log start point: 0/2000028 on timeline 1\n>> pg_basebackup: starting background WAL receiver\n>> pg_basebackup: created temporary replication slot \"pg_basebackup_9925\"\n>> pg_basebackup: backup worker (0) created\n>> pg_basebackup: backup worker (1) created\n>> pg_basebackup: backup worker (2) created\n>> pg_basebackup: backup worker (3) created\n>> ….\n>> ….\n>> pg_basebackup: backup worker (1014) created\n>> pg_basebackup: backup worker (1015) created\n>> pg_basebackup: backup worker (1016) created\n>> pg_basebackup: backup worker (1017) created\n>> pg_basebackup: error: could not connect to server: could not look up\n>> local user ID 1000: Too many open files\n>> Segmentation fault\n>> [edb@localhost bin]$\n>>\n>>\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ gdb pg_basebackup\n>> /tmp/cores/core.pg_basebackup.13219.localhost.localdomain.1586349551\n>> GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7\n>> Copyright (C) 2013 Free Software Foundation, Inc.\n>> License GPLv3+: GNU GPL version 3 or later <\n>> http://gnu.org/licenses/gpl.html>\n>> This is free software: you are free to change and redistribute it.\n>> There is NO WARRANTY, to the extent permitted by law. Type \"show copying\"\n>> and \"show warranty\" for details.\n>> This GDB was configured as \"x86_64-redhat-linux-gnu\".\n>> For bug reporting instructions, please see:\n>> <http://www.gnu.org/software/gdb/bugs/>...\n>> Reading symbols from\n>> /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.\n>> [New LWP 13219]\n>> [New LWP 13222]\n>> [Thread debugging using libthread_db enabled]\n>> Using host libthread_db library \"/lib64/libthread_db.so.1\".\n>> Core was generated by `./pg_basebackup -v -j 1990 -D\n>> /home/edb/Desktop/backup/'.\n>> Program terminated with signal 11, Segmentation fault.\n>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>> 47 if (INVALID_NOT_TERMINATED_TD_P (pd))\n>> (gdb) bt\n>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>> #1 0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978\n>> #2 0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332\n>> #3 0x00007f2226f76a49 in __run_exit_handlers (status=1,\n>> listp=0x7f22272f86c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true)\n>> at exit.c:77\n>> #4 0x00007f2226f76a95 in __GI_exit (status=<optimized out>) at exit.c:99\n>> #5 0x0000000000408c54 in create_parallel_workers (backupinfo=0x952ca0)\n>> at pg_basebackup.c:2811\n>> #6 0x000000000040798f in BaseBackup () at pg_basebackup.c:2211\n>> #7 0x0000000000408b4d in main (argc=6, argv=0x7ffe3dabc718) at\n>> pg_basebackup.c:2765\n>> (gdb)\n>>\n>>\n>>\n>>\n>> b) When executing two backups at the same time, getting FATAL error due\n>> to max_wal_senders and instead of exit Backup got completed.\n>>\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ ./pg_basebackup -v -j 8 -D\n>> /home/edb/Desktop/backup1/\n>> pg_basebackup: warning: backup manifest is disabled in parallel backup\n>> mode\n>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>> pg_basebackup: checkpoint completed\n>> pg_basebackup: write-ahead log start point: 1/DA000028 on timeline 1\n>> pg_basebackup: starting background WAL receiver\n>> pg_basebackup: created temporary replication slot \"pg_basebackup_17066\"\n>> pg_basebackup: backup worker (0) created\n>> pg_basebackup: backup worker (1) created\n>> pg_basebackup: backup worker (2) created\n>> pg_basebackup: backup worker (3) created\n>> pg_basebackup: backup worker (4) created\n>> pg_basebackup: backup worker (5) created\n>> pg_basebackup: backup worker (6) created\n>> pg_basebackup: error: could not connect to server: FATAL: number of\n>> requested standby connections exceeds max_wal_senders (currently 10)\n>> Segmentation fault (core dumped)\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ gdb pg_basebackup\n>> /tmp/cores/core.pg_basebackup.17041.localhost.localdomain.1586353696\n>> GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7\n>> Copyright (C) 2013 Free Software Foundation, Inc.\n>> License GPLv3+: GNU GPL version 3 or later <\n>> http://gnu.org/licenses/gpl.html>\n>> This is free software: you are free to change and redistribute it.\n>> There is NO WARRANTY, to the extent permitted by law. Type \"show copying\"\n>> and \"show warranty\" for details.\n>> This GDB was configured as \"x86_64-redhat-linux-gnu\".\n>> For bug reporting instructions, please see:\n>> <http://www.gnu.org/software/gdb/bugs/>...\n>> Reading symbols from\n>> /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.\n>> [New LWP 17041]\n>> [New LWP 17067]\n>> [Thread debugging using libthread_db enabled]\n>> Using host libthread_db library \"/lib64/libthread_db.so.1\".\n>> Core was generated by `./pg_basebackup -v -j 8 -D\n>> /home/edb/Desktop/backup1/'.\n>> Program terminated with signal 11, Segmentation fault.\n>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>> 47 if (INVALID_NOT_TERMINATED_TD_P (pd))\n>> (gdb) bt\n>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>> #1 0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978\n>> #2 0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332\n>> #3 0x00007f051edc1a49 in __run_exit_handlers (status=1,\n>> listp=0x7f051f1436c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true)\n>> at exit.c:77\n>> #4 0x00007f051edc1a95 in __GI_exit (status=<optimized out>) at exit.c:99\n>> #5 0x0000000000408c54 in create_parallel_workers (backupinfo=0x1c6dca0)\n>> at pg_basebackup.c:2811\n>> #6 0x000000000040798f in BaseBackup () at pg_basebackup.c:2211\n>> #7 0x0000000000408b4d in main (argc=6, argv=0x7ffdb76a6d68) at\n>> pg_basebackup.c:2765\n>> (gdb)\n>>\n>>\n>>\n>>\n>> 2) The following bug is not fixed yet\n>>\n>> A similar case is when DB Server is shut down while the Parallel Backup\n>> is in progress then the correct error is displayed but then the backup\n>> folder is not cleaned and leaves a corrupt backup.\n>>\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/ -j\n>> 8\n>> pg_basebackup: warning: backup manifest is disabled in parallel backup\n>> mode\n>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>> pg_basebackup: checkpoint completed\n>> pg_basebackup: write-ahead log start point: 0/A0000028 on timeline 1\n>> pg_basebackup: starting background WAL receiver\n>> pg_basebackup: created temporary replication slot \"pg_basebackup_16235\"\n>> pg_basebackup: backup worker (0) created\n>> pg_basebackup: backup worker (1) created\n>> pg_basebackup: backup worker (2) created\n>> pg_basebackup: backup worker (3) created\n>> pg_basebackup: backup worker (4) created\n>> pg_basebackup: backup worker (5) created\n>> pg_basebackup: backup worker (6) created\n>> pg_basebackup: backup worker (7) created\n>> pg_basebackup: error: could not read COPY data: server closed the\n>> connection unexpectedly\n>> This probably means the server terminated abnormally\n>> before or while processing the request.\n>> pg_basebackup: error: could not read COPY data: server closed the\n>> connection unexpectedly\n>> This probably means the server terminated abnormally\n>> before or while processing the request.\n>> pg_basebackup: removing contents of data directory\n>> \"/home/edb/Desktop/backup/\"\n>> pg_basebackup: error: could not read COPY data: server closed the\n>> connection unexpectedly\n>> This probably means the server terminated abnormally\n>> before or while processing the request.\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>>\n>>\n>>\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ ls /home/edb/Desktop/backup\n>> base pg_hba.conf pg_logical pg_notify pg_serial\n>> pg_stat pg_subtrans pg_twophase pg_xact postgresql.conf\n>> pg_dynshmem pg_ident.conf pg_multixact pg_replslot pg_snapshots\n>> pg_stat_tmp pg_tblspc PG_VERSION postgresql.auto.conf\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>>\n>>\n>>\n>>\n>> Thanks\n>> Kashif Zeeshan\n>>\n>>>\n>>>\n>>> On Tue, Apr 7, 2020 at 4:03 PM Kashif Zeeshan <\n>>> kashif.zeeshan@enterprisedb.com> wrote:\n>>>\n>>>>\n>>>>\n>>>> On Fri, Apr 3, 2020 at 3:01 PM Kashif Zeeshan <\n>>>> kashif.zeeshan@enterprisedb.com> wrote:\n>>>>\n>>>>> Hi Asif\n>>>>>\n>>>>> When a non-existent slot is used with tablespace then correct error is\n>>>>> displayed but then the backup folder is not cleaned and leaves a corrupt\n>>>>> backup.\n>>>>>\n>>>>> Steps\n>>>>> =======\n>>>>>\n>>>>> edb@localhost bin]$\n>>>>> [edb@localhost bin]$ mkdir /home/edb/tbl1\n>>>>> [edb@localhost bin]$ mkdir /home/edb/tbl_res\n>>>>> [edb@localhost bin]$\n>>>>> postgres=# create tablespace tbl1 location '/home/edb/tbl1';\n>>>>> CREATE TABLESPACE\n>>>>> postgres=#\n>>>>> postgres=# create table t1 (a int) tablespace tbl1;\n>>>>> CREATE TABLE\n>>>>> postgres=# insert into t1 values(100);\n>>>>> INSERT 0 1\n>>>>> postgres=# insert into t1 values(200);\n>>>>> INSERT 0 1\n>>>>> postgres=# insert into t1 values(300);\n>>>>> INSERT 0 1\n>>>>> postgres=#\n>>>>>\n>>>>>\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$ ./pg_basebackup -v -j 2 -D\n>>>>> /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test\n>>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>>> complete\n>>>>> pg_basebackup: checkpoint completed\n>>>>> pg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1\n>>>>> pg_basebackup: starting background WAL receiver\n>>>>> pg_basebackup: error: could not send replication command\n>>>>> \"START_REPLICATION\": ERROR: replication slot \"test\" does not exist\n>>>>> pg_basebackup: backup worker (0) created\n>>>>> pg_basebackup: backup worker (1) created\n>>>>> pg_basebackup: write-ahead log end point: 0/2E000100\n>>>>> pg_basebackup: waiting for background process to finish streaming ...\n>>>>> pg_basebackup: error: child thread exited with error 1\n>>>>> [edb@localhost bin]$\n>>>>>\n>>>>> backup folder not cleaned\n>>>>>\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$ ls /home/edb/Desktop/backup\n>>>>> backup_label global pg_dynshmem pg_ident.conf pg_multixact\n>>>>> pg_replslot pg_snapshots pg_stat_tmp pg_tblspc PG_VERSION pg_xact\n>>>>> postgresql.conf\n>>>>> base pg_commit_ts pg_hba.conf pg_logical pg_notify\n>>>>> pg_serial pg_stat pg_subtrans pg_twophase pg_wal\n>>>>> postgresql.auto.conf\n>>>>> [edb@localhost bin]$\n>>>>>\n>>>>>\n>>>>>\n>>>>>\n>>>>> If the same case is executed without the parallel backup patch then\n>>>>> the backup folder is cleaned after the error is displayed.\n>>>>>\n>>>>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>>>>> -T /home/edb/tbl1=/home/edb/tbl_res -S test999\n>>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>>> complete\n>>>>> pg_basebackup: checkpoint completed\n>>>>> pg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1\n>>>>> pg_basebackup: starting background WAL receiver\n>>>>> pg_basebackup: error: could not send replication command\n>>>>> \"START_REPLICATION\": ERROR: replication slot \"test999\" does not exist\n>>>>> pg_basebackup: write-ahead log end point: 0/2B000100\n>>>>> pg_basebackup: waiting for background process to finish streaming ...\n>>>>> pg_basebackup: error: child process exited with exit code 1\n>>>>> *pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"*\n>>>>> pg_basebackup: changes to tablespace directories will not be undone\n>>>>>\n>>>>\n>>>>\n>>>> Hi Asif\n>>>>\n>>>> A similar case is when DB Server is shut down while the Parallel Backup\n>>>> is in progress then the correct error is displayed but then the backup\n>>>> folder is not cleaned and leaves a corrupt backup. I think one bug fix will\n>>>> solve all these cases where clean up is not done when parallel backup is\n>>>> failed.\n>>>>\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>>>> -j 8\n>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>> complete\n>>>> pg_basebackup: checkpoint completed\n>>>> pg_basebackup: write-ahead log start point: 0/C1000028 on timeline 1\n>>>> pg_basebackup: starting background WAL receiver\n>>>> pg_basebackup: created temporary replication slot \"pg_basebackup_57337\"\n>>>> pg_basebackup: backup worker (0) created\n>>>> pg_basebackup: backup worker (1) created\n>>>> pg_basebackup: backup worker (2) created\n>>>> pg_basebackup: backup worker (3) created\n>>>> pg_basebackup: backup worker (4) created\n>>>> pg_basebackup: backup worker (5) created\n>>>> pg_basebackup: backup worker (6) created\n>>>> pg_basebackup: backup worker (7) created\n>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>> connection unexpectedly\n>>>> This probably means the server terminated abnormally\n>>>> before or while processing the request.\n>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>> connection unexpectedly\n>>>> This probably means the server terminated abnormally\n>>>> before or while processing the request.\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$\n>>>>\n>>>> Same case when executed on pg_basebackup without the Parallel backup\n>>>> patch then proper clean up is done.\n>>>>\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>> complete\n>>>> pg_basebackup: checkpoint completed\n>>>> pg_basebackup: write-ahead log start point: 0/C5000028 on timeline 1\n>>>> pg_basebackup: starting background WAL receiver\n>>>> pg_basebackup: created temporary replication slot \"pg_basebackup_5590\"\n>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>> connection unexpectedly\n>>>> This probably means the server terminated abnormally\n>>>> before or while processing the request.\n>>>> pg_basebackup: removing contents of data directory\n>>>> \"/home/edb/Desktop/backup/\"\n>>>> [edb@localhost bin]$\n>>>>\n>>>> Thanks\n>>>>\n>>>>\n>>>>>\n>>>>> On Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com>\n>>>>> wrote:\n>>>>>\n>>>>>>\n>>>>>>\n>>>>>> On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com>\n>>>>>> wrote:\n>>>>>>\n>>>>>>> On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com>\n>>>>>>> wrote:\n>>>>>>> >> Why would you need to do that? As long as the process where\n>>>>>>> >> STOP_BACKUP can do the check, that seems good enough.\n>>>>>>> >\n>>>>>>> > Yes, but the user will get the error only after the STOP_BACKUP,\n>>>>>>> not while the backup is\n>>>>>>> > in progress. So if the backup is a large one, early error\n>>>>>>> detection would be much beneficial.\n>>>>>>> > This is the current behavior of non-parallel backup as well.\n>>>>>>>\n>>>>>>> Because non-parallel backup does not feature early detection of this\n>>>>>>> error, it is not necessary to make parallel backup do so. Indeed, it\n>>>>>>> is undesirable. If you want to fix that problem, do it on a separate\n>>>>>>> thread in a separate patch. A patch proposing to make parallel backup\n>>>>>>> inconsistent in behavior with non-parallel backup will be rejected,\n>>>>>>> at\n>>>>>>> least if I have anything to say about it.\n>>>>>>>\n>>>>>>> TBH, fixing this doesn't seem like an urgent problem to me. The\n>>>>>>> current situation is not great, but promotions ought to be relatively\n>>>>>>> infrequent, so I'm not sure it's a huge problem in practice. It is\n>>>>>>> also worth considering whether the right fix is to figure out how to\n>>>>>>> make that case actually work, rather than just making it fail\n>>>>>>> quicker.\n>>>>>>> I don't currently understand the reason for the prohibition so I\n>>>>>>> can't\n>>>>>>> express an intelligent opinion on what the right answer is here, but\n>>>>>>> it seems like it ought to be investigated before somebody goes and\n>>>>>>> builds a bunch of infrastructure to make the error more timely.\n>>>>>>>\n>>>>>>\n>>>>>> Non-parallel backup already does the early error checking. I only\n>>>>>> intended\n>>>>>>\n>>>>>> to make parallel behave the same as non-parallel here. So, I agree\n>>>>>> with\n>>>>>>\n>>>>>> you that the behavior of parallel backup should be consistent with the\n>>>>>>\n>>>>>> non-parallel one. Please see the code snippet below from\n>>>>>>\n>>>>>> basebackup.c:sendDir()\n>>>>>>\n>>>>>>\n>>>>>> /*\n>>>>>>>\n>>>>>>> * Check if the postmaster has signaled us to exit, and abort with an\n>>>>>>>\n>>>>>>> * error in that case. The error handler further up will call\n>>>>>>>\n>>>>>>> * do_pg_abort_backup() for us. Also check that if the backup was\n>>>>>>>\n>>>>>>> * started while still in recovery, the server wasn't promoted.\n>>>>>>>\n>>>>>>> * do_pg_stop_backup() will check that too, but it's better to stop\n>>>>>>>\n>>>>>>> * the backup early than continue to the end and fail there.\n>>>>>>>\n>>>>>>> */\n>>>>>>>\n>>>>>>> CHECK_FOR_INTERRUPTS();\n>>>>>>>\n>>>>>>> *if* (RecoveryInProgress() != backup_started_in_recovery)\n>>>>>>>\n>>>>>>> ereport(ERROR,\n>>>>>>>\n>>>>>>> (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n>>>>>>>\n>>>>>>> errmsg(\"the standby was promoted during online backup\"),\n>>>>>>>\n>>>>>>> errhint(\"This means that the backup being taken is corrupt \"\n>>>>>>>\n>>>>>>> \"and should not be used. \"\n>>>>>>>\n>>>>>>> \"Try taking another online backup.\")));\n>>>>>>>\n>>>>>>>\n>>>>>>> > Okay, then I will add the shared state. And since we are adding\n>>>>>>> the shared state, we can use\n>>>>>>> > that for throttling, progress-reporting and standby early error\n>>>>>>> checking.\n>>>>>>>\n>>>>>>> Please propose a grammar here for all the new replication commands\n>>>>>>> you\n>>>>>>> plan to add before going and implement everything. That will make it\n>>>>>>> easier to hash out the design without forcing you to keep changing\n>>>>>>> the\n>>>>>>> code. Your design should include a sketch of how several sets of\n>>>>>>> coordinating backends taking several concurrent parallel backups will\n>>>>>>> end up with one shared state per parallel backup.\n>>>>>>>\n>>>>>>> > There are two possible options:\n>>>>>>> >\n>>>>>>> > (1) Server may generate a unique ID i.e. BackupID=<unique_string>\n>>>>>>> OR\n>>>>>>> > (2) (Preferred Option) Use the WAL start location as the BackupID.\n>>>>>>> >\n>>>>>>> > This BackupID should be given back as a response to start backup\n>>>>>>> command. All client workers\n>>>>>>> > must append this ID to all parallel backup replication commands.\n>>>>>>> So that we can use this identifier\n>>>>>>> > to search for that particular backup. Does that sound good?\n>>>>>>>\n>>>>>>> Using the WAL start location as the backup ID seems like it might be\n>>>>>>> problematic -- could a single checkpoint not end up as the start\n>>>>>>> location for multiple backups started at the same time? Whether\n>>>>>>> that's\n>>>>>>> possible now or not, it seems unwise to hard-wire that assumption\n>>>>>>> into\n>>>>>>> the wire protocol.\n>>>>>>>\n>>>>>>> I was thinking that perhaps the client should generate a unique\n>>>>>>> backup\n>>>>>>> ID, e.g. leader does:\n>>>>>>>\n>>>>>>> START_BACKUP unique_backup_id [options]...\n>>>>>>>\n>>>>>>> And then others do:\n>>>>>>>\n>>>>>>> JOIN_BACKUP unique_backup_id\n>>>>>>>\n>>>>>>> My thought is that you will have a number of shared memory structure\n>>>>>>> equal to max_wal_senders, each one large enough to hold the shared\n>>>>>>> state for one backup. The shared state will include\n>>>>>>> char[NAMEDATALEN-or-something] which will be used to hold the backup\n>>>>>>> ID. START_BACKUP would allocate one and copy the name into it;\n>>>>>>> JOIN_BACKUP would search for one by name.\n>>>>>>>\n>>>>>>> If you want to generate the name on the server side, then I suppose\n>>>>>>> START_BACKUP would return a result set that includes the backup ID,\n>>>>>>> and clients would have to specify that same backup ID when invoking\n>>>>>>> JOIN_BACKUP. The rest would stay the same. I am not sure which way is\n>>>>>>> better. Either way, the backup ID should be something long and hard\n>>>>>>> to\n>>>>>>> guess, not e.g. the leader processes' PID. I think we should generate\n>>>>>>> it using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\n>>>>>>> result to get a string. That way there's almost no risk of two backup\n>>>>>>> IDs colliding accidentally, and even if we somehow had a malicious\n>>>>>>> user trying to screw up somebody else's parallel backup by choosing a\n>>>>>>> colliding backup ID, it would be pretty hard to have any success. A\n>>>>>>> user with enough access to do that sort of thing can probably cause a\n>>>>>>> lot worse problems anyway, but it seems pretty easy to guard against\n>>>>>>> intentional collisions robustly here, so I think we should.\n>>>>>>>\n>>>>>>>\n>>>>>> Okay so If we are to add another replication command ‘JOIN_BACKUP\n>>>>>> unique_backup_id’\n>>>>>> to make workers find the relevant shared state. There won't be any\n>>>>>> need for changing\n>>>>>> the grammar for any other command. The START_BACKUP can return the\n>>>>>> unique_backup_id\n>>>>>> in the result set.\n>>>>>>\n>>>>>> I am thinking of the following struct for shared state:\n>>>>>>\n>>>>>>> *typedef* *struct*\n>>>>>>>\n>>>>>>> {\n>>>>>>>\n>>>>>>> *char* backupid[NAMEDATALEN];\n>>>>>>>\n>>>>>>> XLogRecPtr startptr;\n>>>>>>>\n>>>>>>>\n>>>>>>> slock_t lock;\n>>>>>>>\n>>>>>>> int64 throttling_counter;\n>>>>>>>\n>>>>>>> *bool* backup_started_in_recovery;\n>>>>>>>\n>>>>>>> } BackupSharedState;\n>>>>>>>\n>>>>>>>\n>>>>>> The shared state structure entries would be maintained by a shared\n>>>>>> hash table.\n>>>>>> There will be one structure per parallel backup. Since a single\n>>>>>> parallel backup\n>>>>>> can engage more than one wal sender, so I think max_wal_senders might\n>>>>>> be a little\n>>>>>> too much; perhaps max_wal_senders/2 since there will be at least 2\n>>>>>> connections\n>>>>>> per parallel backup? Alternatively, we can set a new GUC that defines\n>>>>>> the maximum\n>>>>>> number of for concurrent parallel backups i.e.\n>>>>>> ‘max_concurent_backups_allowed = 10’\n>>>>>> perhaps, or we can make it user-configurable.\n>>>>>>\n>>>>>> The key would be “backupid=hex_encode(pg_random_strong(16))”\n>>>>>>\n>>>>>> Checking for Standby Promotion:\n>>>>>> At the START_BACKUP command, we initialize\n>>>>>> BackupSharedState.backup_started_in_recovery\n>>>>>> and keep checking it whenever send_file () is called to send a new\n>>>>>> file.\n>>>>>>\n>>>>>> Throttling:\n>>>>>> BackupSharedState.throttling_counter - The throttling logic remains\n>>>>>> the same\n>>>>>> as for non-parallel backup with the exception that multiple threads\n>>>>>> will now be\n>>>>>> updating it. So in parallel backup, this will represent the overall\n>>>>>> bytes that\n>>>>>> have been transferred. So the workers would sleep if they have\n>>>>>> exceeded the\n>>>>>> limit. Hence, the shared state carries a lock to safely update the\n>>>>>> throttling\n>>>>>> value atomically.\n>>>>>>\n>>>>>> Progress Reporting:\n>>>>>> Although I think we should add progress-reporting for parallel backup\n>>>>>> as a\n>>>>>> separate patch. The relevant entries for progress-reporting such as\n>>>>>> ‘backup_total’ and ‘backup_streamed’ would be then added to this\n>>>>>> structure\n>>>>>> as well.\n>>>>>>\n>>>>>>\n>>>>>> Grammar:\n>>>>>> There is a change in the resultset being returned for START_BACKUP\n>>>>>> command;\n>>>>>> unique_backup_id is added. Additionally, JOIN_BACKUP replication\n>>>>>> command is\n>>>>>> added. SEND_FILES has been renamed to SEND_FILE. There are no other\n>>>>>> changes\n>>>>>> to the grammar.\n>>>>>>\n>>>>>> START_BACKUP [LABEL '<label>'] [FAST]\n>>>>>> - returns startptr, tli, backup_label, unique_backup_id\n>>>>>> STOP_BACKUP [NOWAIT]\n>>>>>> - returns startptr, tli, backup_label\n>>>>>> JOIN_BACKUP ‘unique_backup_id’\n>>>>>> - attaches a shared state identified by ‘unique_backup_id’ to a\n>>>>>> backend process.\n>>>>>>\n>>>>>> LIST_TABLESPACES [PROGRESS]\n>>>>>> LIST_FILES [TABLESPACE]\n>>>>>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>>>>> SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\n>>>>>>\n>>>>>>\n>>\n>\n> Hi,\n>\n> rebased and updated to the current master (8128b0c1). v13 is attached.\n>\n> - Fixes the above reported issues.\n>\n> - Added progress-reporting support for parallel:\n> For this, 'backup_streamed' is moved to a shared structure (BackupState) as\n> pg_atomic_uint64 variable. The worker processes will keep incrementing this\n> variable.\n>\n> While files are being transferred from server to client. The main process\n> remains\n> in an idle state. So after each increment, the worker process will signal\n> master to\n> update the stats in pg_stat_progress_basebackup view.\n>\n> The 'tablespace_streamed' column is not updated and will remain empty.\n> This is\n> because multiple workers may be copying files from different tablespaces.\n>\n>\n> - Added backup manifest:\n> The backend workers maintain their own manifest file which contains a list\n> of files\n> that are being transferred by the work. Once all backup files are\n> transferred, the\n> workers will create a temp file as\n> ('pg_tempdir/temp_file_prefix_backupid.workerid')\n> to write the content of the manifest file from BufFile. The workers won’t\n> add the\n> header, nor the WAL information in their manifest. These two will be added\n> by the\n> main process while merging all worker manifest files.\n>\n> The main process will read these individual files and concatenate them\n> into a single file\n> which is then sent back to the client.\n>\n> The manifest file is created when the following command is received:\n>\n>> BUILD_MANIFEST 'backupid'\n>\n>\n> This is a new replication command. It is sent when pg_basebackup has\n> copied all the\n> $PGDATA files including WAL files.\n>\n>\n>\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\n-- \nRegards\n====================================\nKashif Zeeshan\nLead Quality Assurance Engineer / Manager\n\nEnterpriseDB Corporation\nThe Enterprise Postgres Company\n\nHi AsifGetting the following error on Parallel backup when --no-manifest option is used.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -j 5  -D  /home/edb/Desktop/backup/ --no-manifestpg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_10223\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: write-ahead log end point: 0/2000100pg_basebackup: error: could not get data for 'BUILD_MANIFEST': ERROR:  could not open file \"base/pgsql_tmp/pgsql_tmp_b4ef5ac0fd150b2a28caf626bbb1bef2.1\": No such file or directorypg_basebackup: removing contents of data directory \"/home/edb/Desktop/backup/\"[edb@localhost bin]$ ThanksOn Tue, Apr 14, 2020 at 5:33 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Wed, Apr 8, 2020 at 6:53 PM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:On Tue, Apr 7, 2020 at 9:44 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Hi,Thanks, Kashif and Rajkumar. I have fixed the reported issues.I have added the shared state as previously described. The new grammar changesare as follows:START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]    - This will generate a unique backupid using pg_strong_random(16) and hex-encoded      it. which is then returned as the result set.    - It will also create a shared state and add it to the hashtable. The hash table size is set      to BACKUP_HASH_SIZE=10, but since hashtable can expand dynamically, I think it's      sufficient initial size. max_wal_senders is not used, because it can be set to quite a       large values.JOIN_BACKUP 'backup_id'    - finds 'backup_id' in hashtable and attaches it to server process.SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]    - renamed SEND_FILES to SEND_FILE    - removed START_WAL_LOCATION from this because 'startptr' is now accessible through      shared state.There is no change in other commands:STOP_BACKUP [NOWAIT]LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']The current patches (v11) have been rebased to the latest master. The backup manifest is enabledby default, so I have disabled it for parallel backup mode and have generated a warning so thatuser is aware of it and not expect it in the backup.Hi AsifI have verified the bug fixes, one bug is fixed and working now as expected For the verification of the other bug fixes faced following issues, please have a look.1) Following bug fixes mentioned below are generating segmentation fault. Please note for reference I have added a description only as steps were given in previous emails of each bug I tried to verify the fix. Backtrace is also added with each case which points to one bug for both the cases.a) The backup failed with errors \"error: could not connect to server: could not look up local user ID 1000: Too many open files\" when the max_wal_senders was set to 2000. [edb@localhost bin]$ ./pg_basebackup -v -j 1990 -D  /home/edb/Desktop/backup/pg_basebackup: warning: backup manifest is disabled in parallel backup modepg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_9925\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) created….….pg_basebackup: backup worker (1014) createdpg_basebackup: backup worker (1015) createdpg_basebackup: backup worker (1016) createdpg_basebackup: backup worker (1017) createdpg_basebackup: error: could not connect to server: could not look up local user ID 1000: Too many open filesSegmentation fault[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ gdb pg_basebackup /tmp/cores/core.pg_basebackup.13219.localhost.localdomain.1586349551 GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7Copyright (C) 2013 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"and \"show warranty\" for details.This GDB was configured as \"x86_64-redhat-linux-gnu\".For bug reporting instructions, please see:<http://www.gnu.org/software/gdb/bugs/>...Reading symbols from /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.[New LWP 13219][New LWP 13222][Thread debugging using libthread_db enabled]Using host libthread_db library \"/lib64/libthread_db.so.1\".Core was generated by `./pg_basebackup -v -j 1990 -D /home/edb/Desktop/backup/'.Program terminated with signal 11, Segmentation fault.#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:4747\t  if (INVALID_NOT_TERMINATED_TD_P (pd))(gdb) bt#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47#1  0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978#2  0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332#3  0x00007f2226f76a49 in __run_exit_handlers (status=1, listp=0x7f22272f86c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true) at exit.c:77#4  0x00007f2226f76a95 in __GI_exit (status=<optimized out>) at exit.c:99#5  0x0000000000408c54 in create_parallel_workers (backupinfo=0x952ca0) at pg_basebackup.c:2811#6  0x000000000040798f in BaseBackup () at pg_basebackup.c:2211#7  0x0000000000408b4d in main (argc=6, argv=0x7ffe3dabc718) at pg_basebackup.c:2765(gdb) b) When\n executing two backups at the same time, getting FATAL error due to \nmax_wal_senders and instead of exit  Backup got completed.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -j 8 -D  /home/edb/Desktop/backup1/pg_basebackup: warning: backup manifest is disabled in parallel backup modepg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 1/DA000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_17066\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)Segmentation fault (core dumped)[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ gdb pg_basebackup /tmp/cores/core.pg_basebackup.17041.localhost.localdomain.1586353696 GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7Copyright (C) 2013 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"and \"show warranty\" for details.This GDB was configured as \"x86_64-redhat-linux-gnu\".For bug reporting instructions, please see:<http://www.gnu.org/software/gdb/bugs/>...Reading symbols from /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.[New LWP 17041][New LWP 17067][Thread debugging using libthread_db enabled]Using host libthread_db library \"/lib64/libthread_db.so.1\".Core was generated by `./pg_basebackup -v -j 8 -D /home/edb/Desktop/backup1/'.Program terminated with signal 11, Segmentation fault.#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:4747\t  if (INVALID_NOT_TERMINATED_TD_P (pd))(gdb) bt#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47#1  0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978#2  0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332#3  0x00007f051edc1a49 in __run_exit_handlers (status=1, listp=0x7f051f1436c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true) at exit.c:77#4  0x00007f051edc1a95 in __GI_exit (status=<optimized out>) at exit.c:99#5  0x0000000000408c54 in create_parallel_workers (backupinfo=0x1c6dca0) at pg_basebackup.c:2811#6  0x000000000040798f in BaseBackup () at pg_basebackup.c:2211#7  0x0000000000408b4d in main (argc=6, argv=0x7ffdb76a6d68) at pg_basebackup.c:2765(gdb) 2) The following bug is not fixed yetA similar case is when DB Server is shut down while the Parallel Backup is in progress then the correct error\n is displayed but then the backup folder is not cleaned and leaves a \ncorrupt backup. [edb@localhost bin]$ [edb@localhost bin]$ ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -j 8pg_basebackup: warning: backup manifest is disabled in parallel backup modepg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/A0000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_16235\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: backup worker (7) createdpg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: removing contents of data directory \"/home/edb/Desktop/backup/\"pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ ls /home/edb/Desktop/backupbase         pg_hba.conf    pg_logical    pg_notify    pg_serial     pg_stat      pg_subtrans  pg_twophase  pg_xact               postgresql.confpg_dynshmem  pg_ident.conf  pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    PG_VERSION   postgresql.auto.conf[edb@localhost bin]$ [edb@localhost bin]$ ThanksKashif ZeeshanOn Tue, Apr 7, 2020 at 4:03 PM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:On Fri, Apr 3, 2020 at 3:01 PM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:Hi AsifWhen a non-existent slot is used with tablespace then correct error is displayed but then the backup folder is not cleaned and leaves a corrupt backup.Steps=======edb@localhost bin]$ [edb@localhost bin]$ mkdir /home/edb/tbl1[edb@localhost bin]$ mkdir /home/edb/tbl_res[edb@localhost bin]$ postgres=#  create tablespace tbl1 location '/home/edb/tbl1';CREATE TABLESPACEpostgres=# postgres=# create table t1 (a int) tablespace tbl1;CREATE TABLEpostgres=# insert into t1 values(100);INSERT 0 1postgres=# insert into t1 values(200);INSERT 0 1postgres=# insert into t1 values(300);INSERT 0 1postgres=# [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -j 2 -D  /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S testpg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test\" does not existpg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: write-ahead log end point: 0/2E000100pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: error: child thread exited with error 1[edb@localhost bin]$ backup folder not cleaned[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ ls /home/edb/Desktop/backupbackup_label  global        pg_dynshmem  pg_ident.conf  pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    PG_VERSION  pg_xact               postgresql.confbase          pg_commit_ts  pg_hba.conf  pg_logical     pg_notify     pg_serial    pg_stat       pg_subtrans  pg_twophase  pg_wal      postgresql.auto.conf[edb@localhost bin]$ If the same case is executed without the parallel backup patch then the backup folder is cleaned after the error is displayed.[edb@localhost bin]$ ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test999pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test999\" does not existpg_basebackup: write-ahead log end point: 0/2B000100pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: error: child process exited with exit code 1pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"pg_basebackup: changes to tablespace directories will not be undoneHi AsifA similar case is when DB Server is shut down while the Parallel Backup is in progress then the correct error\n is displayed but then the backup folder is not cleaned and leaves a \ncorrupt backup. I think one bug fix will solve all these cases where clean up is not done when parallel backup is failed.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -j 8pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C1000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_57337\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: backup worker (7) createdpg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.[edb@localhost bin]$ [edb@localhost bin]$ Same case when executed on pg_basebackup without the Parallel backup patch then proper clean up is done.[edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -D  /home/edb/Desktop/backup/ pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C5000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_5590\"pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: removing contents of data directory \"/home/edb/Desktop/backup/\"[edb@localhost bin]$ ThanksOn Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com> wrote:On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>> Why would you need to do that? As long as the process where\n>> STOP_BACKUP can do the check, that seems good enough.\n>\n> Yes, but the user will get the error only after the STOP_BACKUP, not while the backup is\n> in progress. So if the backup is a large one, early error detection would be much beneficial.\n> This is the current behavior of non-parallel backup as well.\n\nBecause non-parallel backup does not feature early detection of this\nerror, it is not necessary to make parallel backup do so. Indeed, it\nis undesirable. If you want to fix that problem, do it on a separate\nthread in a separate patch. A patch proposing to make parallel backup\ninconsistent in behavior with non-parallel backup will be rejected, at\nleast if I have anything to say about it.\n\nTBH, fixing this doesn't seem like an urgent problem to me. The\ncurrent situation is not great, but promotions ought to be relatively\ninfrequent, so I'm not sure it's a huge problem in practice. It is\nalso worth considering whether the right fix is to figure out how to\nmake that case actually work, rather than just making it fail quicker.\nI don't currently understand the reason for the prohibition so I can't\nexpress an intelligent opinion on what the right answer is here, but\nit seems like it ought to be investigated before somebody goes and\nbuilds a bunch of infrastructure to make the error more timely.Non-parallel backup already does the early error checking. I only intendedto make parallel behave the same as non-parallel here. So, I agree withyou that the behavior of parallel backup should be consistent with thenon-parallel one.  Please see the code snippet below from basebackup.c:sendDir()/*\n * Check if the postmaster has signaled us to exit, and abort with an\n * error in that case. The error handler further up will call\n * do_pg_abort_backup() for us. Also check that if the backup was\n * started while still in recovery, the server wasn't promoted.\n * do_pg_stop_backup() will check that too, but it's better to stop\n * the backup early than continue to the end and fail there.\n */\nCHECK_FOR_INTERRUPTS();\nif (RecoveryInProgress() != backup_started_in_recovery)\n ereport(ERROR,\n (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n errmsg(\"the standby was promoted during online backup\"),\n errhint(\"This means that the backup being taken is corrupt \"\n \"and should not be used. \"\n \"Try taking another online backup.\"))); \n\n> Okay, then I will add the shared state. And since we are adding the shared state, we can use\n> that for throttling, progress-reporting and standby early error checking.\n\nPlease propose a grammar here for all the new replication commands you\nplan to add before going and implement everything. That will make it\neasier to hash out the design without forcing you to keep changing the\ncode. Your design should include a sketch of how several sets of\ncoordinating backends taking several concurrent parallel backups will\nend up with one shared state per parallel backup.\n\n> There are two possible options:\n>\n> (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n> (2) (Preferred Option) Use the WAL start location as the BackupID.\n>\n> This BackupID should be given back as a response to start backup command. All client workers\n> must append this ID to all parallel backup replication commands. So that we can use this identifier\n> to search for that particular backup. Does that sound good?\n\nUsing the WAL start location as the backup ID seems like it might be\nproblematic -- could a single checkpoint not end up as the start\nlocation for multiple backups started at the same time? Whether that's\npossible now or not, it seems unwise to hard-wire that assumption into\nthe wire protocol.\n\nI was thinking that perhaps the client should generate a unique backup\nID, e.g. leader does:\n\nSTART_BACKUP unique_backup_id [options]...\n\nAnd then others do:\n\nJOIN_BACKUP unique_backup_id\n\nMy thought is that you will have a number of shared memory structure\nequal to max_wal_senders, each one large enough to hold the shared\nstate for one backup. The shared state will include\nchar[NAMEDATALEN-or-something] which will be used to hold the backup\nID. START_BACKUP would allocate one and copy the name into it;\nJOIN_BACKUP would search for one by name.\n\nIf you want to generate the name on the server side, then I suppose\nSTART_BACKUP would return a result set that includes the backup ID,\nand clients would have to specify that same backup ID when invoking\nJOIN_BACKUP. The rest would stay the same. I am not sure which way is\nbetter. Either way, the backup ID should be something long and hard to\nguess, not e.g. the leader processes' PID. I think we should generate\nit using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\nresult to get a string. That way there's almost no risk of two backup\nIDs colliding accidentally, and even if we somehow had a malicious\nuser trying to screw up somebody else's parallel backup by choosing a\ncolliding backup ID, it would be pretty hard to have any success. A\nuser with enough access to do that sort of thing can probably cause a\nlot worse problems anyway, but it seems pretty easy to guard against\nintentional collisions robustly here, so I think we should.\nOkay so If we are to add another replication command ‘JOIN_BACKUP unique_backup_id’to make workers find the relevant shared state. There won't be any need for changingthe grammar for any other command. The START_BACKUP can return the unique_backup_idin the result set.I am thinking of the following struct for shared state:typedef struct\n{\n char backupid[NAMEDATALEN];\n XLogRecPtr startptr;\n\n slock_t lock;\n int64 throttling_counter;\n bool backup_started_in_recovery;\n} BackupSharedState;The shared state structure entries would be maintained by a shared hash table.There will be one structure per parallel backup. Since a single parallel backupcan engage more than one wal sender, so I think max_wal_senders might be a littletoo much; perhaps max_wal_senders/2 since there will be at least 2 connectionsper parallel backup? Alternatively, we can set a new GUC that defines the maximumnumber of for concurrent parallel backups i.e. ‘max_concurent_backups_allowed = 10’ perhaps, or we can make it user-configurable.The key would be “backupid=hex_encode(pg_random_strong(16))”Checking for Standby Promotion:At the START_BACKUP command, we initialize BackupSharedState.backup_started_in_recovery and keep checking it whenever send_file () is called to send a new file.Throttling:BackupSharedState.throttling_counter - The throttling logic remains the sameas for non-parallel backup with the exception that multiple threads will now beupdating it. So in parallel backup, this will represent the overall bytes thathave been transferred. So the workers would sleep if they have exceeded thelimit. Hence, the shared state carries a lock to safely update the throttlingvalue atomically. Progress Reporting:Although I think we should add progress-reporting for parallel backup as aseparate patch. The relevant entries for progress-reporting such as ‘backup_total’ and ‘backup_streamed’ would be then added to this structureas well.  Grammar:There is a change in the resultset being returned for START_BACKUP command; unique_backup_id is added. Additionally, JOIN_BACKUP replication command isadded. SEND_FILES has been renamed to SEND_FILE. There are no other changesto the grammar.START_BACKUP [LABEL '<label>'] [FAST]  - returns startptr, tli, backup_label, unique_backup_idSTOP_BACKUP [NOWAIT]  - returns startptr, tli, backup_labelJOIN_BACKUP ‘unique_backup_id’  - attaches a shared state identified by ‘unique_backup_id’ to a backend process. LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\nHi,rebased and updated to the current master (8128b0c1). v13 is attached.- Fixes the above reported issues.- Added progress-reporting support for parallel:For this, 'backup_streamed' is moved to a shared structure (BackupState) aspg_atomic_uint64 variable. The worker processes will keep incrementing thisvariable.While files are being transferred from server to client. The main process remainsin an idle state. So after each increment, the worker process will signal master toupdate the stats in pg_stat_progress_basebackup view.The 'tablespace_streamed' column is not updated and will remain empty. This isbecause multiple workers may be copying files from different tablespaces.- Added backup manifest:The backend workers maintain their own manifest file which contains a list of filesthat are being transferred by the work. Once all backup files are transferred, theworkers will create a temp file as ('pg_tempdir/temp_file_prefix_backupid.workerid')to write the content of the manifest file from BufFile. The workers won’t add theheader, nor the WAL information in their manifest. These two will be added by themain process while merging all worker manifest files.The main process will read these individual files and concatenate them into a single filewhich is then sent back to the client. The manifest file is created when the following command is received:    BUILD_MANIFEST 'backupid'This is a new replication command. It is sent when pg_basebackup has copied all the$PGDATA files including WAL files.--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- Regards====================================Kashif ZeeshanLead Quality Assurance Engineer / ManagerEnterpriseDB CorporationThe Enterprise Postgres Company", "msg_date": "Tue, 14 Apr 2020 18:32:40 +0500", "msg_from": "Kashif Zeeshan <kashif.zeeshan@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Apr 14, 2020 at 6:32 PM Kashif Zeeshan <\nkashif.zeeshan@enterprisedb.com> wrote:\n\n> Hi Asif\n>\n> Getting the following error on Parallel backup when --no-manifest option\n> is used.\n>\n> [edb@localhost bin]$\n> [edb@localhost bin]$\n> [edb@localhost bin]$ ./pg_basebackup -v -j 5 -D\n> /home/edb/Desktop/backup/ --no-manifest\n> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n> pg_basebackup: checkpoint completed\n> pg_basebackup: write-ahead log start point: 0/2000028 on timeline 1\n> pg_basebackup: starting background WAL receiver\n> pg_basebackup: created temporary replication slot \"pg_basebackup_10223\"\n> pg_basebackup: backup worker (0) created\n> pg_basebackup: backup worker (1) created\n> pg_basebackup: backup worker (2) created\n> pg_basebackup: backup worker (3) created\n> pg_basebackup: backup worker (4) created\n> pg_basebackup: write-ahead log end point: 0/2000100\n> pg_basebackup: error: could not get data for 'BUILD_MANIFEST': ERROR:\n> could not open file\n> \"base/pgsql_tmp/pgsql_tmp_b4ef5ac0fd150b2a28caf626bbb1bef2.1\": No such file\n> or directory\n> pg_basebackup: removing contents of data directory\n> \"/home/edb/Desktop/backup/\"\n> [edb@localhost bin]$\n>\n\nI forgot to make a check for no-manifest. Fixed. Attached is the updated\npatch.\n\n\n> Thanks\n>\n> On Tue, Apr 14, 2020 at 5:33 PM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n>\n>>\n>>\n>> On Wed, Apr 8, 2020 at 6:53 PM Kashif Zeeshan <\n>> kashif.zeeshan@enterprisedb.com> wrote:\n>>\n>>>\n>>>\n>>> On Tue, Apr 7, 2020 at 9:44 PM Asif Rehman <asifr.rehman@gmail.com>\n>>> wrote:\n>>>\n>>>> Hi,\n>>>>\n>>>> Thanks, Kashif and Rajkumar. I have fixed the reported issues.\n>>>>\n>>>> I have added the shared state as previously described. The new grammar\n>>>> changes\n>>>> are as follows:\n>>>>\n>>>> START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]\n>>>> - This will generate a unique backupid using pg_strong_random(16)\n>>>> and hex-encoded\n>>>> it. which is then returned as the result set.\n>>>> - It will also create a shared state and add it to the hashtable.\n>>>> The hash table size is set\n>>>> to BACKUP_HASH_SIZE=10, but since hashtable can expand\n>>>> dynamically, I think it's\n>>>> sufficient initial size. max_wal_senders is not used, because it\n>>>> can be set to quite a\n>>>> large values.\n>>>>\n>>>> JOIN_BACKUP 'backup_id'\n>>>> - finds 'backup_id' in hashtable and attaches it to server process.\n>>>>\n>>>>\n>>>> SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]\n>>>> - renamed SEND_FILES to SEND_FILE\n>>>> - removed START_WAL_LOCATION from this because 'startptr' is now\n>>>> accessible through\n>>>> shared state.\n>>>>\n>>>> There is no change in other commands:\n>>>> STOP_BACKUP [NOWAIT]\n>>>> LIST_TABLESPACES [PROGRESS]\n>>>> LIST_FILES [TABLESPACE]\n>>>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>>>\n>>>> The current patches (v11) have been rebased to the latest master. The\n>>>> backup manifest is enabled\n>>>> by default, so I have disabled it for parallel backup mode and have\n>>>> generated a warning so that\n>>>> user is aware of it and not expect it in the backup.\n>>>>\n>>>> Hi Asif\n>>>\n>>> I have verified the bug fixes, one bug is fixed and working now as\n>>> expected\n>>>\n>>> For the verification of the other bug fixes faced following issues,\n>>> please have a look.\n>>>\n>>>\n>>> 1) Following bug fixes mentioned below are generating segmentation\n>>> fault.\n>>>\n>>> Please note for reference I have added a description only as steps were\n>>> given in previous emails of each bug I tried to verify the fix. Backtrace\n>>> is also added with each case which points to one bug for both the cases.\n>>>\n>>> a) The backup failed with errors \"error: could not connect to server:\n>>> could not look up local user ID 1000: Too many open files\" when the\n>>> max_wal_senders was set to 2000.\n>>>\n>>>\n>>> [edb@localhost bin]$ ./pg_basebackup -v -j 1990 -D\n>>> /home/edb/Desktop/backup/\n>>> pg_basebackup: warning: backup manifest is disabled in parallel backup\n>>> mode\n>>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>>> pg_basebackup: checkpoint completed\n>>> pg_basebackup: write-ahead log start point: 0/2000028 on timeline 1\n>>> pg_basebackup: starting background WAL receiver\n>>> pg_basebackup: created temporary replication slot \"pg_basebackup_9925\"\n>>> pg_basebackup: backup worker (0) created\n>>> pg_basebackup: backup worker (1) created\n>>> pg_basebackup: backup worker (2) created\n>>> pg_basebackup: backup worker (3) created\n>>> ….\n>>> ….\n>>> pg_basebackup: backup worker (1014) created\n>>> pg_basebackup: backup worker (1015) created\n>>> pg_basebackup: backup worker (1016) created\n>>> pg_basebackup: backup worker (1017) created\n>>> pg_basebackup: error: could not connect to server: could not look up\n>>> local user ID 1000: Too many open files\n>>> Segmentation fault\n>>> [edb@localhost bin]$\n>>>\n>>>\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$ gdb pg_basebackup\n>>> /tmp/cores/core.pg_basebackup.13219.localhost.localdomain.1586349551\n>>> GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7\n>>> Copyright (C) 2013 Free Software Foundation, Inc.\n>>> License GPLv3+: GNU GPL version 3 or later <\n>>> http://gnu.org/licenses/gpl.html>\n>>> This is free software: you are free to change and redistribute it.\n>>> There is NO WARRANTY, to the extent permitted by law. Type \"show\n>>> copying\"\n>>> and \"show warranty\" for details.\n>>> This GDB was configured as \"x86_64-redhat-linux-gnu\".\n>>> For bug reporting instructions, please see:\n>>> <http://www.gnu.org/software/gdb/bugs/>...\n>>> Reading symbols from\n>>> /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.\n>>> [New LWP 13219]\n>>> [New LWP 13222]\n>>> [Thread debugging using libthread_db enabled]\n>>> Using host libthread_db library \"/lib64/libthread_db.so.1\".\n>>> Core was generated by `./pg_basebackup -v -j 1990 -D\n>>> /home/edb/Desktop/backup/'.\n>>> Program terminated with signal 11, Segmentation fault.\n>>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>>> 47 if (INVALID_NOT_TERMINATED_TD_P (pd))\n>>> (gdb) bt\n>>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>>> #1 0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978\n>>> #2 0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332\n>>> #3 0x00007f2226f76a49 in __run_exit_handlers (status=1,\n>>> listp=0x7f22272f86c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true)\n>>> at exit.c:77\n>>> #4 0x00007f2226f76a95 in __GI_exit (status=<optimized out>) at exit.c:99\n>>> #5 0x0000000000408c54 in create_parallel_workers (backupinfo=0x952ca0)\n>>> at pg_basebackup.c:2811\n>>> #6 0x000000000040798f in BaseBackup () at pg_basebackup.c:2211\n>>> #7 0x0000000000408b4d in main (argc=6, argv=0x7ffe3dabc718) at\n>>> pg_basebackup.c:2765\n>>> (gdb)\n>>>\n>>>\n>>>\n>>>\n>>> b) When executing two backups at the same time, getting FATAL error due\n>>> to max_wal_senders and instead of exit Backup got completed.\n>>>\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$ ./pg_basebackup -v -j 8 -D\n>>> /home/edb/Desktop/backup1/\n>>> pg_basebackup: warning: backup manifest is disabled in parallel backup\n>>> mode\n>>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>>> pg_basebackup: checkpoint completed\n>>> pg_basebackup: write-ahead log start point: 1/DA000028 on timeline 1\n>>> pg_basebackup: starting background WAL receiver\n>>> pg_basebackup: created temporary replication slot \"pg_basebackup_17066\"\n>>> pg_basebackup: backup worker (0) created\n>>> pg_basebackup: backup worker (1) created\n>>> pg_basebackup: backup worker (2) created\n>>> pg_basebackup: backup worker (3) created\n>>> pg_basebackup: backup worker (4) created\n>>> pg_basebackup: backup worker (5) created\n>>> pg_basebackup: backup worker (6) created\n>>> pg_basebackup: error: could not connect to server: FATAL: number of\n>>> requested standby connections exceeds max_wal_senders (currently 10)\n>>> Segmentation fault (core dumped)\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$ gdb pg_basebackup\n>>> /tmp/cores/core.pg_basebackup.17041.localhost.localdomain.1586353696\n>>> GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7\n>>> Copyright (C) 2013 Free Software Foundation, Inc.\n>>> License GPLv3+: GNU GPL version 3 or later <\n>>> http://gnu.org/licenses/gpl.html>\n>>> This is free software: you are free to change and redistribute it.\n>>> There is NO WARRANTY, to the extent permitted by law. Type \"show\n>>> copying\"\n>>> and \"show warranty\" for details.\n>>> This GDB was configured as \"x86_64-redhat-linux-gnu\".\n>>> For bug reporting instructions, please see:\n>>> <http://www.gnu.org/software/gdb/bugs/>...\n>>> Reading symbols from\n>>> /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.\n>>> [New LWP 17041]\n>>> [New LWP 17067]\n>>> [Thread debugging using libthread_db enabled]\n>>> Using host libthread_db library \"/lib64/libthread_db.so.1\".\n>>> Core was generated by `./pg_basebackup -v -j 8 -D\n>>> /home/edb/Desktop/backup1/'.\n>>> Program terminated with signal 11, Segmentation fault.\n>>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>>> 47 if (INVALID_NOT_TERMINATED_TD_P (pd))\n>>> (gdb) bt\n>>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>>> #1 0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978\n>>> #2 0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332\n>>> #3 0x00007f051edc1a49 in __run_exit_handlers (status=1,\n>>> listp=0x7f051f1436c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true)\n>>> at exit.c:77\n>>> #4 0x00007f051edc1a95 in __GI_exit (status=<optimized out>) at exit.c:99\n>>> #5 0x0000000000408c54 in create_parallel_workers (backupinfo=0x1c6dca0)\n>>> at pg_basebackup.c:2811\n>>> #6 0x000000000040798f in BaseBackup () at pg_basebackup.c:2211\n>>> #7 0x0000000000408b4d in main (argc=6, argv=0x7ffdb76a6d68) at\n>>> pg_basebackup.c:2765\n>>> (gdb)\n>>>\n>>>\n>>>\n>>>\n>>> 2) The following bug is not fixed yet\n>>>\n>>> A similar case is when DB Server is shut down while the Parallel Backup\n>>> is in progress then the correct error is displayed but then the backup\n>>> folder is not cleaned and leaves a corrupt backup.\n>>>\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>>> -j 8\n>>> pg_basebackup: warning: backup manifest is disabled in parallel backup\n>>> mode\n>>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>>> pg_basebackup: checkpoint completed\n>>> pg_basebackup: write-ahead log start point: 0/A0000028 on timeline 1\n>>> pg_basebackup: starting background WAL receiver\n>>> pg_basebackup: created temporary replication slot \"pg_basebackup_16235\"\n>>> pg_basebackup: backup worker (0) created\n>>> pg_basebackup: backup worker (1) created\n>>> pg_basebackup: backup worker (2) created\n>>> pg_basebackup: backup worker (3) created\n>>> pg_basebackup: backup worker (4) created\n>>> pg_basebackup: backup worker (5) created\n>>> pg_basebackup: backup worker (6) created\n>>> pg_basebackup: backup worker (7) created\n>>> pg_basebackup: error: could not read COPY data: server closed the\n>>> connection unexpectedly\n>>> This probably means the server terminated abnormally\n>>> before or while processing the request.\n>>> pg_basebackup: error: could not read COPY data: server closed the\n>>> connection unexpectedly\n>>> This probably means the server terminated abnormally\n>>> before or while processing the request.\n>>> pg_basebackup: removing contents of data directory\n>>> \"/home/edb/Desktop/backup/\"\n>>> pg_basebackup: error: could not read COPY data: server closed the\n>>> connection unexpectedly\n>>> This probably means the server terminated abnormally\n>>> before or while processing the request.\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$\n>>>\n>>>\n>>>\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$ ls /home/edb/Desktop/backup\n>>> base pg_hba.conf pg_logical pg_notify pg_serial\n>>> pg_stat pg_subtrans pg_twophase pg_xact postgresql.conf\n>>> pg_dynshmem pg_ident.conf pg_multixact pg_replslot pg_snapshots\n>>> pg_stat_tmp pg_tblspc PG_VERSION postgresql.auto.conf\n>>> [edb@localhost bin]$\n>>> [edb@localhost bin]$\n>>>\n>>>\n>>>\n>>>\n>>> Thanks\n>>> Kashif Zeeshan\n>>>\n>>>>\n>>>>\n>>>> On Tue, Apr 7, 2020 at 4:03 PM Kashif Zeeshan <\n>>>> kashif.zeeshan@enterprisedb.com> wrote:\n>>>>\n>>>>>\n>>>>>\n>>>>> On Fri, Apr 3, 2020 at 3:01 PM Kashif Zeeshan <\n>>>>> kashif.zeeshan@enterprisedb.com> wrote:\n>>>>>\n>>>>>> Hi Asif\n>>>>>>\n>>>>>> When a non-existent slot is used with tablespace then correct error\n>>>>>> is displayed but then the backup folder is not cleaned and leaves a corrupt\n>>>>>> backup.\n>>>>>>\n>>>>>> Steps\n>>>>>> =======\n>>>>>>\n>>>>>> edb@localhost bin]$\n>>>>>> [edb@localhost bin]$ mkdir /home/edb/tbl1\n>>>>>> [edb@localhost bin]$ mkdir /home/edb/tbl_res\n>>>>>> [edb@localhost bin]$\n>>>>>> postgres=# create tablespace tbl1 location '/home/edb/tbl1';\n>>>>>> CREATE TABLESPACE\n>>>>>> postgres=#\n>>>>>> postgres=# create table t1 (a int) tablespace tbl1;\n>>>>>> CREATE TABLE\n>>>>>> postgres=# insert into t1 values(100);\n>>>>>> INSERT 0 1\n>>>>>> postgres=# insert into t1 values(200);\n>>>>>> INSERT 0 1\n>>>>>> postgres=# insert into t1 values(300);\n>>>>>> INSERT 0 1\n>>>>>> postgres=#\n>>>>>>\n>>>>>>\n>>>>>> [edb@localhost bin]$\n>>>>>> [edb@localhost bin]$ ./pg_basebackup -v -j 2 -D\n>>>>>> /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test\n>>>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>>>> complete\n>>>>>> pg_basebackup: checkpoint completed\n>>>>>> pg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1\n>>>>>> pg_basebackup: starting background WAL receiver\n>>>>>> pg_basebackup: error: could not send replication command\n>>>>>> \"START_REPLICATION\": ERROR: replication slot \"test\" does not exist\n>>>>>> pg_basebackup: backup worker (0) created\n>>>>>> pg_basebackup: backup worker (1) created\n>>>>>> pg_basebackup: write-ahead log end point: 0/2E000100\n>>>>>> pg_basebackup: waiting for background process to finish streaming ...\n>>>>>> pg_basebackup: error: child thread exited with error 1\n>>>>>> [edb@localhost bin]$\n>>>>>>\n>>>>>> backup folder not cleaned\n>>>>>>\n>>>>>> [edb@localhost bin]$\n>>>>>> [edb@localhost bin]$\n>>>>>> [edb@localhost bin]$\n>>>>>> [edb@localhost bin]$ ls /home/edb/Desktop/backup\n>>>>>> backup_label global pg_dynshmem pg_ident.conf pg_multixact\n>>>>>> pg_replslot pg_snapshots pg_stat_tmp pg_tblspc PG_VERSION pg_xact\n>>>>>> postgresql.conf\n>>>>>> base pg_commit_ts pg_hba.conf pg_logical pg_notify\n>>>>>> pg_serial pg_stat pg_subtrans pg_twophase pg_wal\n>>>>>> postgresql.auto.conf\n>>>>>> [edb@localhost bin]$\n>>>>>>\n>>>>>>\n>>>>>>\n>>>>>>\n>>>>>> If the same case is executed without the parallel backup patch then\n>>>>>> the backup folder is cleaned after the error is displayed.\n>>>>>>\n>>>>>> [edb@localhost bin]$ ./pg_basebackup -v -D\n>>>>>> /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test999\n>>>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>>>> complete\n>>>>>> pg_basebackup: checkpoint completed\n>>>>>> pg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1\n>>>>>> pg_basebackup: starting background WAL receiver\n>>>>>> pg_basebackup: error: could not send replication command\n>>>>>> \"START_REPLICATION\": ERROR: replication slot \"test999\" does not exist\n>>>>>> pg_basebackup: write-ahead log end point: 0/2B000100\n>>>>>> pg_basebackup: waiting for background process to finish streaming ...\n>>>>>> pg_basebackup: error: child process exited with exit code 1\n>>>>>> *pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"*\n>>>>>> pg_basebackup: changes to tablespace directories will not be undone\n>>>>>>\n>>>>>\n>>>>>\n>>>>> Hi Asif\n>>>>>\n>>>>> A similar case is when DB Server is shut down while the Parallel\n>>>>> Backup is in progress then the correct error is displayed but then the\n>>>>> backup folder is not cleaned and leaves a corrupt backup. I think one bug\n>>>>> fix will solve all these cases where clean up is not done when parallel\n>>>>> backup is failed.\n>>>>>\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$ ./pg_basebackup -v -D\n>>>>> /home/edb/Desktop/backup/ -j 8\n>>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>>> complete\n>>>>> pg_basebackup: checkpoint completed\n>>>>> pg_basebackup: write-ahead log start point: 0/C1000028 on timeline 1\n>>>>> pg_basebackup: starting background WAL receiver\n>>>>> pg_basebackup: created temporary replication slot \"pg_basebackup_57337\"\n>>>>> pg_basebackup: backup worker (0) created\n>>>>> pg_basebackup: backup worker (1) created\n>>>>> pg_basebackup: backup worker (2) created\n>>>>> pg_basebackup: backup worker (3) created\n>>>>> pg_basebackup: backup worker (4) created\n>>>>> pg_basebackup: backup worker (5) created\n>>>>> pg_basebackup: backup worker (6) created\n>>>>> pg_basebackup: backup worker (7) created\n>>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>>> connection unexpectedly\n>>>>> This probably means the server terminated abnormally\n>>>>> before or while processing the request.\n>>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>>> connection unexpectedly\n>>>>> This probably means the server terminated abnormally\n>>>>> before or while processing the request.\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$\n>>>>>\n>>>>> Same case when executed on pg_basebackup without the Parallel backup\n>>>>> patch then proper clean up is done.\n>>>>>\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$ ./pg_basebackup -v -D\n>>>>> /home/edb/Desktop/backup/\n>>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>>> complete\n>>>>> pg_basebackup: checkpoint completed\n>>>>> pg_basebackup: write-ahead log start point: 0/C5000028 on timeline 1\n>>>>> pg_basebackup: starting background WAL receiver\n>>>>> pg_basebackup: created temporary replication slot \"pg_basebackup_5590\"\n>>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>>> connection unexpectedly\n>>>>> This probably means the server terminated abnormally\n>>>>> before or while processing the request.\n>>>>> pg_basebackup: removing contents of data directory\n>>>>> \"/home/edb/Desktop/backup/\"\n>>>>> [edb@localhost bin]$\n>>>>>\n>>>>> Thanks\n>>>>>\n>>>>>\n>>>>>>\n>>>>>> On Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com>\n>>>>>> wrote:\n>>>>>>\n>>>>>>>\n>>>>>>>\n>>>>>>> On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com>\n>>>>>>> wrote:\n>>>>>>>\n>>>>>>>> On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com>\n>>>>>>>> wrote:\n>>>>>>>> >> Why would you need to do that? As long as the process where\n>>>>>>>> >> STOP_BACKUP can do the check, that seems good enough.\n>>>>>>>> >\n>>>>>>>> > Yes, but the user will get the error only after the STOP_BACKUP,\n>>>>>>>> not while the backup is\n>>>>>>>> > in progress. So if the backup is a large one, early error\n>>>>>>>> detection would be much beneficial.\n>>>>>>>> > This is the current behavior of non-parallel backup as well.\n>>>>>>>>\n>>>>>>>> Because non-parallel backup does not feature early detection of this\n>>>>>>>> error, it is not necessary to make parallel backup do so. Indeed, it\n>>>>>>>> is undesirable. If you want to fix that problem, do it on a separate\n>>>>>>>> thread in a separate patch. A patch proposing to make parallel\n>>>>>>>> backup\n>>>>>>>> inconsistent in behavior with non-parallel backup will be rejected,\n>>>>>>>> at\n>>>>>>>> least if I have anything to say about it.\n>>>>>>>>\n>>>>>>>> TBH, fixing this doesn't seem like an urgent problem to me. The\n>>>>>>>> current situation is not great, but promotions ought to be\n>>>>>>>> relatively\n>>>>>>>> infrequent, so I'm not sure it's a huge problem in practice. It is\n>>>>>>>> also worth considering whether the right fix is to figure out how to\n>>>>>>>> make that case actually work, rather than just making it fail\n>>>>>>>> quicker.\n>>>>>>>> I don't currently understand the reason for the prohibition so I\n>>>>>>>> can't\n>>>>>>>> express an intelligent opinion on what the right answer is here, but\n>>>>>>>> it seems like it ought to be investigated before somebody goes and\n>>>>>>>> builds a bunch of infrastructure to make the error more timely.\n>>>>>>>>\n>>>>>>>\n>>>>>>> Non-parallel backup already does the early error checking. I only\n>>>>>>> intended\n>>>>>>>\n>>>>>>> to make parallel behave the same as non-parallel here. So, I agree\n>>>>>>> with\n>>>>>>>\n>>>>>>> you that the behavior of parallel backup should be consistent with\n>>>>>>> the\n>>>>>>>\n>>>>>>> non-parallel one. Please see the code snippet below from\n>>>>>>>\n>>>>>>> basebackup.c:sendDir()\n>>>>>>>\n>>>>>>>\n>>>>>>> /*\n>>>>>>>>\n>>>>>>>> * Check if the postmaster has signaled us to exit, and abort with\n>>>>>>>> an\n>>>>>>>>\n>>>>>>>> * error in that case. The error handler further up will call\n>>>>>>>>\n>>>>>>>> * do_pg_abort_backup() for us. Also check that if the backup was\n>>>>>>>>\n>>>>>>>> * started while still in recovery, the server wasn't promoted.\n>>>>>>>>\n>>>>>>>> * do_pg_stop_backup() will check that too, but it's better to stop\n>>>>>>>>\n>>>>>>>> * the backup early than continue to the end and fail there.\n>>>>>>>>\n>>>>>>>> */\n>>>>>>>>\n>>>>>>>> CHECK_FOR_INTERRUPTS();\n>>>>>>>>\n>>>>>>>> *if* (RecoveryInProgress() != backup_started_in_recovery)\n>>>>>>>>\n>>>>>>>> ereport(ERROR,\n>>>>>>>>\n>>>>>>>> (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n>>>>>>>>\n>>>>>>>> errmsg(\"the standby was promoted during online backup\"),\n>>>>>>>>\n>>>>>>>> errhint(\"This means that the backup being taken is corrupt \"\n>>>>>>>>\n>>>>>>>> \"and should not be used. \"\n>>>>>>>>\n>>>>>>>> \"Try taking another online backup.\")));\n>>>>>>>>\n>>>>>>>>\n>>>>>>>> > Okay, then I will add the shared state. And since we are adding\n>>>>>>>> the shared state, we can use\n>>>>>>>> > that for throttling, progress-reporting and standby early error\n>>>>>>>> checking.\n>>>>>>>>\n>>>>>>>> Please propose a grammar here for all the new replication commands\n>>>>>>>> you\n>>>>>>>> plan to add before going and implement everything. That will make it\n>>>>>>>> easier to hash out the design without forcing you to keep changing\n>>>>>>>> the\n>>>>>>>> code. Your design should include a sketch of how several sets of\n>>>>>>>> coordinating backends taking several concurrent parallel backups\n>>>>>>>> will\n>>>>>>>> end up with one shared state per parallel backup.\n>>>>>>>>\n>>>>>>>> > There are two possible options:\n>>>>>>>> >\n>>>>>>>> > (1) Server may generate a unique ID i.e. BackupID=<unique_string>\n>>>>>>>> OR\n>>>>>>>> > (2) (Preferred Option) Use the WAL start location as the BackupID.\n>>>>>>>> >\n>>>>>>>> > This BackupID should be given back as a response to start backup\n>>>>>>>> command. All client workers\n>>>>>>>> > must append this ID to all parallel backup replication commands.\n>>>>>>>> So that we can use this identifier\n>>>>>>>> > to search for that particular backup. Does that sound good?\n>>>>>>>>\n>>>>>>>> Using the WAL start location as the backup ID seems like it might be\n>>>>>>>> problematic -- could a single checkpoint not end up as the start\n>>>>>>>> location for multiple backups started at the same time? Whether\n>>>>>>>> that's\n>>>>>>>> possible now or not, it seems unwise to hard-wire that assumption\n>>>>>>>> into\n>>>>>>>> the wire protocol.\n>>>>>>>>\n>>>>>>>> I was thinking that perhaps the client should generate a unique\n>>>>>>>> backup\n>>>>>>>> ID, e.g. leader does:\n>>>>>>>>\n>>>>>>>> START_BACKUP unique_backup_id [options]...\n>>>>>>>>\n>>>>>>>> And then others do:\n>>>>>>>>\n>>>>>>>> JOIN_BACKUP unique_backup_id\n>>>>>>>>\n>>>>>>>> My thought is that you will have a number of shared memory structure\n>>>>>>>> equal to max_wal_senders, each one large enough to hold the shared\n>>>>>>>> state for one backup. The shared state will include\n>>>>>>>> char[NAMEDATALEN-or-something] which will be used to hold the backup\n>>>>>>>> ID. START_BACKUP would allocate one and copy the name into it;\n>>>>>>>> JOIN_BACKUP would search for one by name.\n>>>>>>>>\n>>>>>>>> If you want to generate the name on the server side, then I suppose\n>>>>>>>> START_BACKUP would return a result set that includes the backup ID,\n>>>>>>>> and clients would have to specify that same backup ID when invoking\n>>>>>>>> JOIN_BACKUP. The rest would stay the same. I am not sure which way\n>>>>>>>> is\n>>>>>>>> better. Either way, the backup ID should be something long and hard\n>>>>>>>> to\n>>>>>>>> guess, not e.g. the leader processes' PID. I think we should\n>>>>>>>> generate\n>>>>>>>> it using pg_strong_random, say 8 or 16 bytes, and then hex-encode\n>>>>>>>> the\n>>>>>>>> result to get a string. That way there's almost no risk of two\n>>>>>>>> backup\n>>>>>>>> IDs colliding accidentally, and even if we somehow had a malicious\n>>>>>>>> user trying to screw up somebody else's parallel backup by choosing\n>>>>>>>> a\n>>>>>>>> colliding backup ID, it would be pretty hard to have any success. A\n>>>>>>>> user with enough access to do that sort of thing can probably cause\n>>>>>>>> a\n>>>>>>>> lot worse problems anyway, but it seems pretty easy to guard against\n>>>>>>>> intentional collisions robustly here, so I think we should.\n>>>>>>>>\n>>>>>>>>\n>>>>>>> Okay so If we are to add another replication command ‘JOIN_BACKUP\n>>>>>>> unique_backup_id’\n>>>>>>> to make workers find the relevant shared state. There won't be any\n>>>>>>> need for changing\n>>>>>>> the grammar for any other command. The START_BACKUP can return the\n>>>>>>> unique_backup_id\n>>>>>>> in the result set.\n>>>>>>>\n>>>>>>> I am thinking of the following struct for shared state:\n>>>>>>>\n>>>>>>>> *typedef* *struct*\n>>>>>>>>\n>>>>>>>> {\n>>>>>>>>\n>>>>>>>> *char* backupid[NAMEDATALEN];\n>>>>>>>>\n>>>>>>>> XLogRecPtr startptr;\n>>>>>>>>\n>>>>>>>>\n>>>>>>>> slock_t lock;\n>>>>>>>>\n>>>>>>>> int64 throttling_counter;\n>>>>>>>>\n>>>>>>>> *bool* backup_started_in_recovery;\n>>>>>>>>\n>>>>>>>> } BackupSharedState;\n>>>>>>>>\n>>>>>>>>\n>>>>>>> The shared state structure entries would be maintained by a shared\n>>>>>>> hash table.\n>>>>>>> There will be one structure per parallel backup. Since a single\n>>>>>>> parallel backup\n>>>>>>> can engage more than one wal sender, so I think max_wal_senders\n>>>>>>> might be a little\n>>>>>>> too much; perhaps max_wal_senders/2 since there will be at least 2\n>>>>>>> connections\n>>>>>>> per parallel backup? Alternatively, we can set a new GUC that\n>>>>>>> defines the maximum\n>>>>>>> number of for concurrent parallel backups i.e.\n>>>>>>> ‘max_concurent_backups_allowed = 10’\n>>>>>>> perhaps, or we can make it user-configurable.\n>>>>>>>\n>>>>>>> The key would be “backupid=hex_encode(pg_random_strong(16))”\n>>>>>>>\n>>>>>>> Checking for Standby Promotion:\n>>>>>>> At the START_BACKUP command, we initialize\n>>>>>>> BackupSharedState.backup_started_in_recovery\n>>>>>>> and keep checking it whenever send_file () is called to send a new\n>>>>>>> file.\n>>>>>>>\n>>>>>>> Throttling:\n>>>>>>> BackupSharedState.throttling_counter - The throttling logic remains\n>>>>>>> the same\n>>>>>>> as for non-parallel backup with the exception that multiple threads\n>>>>>>> will now be\n>>>>>>> updating it. So in parallel backup, this will represent the overall\n>>>>>>> bytes that\n>>>>>>> have been transferred. So the workers would sleep if they have\n>>>>>>> exceeded the\n>>>>>>> limit. Hence, the shared state carries a lock to safely update the\n>>>>>>> throttling\n>>>>>>> value atomically.\n>>>>>>>\n>>>>>>> Progress Reporting:\n>>>>>>> Although I think we should add progress-reporting for parallel\n>>>>>>> backup as a\n>>>>>>> separate patch. The relevant entries for progress-reporting such as\n>>>>>>> ‘backup_total’ and ‘backup_streamed’ would be then added to this\n>>>>>>> structure\n>>>>>>> as well.\n>>>>>>>\n>>>>>>>\n>>>>>>> Grammar:\n>>>>>>> There is a change in the resultset being returned for START_BACKUP\n>>>>>>> command;\n>>>>>>> unique_backup_id is added. Additionally, JOIN_BACKUP replication\n>>>>>>> command is\n>>>>>>> added. SEND_FILES has been renamed to SEND_FILE. There are no other\n>>>>>>> changes\n>>>>>>> to the grammar.\n>>>>>>>\n>>>>>>> START_BACKUP [LABEL '<label>'] [FAST]\n>>>>>>> - returns startptr, tli, backup_label, unique_backup_id\n>>>>>>> STOP_BACKUP [NOWAIT]\n>>>>>>> - returns startptr, tli, backup_label\n>>>>>>> JOIN_BACKUP ‘unique_backup_id’\n>>>>>>> - attaches a shared state identified by ‘unique_backup_id’ to a\n>>>>>>> backend process.\n>>>>>>>\n>>>>>>> LIST_TABLESPACES [PROGRESS]\n>>>>>>> LIST_FILES [TABLESPACE]\n>>>>>>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>>>>>> SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\n>>>>>>>\n>>>>>>>\n>>>\n>>\n>> Hi,\n>>\n>> rebased and updated to the current master (8128b0c1). v13 is attached.\n>>\n>> - Fixes the above reported issues.\n>>\n>> - Added progress-reporting support for parallel:\n>> For this, 'backup_streamed' is moved to a shared structure (BackupState)\n>> as\n>> pg_atomic_uint64 variable. The worker processes will keep incrementing\n>> this\n>> variable.\n>>\n>> While files are being transferred from server to client. The main process\n>> remains\n>> in an idle state. So after each increment, the worker process will signal\n>> master to\n>> update the stats in pg_stat_progress_basebackup view.\n>>\n>> The 'tablespace_streamed' column is not updated and will remain empty.\n>> This is\n>> because multiple workers may be copying files from different tablespaces.\n>>\n>>\n>> - Added backup manifest:\n>> The backend workers maintain their own manifest file which contains a\n>> list of files\n>> that are being transferred by the work. Once all backup files are\n>> transferred, the\n>> workers will create a temp file as\n>> ('pg_tempdir/temp_file_prefix_backupid.workerid')\n>> to write the content of the manifest file from BufFile. The workers won’t\n>> add the\n>> header, nor the WAL information in their manifest. These two will be\n>> added by the\n>> main process while merging all worker manifest files.\n>>\n>> The main process will read these individual files and concatenate them\n>> into a single file\n>> which is then sent back to the client.\n>>\n>> The manifest file is created when the following command is received:\n>>\n>>> BUILD_MANIFEST 'backupid'\n>>\n>>\n>> This is a new replication command. It is sent when pg_basebackup has\n>> copied all the\n>> $PGDATA files including WAL files.\n>>\n>>\n>>\n>> --\n>> Asif Rehman\n>> Highgo Software (Canada/China/Pakistan)\n>> URL : www.highgo.ca\n>>\n>>\n>\n> --\n> Regards\n> ====================================\n> Kashif Zeeshan\n> Lead Quality Assurance Engineer / Manager\n>\n> EnterpriseDB Corporation\n> The Enterprise Postgres Company\n>\n>\n\n-- \n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Tue, 14 Apr 2020 19:36:58 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Apr 14, 2020 at 10:37 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> I forgot to make a check for no-manifest. Fixed. Attached is the updated patch.\n\n+typedef struct\n+{\n...\n+} BackupFile;\n+\n+typedef struct\n+{\n...\n+} BackupState;\n\nThese structures need comments.\n\n+list_wal_files_opt_list:\n+ SCONST SCONST\n {\n- $$ = makeDefElem(\"manifest_checksums\",\n-\n(Node *)makeString($2), -1);\n+ $$ = list_make2(\n+ makeDefElem(\"start_wal_location\",\n+ (Node *)makeString($2), -1),\n+ makeDefElem(\"end_wal_location\",\n+ (Node *)makeString($2), -1));\n+\n }\n\nThis seems like an unnecessarily complicated parse representation. The\nDefElems seem to be completely unnecessary here.\n\n@@ -998,7 +1110,37 @@ SendBaseBackup(BaseBackupCmd *cmd)\n set_ps_display(activitymsg);\n }\n\n- perform_base_backup(&opt);\n+ switch (cmd->cmdtag)\n\nSo the design here is that SendBaseBackup() is now going to do a bunch\nof things that are NOT sending a base backup? With no updates to the\ncomments of that function and no change to the process title it sets?\n\n- return (manifest->buffile != NULL);\n+ return (manifest && manifest->buffile != NULL);\n\nHeck no. It appears that you didn't even bother reading the function\nheader comment.\n\n+ * Send a single resultset containing XLogRecPtr record (in text format)\n+ * TimelineID and backup label.\n */\n static void\n-SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli)\n+SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli,\n+ StringInfo label, char *backupid)\n\nThis just casually breaks wire protocol compatibility, which seems\ncompletely unacceptable.\n\n+ if (strlen(opt->tablespace) > 0)\n+ sendTablespace(opt->tablespace, NULL, true, NULL, &files);\n+ else\n+ sendDir(\".\", 1, true, NIL, true, NULL, NULL, &files);\n+\n+ SendFilesHeader(files);\n\nSo I guess the idea here is that we buffer the entire list of files in\nmemory, regardless of size, and then we send it out afterwards. That\ndoesn't seem like a good idea. The list of files might be very large.\nWe probably need some code refactoring here rather than just piling\nmore and more different responsibilities onto sendTablespace() and\nsendDir().\n\n+ if (state->parallel_mode)\n+ SpinLockAcquire(&state->lock);\n+\n+ state->throttling_counter += increment;\n+\n+ if (state->parallel_mode)\n+ SpinLockRelease(&state->lock);\n\nI don't like this much. It seems to me that we would do better to use\natomics here all the time, instead of conditional spinlocks.\n\n+static void\n+send_file(basebackup_options *opt, char *file, bool missing_ok)\n...\n+ if (file == NULL)\n+ return;\n\nThat seems totally inappropriate.\n\n+ sendFile(file, file + basepathlen, &statbuf,\ntrue, InvalidOid, NULL, NULL);\n\nMaybe I'm misunderstanding, but this looks like it's going to write a\ntar header, even though we're not writing a tarfile.\n\n+ else\n+ ereport(WARNING,\n+ (errmsg(\"skipping special file\nor directory \\\"%s\\\"\", file)));\n\nSo, if the user asks for a directory or symlink, what's going to\nhappen is that they're going to receive an empty file, and get a\nwarning. That sounds like terrible behavior.\n\n+ /*\n+ * Check for checksum failures. If there are failures across multiple\n+ * processes it may not report total checksum count, but it will error\n+ * out,terminating the backup.\n+ */\n\nIn other words, the patch breaks the feature. Not that the feature in\nquestion works particularly well as things stand, but this makes it\nworse.\n\nI think this patch (0003) is in really bad shape. I'm having second\nthoughts about the design, but it's kind of hard to even have a\ndiscussion about the design when the patch is riddled with minor\nproblems like inadequate comments, failure to update existing\ncomments, and breaking a bunch of things. I understand that sometimes\nthings get missed, but this is version 14 of a patch that's been\nkicking around since last August.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 14 Apr 2020 16:49:04 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, 15 Apr 2020 at 1:49 AM, Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Tue, Apr 14, 2020 at 10:37 AM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n> > I forgot to make a check for no-manifest. Fixed. Attached is the updated\n> patch.\n>\n> +typedef struct\n> +{\n> ...\n> +} BackupFile;\n> +\n> +typedef struct\n> +{\n> ...\n> +} BackupState;\n>\n> These structures need comments.\n>\n> +list_wal_files_opt_list:\n> + SCONST SCONST\n> {\n> - $$ = makeDefElem(\"manifest_checksums\",\n> -\n> (Node *)makeString($2), -1);\n> + $$ = list_make2(\n> + makeDefElem(\"start_wal_location\",\n> + (Node *)makeString($2),\n> -1),\n> + makeDefElem(\"end_wal_location\",\n> + (Node *)makeString($2),\n> -1));\n> +\n> }\n>\n> This seems like an unnecessarily complicated parse representation. The\n> DefElems seem to be completely unnecessary here.\n>\n> @@ -998,7 +1110,37 @@ SendBaseBackup(BaseBackupCmd *cmd)\n> set_ps_display(activitymsg);\n> }\n>\n> - perform_base_backup(&opt);\n> + switch (cmd->cmdtag)\n>\n> So the design here is that SendBaseBackup() is now going to do a bunch\n> of things that are NOT sending a base backup? With no updates to the\n> comments of that function and no change to the process title it sets?\n>\n> - return (manifest->buffile != NULL);\n> + return (manifest && manifest->buffile != NULL);\n>\n> Heck no. It appears that you didn't even bother reading the function\n> header comment.\n>\n> + * Send a single resultset containing XLogRecPtr record (in text format)\n> + * TimelineID and backup label.\n> */\n> static void\n> -SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli)\n> +SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli,\n> + StringInfo label, char *backupid)\n>\n> This just casually breaks wire protocol compatibility, which seems\n> completely unacceptable.\n>\n> + if (strlen(opt->tablespace) > 0)\n> + sendTablespace(opt->tablespace, NULL, true, NULL, &files);\n> + else\n> + sendDir(\".\", 1, true, NIL, true, NULL, NULL, &files);\n> +\n> + SendFilesHeader(files);\n>\n> So I guess the idea here is that we buffer the entire list of files in\n> memory, regardless of size, and then we send it out afterwards. That\n> doesn't seem like a good idea. The list of files might be very large.\n> We probably need some code refactoring here rather than just piling\n> more and more different responsibilities onto sendTablespace() and\n> sendDir().\n>\n> + if (state->parallel_mode)\n> + SpinLockAcquire(&state->lock);\n> +\n> + state->throttling_counter += increment;\n> +\n> + if (state->parallel_mode)\n> + SpinLockRelease(&state->lock);\n>\n> I don't like this much. It seems to me that we would do better to use\n> atomics here all the time, instead of conditional spinlocks.\n>\n> +static void\n> +send_file(basebackup_options *opt, char *file, bool missing_ok)\n> ...\n> + if (file == NULL)\n> + return;\n>\n> That seems totally inappropriate.\n>\n> + sendFile(file, file + basepathlen, &statbuf,\n> true, InvalidOid, NULL, NULL);\n>\n> Maybe I'm misunderstanding, but this looks like it's going to write a\n> tar header, even though we're not writing a tarfile.\n>\n> + else\n> + ereport(WARNING,\n> + (errmsg(\"skipping special file\n> or directory \\\"%s\\\"\", file)));\n>\n> So, if the user asks for a directory or symlink, what's going to\n> happen is that they're going to receive an empty file, and get a\n> warning. That sounds like terrible behavior.\n>\n> + /*\n> + * Check for checksum failures. If there are failures across\n> multiple\n> + * processes it may not report total checksum count, but it will\n> error\n> + * out,terminating the backup.\n> + */\n>\n> In other words, the patch breaks the feature. Not that the feature in\n> question works particularly well as things stand, but this makes it\n> worse.\n>\n> I think this patch (0003) is in really bad shape. I'm having second\n> thoughts about the design, but it's kind of hard to even have a\n> discussion about the design when the patch is riddled with minor\n> problems like inadequate comments, failure to update existing\n> comments, and breaking a bunch of things. I understand that sometimes\n> things get missed, but this is version 14 of a patch that's been\n> kicking around since last August.\n\n\nFair enough. Some of this is also due to backup related features i.e backup\nmanifest, progress reporting that got committed to master towards the tail\nend of PG-13. Rushing to get parallel backup feature compatible with these\nfeatures also caused some of the oversights.\n\n\n>\n> --\n> Robert Haas\n> EnterpriseDB: http://www.enterprisedb.com\n> The Enterprise PostgreSQL Company\n>\n>\n> --\nHighgo Software (Canada/China/Pakistan)\nURL : http://www.highgo.ca\nADDR: 10318 WHALLEY BLVD, Surrey, BC\nEMAIL: mailto: ahsan.hadi@highgo.ca\n\nOn Wed, 15 Apr 2020 at 1:49 AM, Robert Haas <robertmhaas@gmail.com> wrote:On Tue, Apr 14, 2020 at 10:37 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> I forgot to make a check for no-manifest. Fixed. Attached is the updated patch.\n\n+typedef struct\n+{\n...\n+} BackupFile;\n+\n+typedef struct\n+{\n...\n+} BackupState;\n\nThese structures need comments.\n\n+list_wal_files_opt_list:\n+                       SCONST SCONST\n                                {\n-                                 $$ = makeDefElem(\"manifest_checksums\",\n-\n(Node *)makeString($2), -1);\n+                                       $$ = list_make2(\n+                                       makeDefElem(\"start_wal_location\",\n+                                               (Node *)makeString($2), -1),\n+                                       makeDefElem(\"end_wal_location\",\n+                                               (Node *)makeString($2), -1));\n+\n                                }\n\nThis seems like an unnecessarily complicated parse representation. The\nDefElems seem to be completely unnecessary here.\n\n@@ -998,7 +1110,37 @@ SendBaseBackup(BaseBackupCmd *cmd)\n                set_ps_display(activitymsg);\n        }\n\n-       perform_base_backup(&opt);\n+       switch (cmd->cmdtag)\n\nSo the design here is that SendBaseBackup() is now going to do a bunch\nof things that are NOT sending a base backup? With no updates to the\ncomments of that function and no change to the process title it sets?\n\n-       return (manifest->buffile != NULL);\n+       return (manifest && manifest->buffile != NULL);\n\nHeck no. It appears that you didn't even bother reading the function\nheader comment.\n\n+ * Send a single resultset containing XLogRecPtr record (in text format)\n+ * TimelineID and backup label.\n  */\n static void\n-SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli)\n+SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli,\n+                                        StringInfo label, char *backupid)\n\nThis just casually breaks wire protocol compatibility, which seems\ncompletely unacceptable.\n\n+       if (strlen(opt->tablespace) > 0)\n+               sendTablespace(opt->tablespace, NULL, true, NULL, &files);\n+       else\n+               sendDir(\".\", 1, true, NIL, true, NULL, NULL, &files);\n+\n+       SendFilesHeader(files);\n\nSo I guess the idea here is that we buffer the entire list of files in\nmemory, regardless of size, and then we send it out afterwards. That\ndoesn't seem like a good idea. The list of files might be very large.\nWe probably need some code refactoring here rather than just piling\nmore and more different responsibilities onto sendTablespace() and\nsendDir().\n\n+       if (state->parallel_mode)\n+               SpinLockAcquire(&state->lock);\n+\n+       state->throttling_counter += increment;\n+\n+       if (state->parallel_mode)\n+               SpinLockRelease(&state->lock);\n\nI don't like this much. It seems to me that we would do better to use\natomics here all the time, instead of conditional spinlocks.\n\n+static void\n+send_file(basebackup_options *opt, char *file, bool missing_ok)\n...\n+       if (file == NULL)\n+               return;\n\nThat seems totally inappropriate.\n\n+                       sendFile(file, file + basepathlen, &statbuf,\ntrue, InvalidOid, NULL, NULL);\n\nMaybe I'm misunderstanding, but this looks like it's going to write a\ntar header, even though we're not writing a tarfile.\n\n+               else\n+                       ereport(WARNING,\n+                                       (errmsg(\"skipping special file\nor directory \\\"%s\\\"\", file)));\n\nSo, if the user asks for a directory or symlink, what's going to\nhappen is that they're going to receive an empty file, and get a\nwarning. That sounds like terrible behavior.\n\n+       /*\n+        * Check for checksum failures. If there are failures across multiple\n+        * processes it may not report total checksum count, but it will error\n+        * out,terminating the backup.\n+        */\n\nIn other words, the patch breaks the feature. Not that the feature in\nquestion works particularly well as things stand, but this makes it\nworse.\n\nI think this patch (0003) is in really bad shape. I'm having second\nthoughts about the design, but it's kind of hard to even have a\ndiscussion about the design when the patch is riddled with minor\nproblems like inadequate comments, failure to update existing\ncomments, and breaking a bunch of things. I understand that sometimes\nthings get missed, but this is version 14 of a patch that's been\nkicking around since last August.Fair enough. Some of this is also due to backup related features i.e backup manifest, progress reporting that got committed to master towards the tail end of PG-13. Rushing to get parallel backup feature compatible with these features also caused some of the oversights.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n-- Highgo Software (Canada/China/Pakistan)URL : http://www.highgo.caADDR: 10318 WHALLEY BLVD, Surrey, BCEMAIL: mailto: ahsan.hadi@highgo.ca", "msg_date": "Wed, 15 Apr 2020 13:49:39 +0500", "msg_from": "Ahsan Hadi <ahsan.hadi@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif,\n\nIn below scenarios backup verification failed for tablespace, when backup\ntaken with parallel option.\nwithout parallel for the same scenario pg_verifybackup is passed without\nany error.\n\n[edb@localhost bin]$ mkdir /tmp/test_bkp/tblsp1\n[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace tblsp1\nlocation '/tmp/test_bkp/tblsp1';\"\nCREATE TABLESPACE\n[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a text)\ntablespace tblsp1;\"\nCREATE TABLE\n[edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test values\n('parallel_backup with -T tablespace option');\"\nINSERT 0 1\n[edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/test_bkp/bkp -T\n/tmp/test_bkp/tblsp1=/tmp/test_bkp/tblsp2 -j 4\n[edb@localhost bin]$ ./pg_verifybackup /tmp/test_bkp/bkp\npg_verifybackup: error: \"pg_tblspc/16384/PG_13_202004074/13530/16390\" is\npresent on disk but not in the manifest\npg_verifybackup: error: \"pg_tblspc/16384/PG_13_202004074/13530/16388\" is\npresent on disk but not in the manifest\npg_verifybackup: error: \"pg_tblspc/16384/PG_13_202004074/13530/16385\" is\npresent on disk but not in the manifest\npg_verifybackup: error: \"/PG_13_202004074/13530/16388\" is present in the\nmanifest but not on disk\npg_verifybackup: error: \"/PG_13_202004074/13530/16390\" is present in the\nmanifest but not on disk\npg_verifybackup: error: \"/PG_13_202004074/13530/16385\" is present in the\nmanifest but not on disk\n\n--without parallel backup\n[edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/test_bkp/bkp1 -T\n/tmp/test_bkp/tblsp1=/tmp/test_bkp/tblsp3 -j 1\n[edb@localhost bin]$ ./pg_verifybackup /tmp/test_bkp/bkp1\nbackup successfully verified\n\n\nThanks & Regards,\nRajkumar Raghuwanshi\n\n\nOn Wed, Apr 15, 2020 at 2:19 PM Ahsan Hadi <ahsan.hadi@gmail.com> wrote:\n\n>\n>\n> On Wed, 15 Apr 2020 at 1:49 AM, Robert Haas <robertmhaas@gmail.com> wrote:\n>\n>> On Tue, Apr 14, 2020 at 10:37 AM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>> > I forgot to make a check for no-manifest. Fixed. Attached is the\n>> updated patch.\n>>\n>> +typedef struct\n>> +{\n>> ...\n>> +} BackupFile;\n>> +\n>> +typedef struct\n>> +{\n>> ...\n>> +} BackupState;\n>>\n>> These structures need comments.\n>>\n>> +list_wal_files_opt_list:\n>> + SCONST SCONST\n>> {\n>> - $$ = makeDefElem(\"manifest_checksums\",\n>> -\n>> (Node *)makeString($2), -1);\n>> + $$ = list_make2(\n>> + makeDefElem(\"start_wal_location\",\n>> + (Node *)makeString($2),\n>> -1),\n>> + makeDefElem(\"end_wal_location\",\n>> + (Node *)makeString($2),\n>> -1));\n>> +\n>> }\n>>\n>> This seems like an unnecessarily complicated parse representation. The\n>> DefElems seem to be completely unnecessary here.\n>>\n>> @@ -998,7 +1110,37 @@ SendBaseBackup(BaseBackupCmd *cmd)\n>> set_ps_display(activitymsg);\n>> }\n>>\n>> - perform_base_backup(&opt);\n>> + switch (cmd->cmdtag)\n>>\n>> So the design here is that SendBaseBackup() is now going to do a bunch\n>> of things that are NOT sending a base backup? With no updates to the\n>> comments of that function and no change to the process title it sets?\n>>\n>> - return (manifest->buffile != NULL);\n>> + return (manifest && manifest->buffile != NULL);\n>>\n>> Heck no. It appears that you didn't even bother reading the function\n>> header comment.\n>>\n>> + * Send a single resultset containing XLogRecPtr record (in text format)\n>> + * TimelineID and backup label.\n>> */\n>> static void\n>> -SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli)\n>> +SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli,\n>> + StringInfo label, char *backupid)\n>>\n>> This just casually breaks wire protocol compatibility, which seems\n>> completely unacceptable.\n>>\n>> + if (strlen(opt->tablespace) > 0)\n>> + sendTablespace(opt->tablespace, NULL, true, NULL, &files);\n>> + else\n>> + sendDir(\".\", 1, true, NIL, true, NULL, NULL, &files);\n>> +\n>> + SendFilesHeader(files);\n>>\n>> So I guess the idea here is that we buffer the entire list of files in\n>> memory, regardless of size, and then we send it out afterwards. That\n>> doesn't seem like a good idea. The list of files might be very large.\n>> We probably need some code refactoring here rather than just piling\n>> more and more different responsibilities onto sendTablespace() and\n>> sendDir().\n>>\n>> + if (state->parallel_mode)\n>> + SpinLockAcquire(&state->lock);\n>> +\n>> + state->throttling_counter += increment;\n>> +\n>> + if (state->parallel_mode)\n>> + SpinLockRelease(&state->lock);\n>>\n>> I don't like this much. It seems to me that we would do better to use\n>> atomics here all the time, instead of conditional spinlocks.\n>>\n>> +static void\n>> +send_file(basebackup_options *opt, char *file, bool missing_ok)\n>> ...\n>> + if (file == NULL)\n>> + return;\n>>\n>> That seems totally inappropriate.\n>>\n>> + sendFile(file, file + basepathlen, &statbuf,\n>> true, InvalidOid, NULL, NULL);\n>>\n>> Maybe I'm misunderstanding, but this looks like it's going to write a\n>> tar header, even though we're not writing a tarfile.\n>>\n>> + else\n>> + ereport(WARNING,\n>> + (errmsg(\"skipping special file\n>> or directory \\\"%s\\\"\", file)));\n>>\n>> So, if the user asks for a directory or symlink, what's going to\n>> happen is that they're going to receive an empty file, and get a\n>> warning. That sounds like terrible behavior.\n>>\n>> + /*\n>> + * Check for checksum failures. If there are failures across\n>> multiple\n>> + * processes it may not report total checksum count, but it will\n>> error\n>> + * out,terminating the backup.\n>> + */\n>>\n>> In other words, the patch breaks the feature. Not that the feature in\n>> question works particularly well as things stand, but this makes it\n>> worse.\n>>\n>> I think this patch (0003) is in really bad shape. I'm having second\n>> thoughts about the design, but it's kind of hard to even have a\n>> discussion about the design when the patch is riddled with minor\n>> problems like inadequate comments, failure to update existing\n>> comments, and breaking a bunch of things. I understand that sometimes\n>> things get missed, but this is version 14 of a patch that's been\n>> kicking around since last August.\n>\n>\n> Fair enough. Some of this is also due to backup related features i.e\n> backup manifest, progress reporting that got committed to master towards\n> the tail end of PG-13. Rushing to get parallel backup feature compatible\n> with these features also caused some of the oversights.\n>\n>\n>>\n>> --\n>> Robert Haas\n>> EnterpriseDB: http://www.enterprisedb.com\n>> The Enterprise PostgreSQL Company\n>>\n>>\n>> --\n> Highgo Software (Canada/China/Pakistan)\n> URL : http://www.highgo.ca\n> ADDR: 10318 WHALLEY BLVD, Surrey, BC\n> EMAIL: mailto: ahsan.hadi@highgo.ca\n>\n\nHi Asif,In below scenarios backup verification failed for tablespace, when backup taken with parallel option.without parallel for the same scenario pg_verifybackup is passed without any error.[edb@localhost bin]$ mkdir /tmp/test_bkp/tblsp1[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create tablespace tblsp1 location '/tmp/test_bkp/tblsp1';\"CREATE TABLESPACE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"create table test (a text) tablespace tblsp1;\"CREATE TABLE[edb@localhost bin]$ ./psql postgres -p 5432 -c \"insert into test values ('parallel_backup with -T tablespace option');\"INSERT 0 1[edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/test_bkp/bkp -T /tmp/test_bkp/tblsp1=/tmp/test_bkp/tblsp2 -j 4[edb@localhost bin]$ ./pg_verifybackup /tmp/test_bkp/bkppg_verifybackup: error: \"pg_tblspc/16384/PG_13_202004074/13530/16390\" is present on disk but not in the manifestpg_verifybackup: error: \"pg_tblspc/16384/PG_13_202004074/13530/16388\" is present on disk but not in the manifestpg_verifybackup: error: \"pg_tblspc/16384/PG_13_202004074/13530/16385\" is present on disk but not in the manifestpg_verifybackup: error: \"/PG_13_202004074/13530/16388\" is present in the manifest but not on diskpg_verifybackup: error: \"/PG_13_202004074/13530/16390\" is present in the manifest but not on diskpg_verifybackup: error: \"/PG_13_202004074/13530/16385\" is present in the manifest but not on disk--without parallel backup[edb@localhost bin]$ ./pg_basebackup -p 5432 -D /tmp/test_bkp/bkp1 -T /tmp/test_bkp/tblsp1=/tmp/test_bkp/tblsp3 -j 1[edb@localhost bin]$ ./pg_verifybackup /tmp/test_bkp/bkp1backup successfully verifiedThanks & Regards,Rajkumar RaghuwanshiOn Wed, Apr 15, 2020 at 2:19 PM Ahsan Hadi <ahsan.hadi@gmail.com> wrote:On Wed, 15 Apr 2020 at 1:49 AM, Robert Haas <robertmhaas@gmail.com> wrote:On Tue, Apr 14, 2020 at 10:37 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> I forgot to make a check for no-manifest. Fixed. Attached is the updated patch.\n\n+typedef struct\n+{\n...\n+} BackupFile;\n+\n+typedef struct\n+{\n...\n+} BackupState;\n\nThese structures need comments.\n\n+list_wal_files_opt_list:\n+                       SCONST SCONST\n                                {\n-                                 $$ = makeDefElem(\"manifest_checksums\",\n-\n(Node *)makeString($2), -1);\n+                                       $$ = list_make2(\n+                                       makeDefElem(\"start_wal_location\",\n+                                               (Node *)makeString($2), -1),\n+                                       makeDefElem(\"end_wal_location\",\n+                                               (Node *)makeString($2), -1));\n+\n                                }\n\nThis seems like an unnecessarily complicated parse representation. The\nDefElems seem to be completely unnecessary here.\n\n@@ -998,7 +1110,37 @@ SendBaseBackup(BaseBackupCmd *cmd)\n                set_ps_display(activitymsg);\n        }\n\n-       perform_base_backup(&opt);\n+       switch (cmd->cmdtag)\n\nSo the design here is that SendBaseBackup() is now going to do a bunch\nof things that are NOT sending a base backup? With no updates to the\ncomments of that function and no change to the process title it sets?\n\n-       return (manifest->buffile != NULL);\n+       return (manifest && manifest->buffile != NULL);\n\nHeck no. It appears that you didn't even bother reading the function\nheader comment.\n\n+ * Send a single resultset containing XLogRecPtr record (in text format)\n+ * TimelineID and backup label.\n  */\n static void\n-SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli)\n+SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli,\n+                                        StringInfo label, char *backupid)\n\nThis just casually breaks wire protocol compatibility, which seems\ncompletely unacceptable.\n\n+       if (strlen(opt->tablespace) > 0)\n+               sendTablespace(opt->tablespace, NULL, true, NULL, &files);\n+       else\n+               sendDir(\".\", 1, true, NIL, true, NULL, NULL, &files);\n+\n+       SendFilesHeader(files);\n\nSo I guess the idea here is that we buffer the entire list of files in\nmemory, regardless of size, and then we send it out afterwards. That\ndoesn't seem like a good idea. The list of files might be very large.\nWe probably need some code refactoring here rather than just piling\nmore and more different responsibilities onto sendTablespace() and\nsendDir().\n\n+       if (state->parallel_mode)\n+               SpinLockAcquire(&state->lock);\n+\n+       state->throttling_counter += increment;\n+\n+       if (state->parallel_mode)\n+               SpinLockRelease(&state->lock);\n\nI don't like this much. It seems to me that we would do better to use\natomics here all the time, instead of conditional spinlocks.\n\n+static void\n+send_file(basebackup_options *opt, char *file, bool missing_ok)\n...\n+       if (file == NULL)\n+               return;\n\nThat seems totally inappropriate.\n\n+                       sendFile(file, file + basepathlen, &statbuf,\ntrue, InvalidOid, NULL, NULL);\n\nMaybe I'm misunderstanding, but this looks like it's going to write a\ntar header, even though we're not writing a tarfile.\n\n+               else\n+                       ereport(WARNING,\n+                                       (errmsg(\"skipping special file\nor directory \\\"%s\\\"\", file)));\n\nSo, if the user asks for a directory or symlink, what's going to\nhappen is that they're going to receive an empty file, and get a\nwarning. That sounds like terrible behavior.\n\n+       /*\n+        * Check for checksum failures. If there are failures across multiple\n+        * processes it may not report total checksum count, but it will error\n+        * out,terminating the backup.\n+        */\n\nIn other words, the patch breaks the feature. Not that the feature in\nquestion works particularly well as things stand, but this makes it\nworse.\n\nI think this patch (0003) is in really bad shape. I'm having second\nthoughts about the design, but it's kind of hard to even have a\ndiscussion about the design when the patch is riddled with minor\nproblems like inadequate comments, failure to update existing\ncomments, and breaking a bunch of things. I understand that sometimes\nthings get missed, but this is version 14 of a patch that's been\nkicking around since last August.Fair enough. Some of this is also due to backup related features i.e backup manifest, progress reporting that got committed to master towards the tail end of PG-13. Rushing to get parallel backup feature compatible with these features also caused some of the oversights.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n-- Highgo Software (Canada/China/Pakistan)URL : http://www.highgo.caADDR: 10318 WHALLEY BLVD, Surrey, BCEMAIL: mailto: ahsan.hadi@highgo.ca", "msg_date": "Wed, 15 Apr 2020 14:58:37 +0530", "msg_from": "Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, Apr 15, 2020 at 4:49 AM Ahsan Hadi <ahsan.hadi@gmail.com> wrote:\n> Fair enough. Some of this is also due to backup related features i.e backup manifest, progress reporting that got committed to master towards the tail end of PG-13. Rushing to get parallel backup feature compatible with these features also caused some of the oversights.\n\nSure, but there's also no point in rushing out a feature that's in a\nstate where it's got no chance of being acceptable, and quite a number\nof these problems are not new, either.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Wed, 15 Apr 2020 09:31:22 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Apr 14, 2020 at 7:37 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Tue, Apr 14, 2020 at 6:32 PM Kashif Zeeshan <\n> kashif.zeeshan@enterprisedb.com> wrote:\n>\n>> Hi Asif\n>>\n>> Getting the following error on Parallel backup when --no-manifest option\n>> is used.\n>>\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ ./pg_basebackup -v -j 5 -D\n>> /home/edb/Desktop/backup/ --no-manifest\n>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>> pg_basebackup: checkpoint completed\n>> pg_basebackup: write-ahead log start point: 0/2000028 on timeline 1\n>> pg_basebackup: starting background WAL receiver\n>> pg_basebackup: created temporary replication slot \"pg_basebackup_10223\"\n>> pg_basebackup: backup worker (0) created\n>> pg_basebackup: backup worker (1) created\n>> pg_basebackup: backup worker (2) created\n>> pg_basebackup: backup worker (3) created\n>> pg_basebackup: backup worker (4) created\n>> pg_basebackup: write-ahead log end point: 0/2000100\n>> pg_basebackup: error: could not get data for 'BUILD_MANIFEST': ERROR:\n>> could not open file\n>> \"base/pgsql_tmp/pgsql_tmp_b4ef5ac0fd150b2a28caf626bbb1bef2.1\": No such file\n>> or directory\n>> pg_basebackup: removing contents of data directory\n>> \"/home/edb/Desktop/backup/\"\n>> [edb@localhost bin]$\n>>\n>\n> I forgot to make a check for no-manifest. Fixed. Attached is the updated\n> patch.\n>\nHi Asif\n\nVerified the fix, thanks.\n\n[edb@localhost bin]$\n[edb@localhost bin]$\n[edb@localhost bin]$ ./pg_basebackup -v -j 5 -D\n/home/edb/Desktop/backup --no-manifest\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 0/4000028 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: created temporary replication slot \"pg_basebackup_27407\"\npg_basebackup: backup worker (0) created\npg_basebackup: backup worker (1) created\npg_basebackup: backup worker (2) created\npg_basebackup: backup worker (3) created\npg_basebackup: backup worker (4) created\npg_basebackup: write-ahead log end point: 0/4000100\npg_basebackup: waiting for background process to finish streaming ...\npg_basebackup: syncing data to disk ...\npg_basebackup: base backup completed\n[edb@localhost bin]$\n[edb@localhost bin]$ ls /home/edb/Desktop/backup\nbackup_label pg_commit_ts pg_ident.conf pg_notify pg_snapshots\npg_subtrans PG_VERSION postgresql.auto.conf\nbase pg_dynshmem pg_logical pg_replslot pg_stat\npg_tblspc pg_wal postgresql.conf\nglobal pg_hba.conf pg_multixact pg_serial pg_stat_tmp\npg_twophase pg_xact\n[edb@localhost bin]$\n[edb@localhost bin]$\n[edb@localhost bin]$\n\nRegards\nKashif Zeeshan\n\n>\n>\n>> Thanks\n>>\n>> On Tue, Apr 14, 2020 at 5:33 PM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>>\n>>>\n>>>\n>>> On Wed, Apr 8, 2020 at 6:53 PM Kashif Zeeshan <\n>>> kashif.zeeshan@enterprisedb.com> wrote:\n>>>\n>>>>\n>>>>\n>>>> On Tue, Apr 7, 2020 at 9:44 PM Asif Rehman <asifr.rehman@gmail.com>\n>>>> wrote:\n>>>>\n>>>>> Hi,\n>>>>>\n>>>>> Thanks, Kashif and Rajkumar. I have fixed the reported issues.\n>>>>>\n>>>>> I have added the shared state as previously described. The new grammar\n>>>>> changes\n>>>>> are as follows:\n>>>>>\n>>>>> START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]\n>>>>> - This will generate a unique backupid using pg_strong_random(16)\n>>>>> and hex-encoded\n>>>>> it. which is then returned as the result set.\n>>>>> - It will also create a shared state and add it to the hashtable.\n>>>>> The hash table size is set\n>>>>> to BACKUP_HASH_SIZE=10, but since hashtable can expand\n>>>>> dynamically, I think it's\n>>>>> sufficient initial size. max_wal_senders is not used, because it\n>>>>> can be set to quite a\n>>>>> large values.\n>>>>>\n>>>>> JOIN_BACKUP 'backup_id'\n>>>>> - finds 'backup_id' in hashtable and attaches it to server process.\n>>>>>\n>>>>>\n>>>>> SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]\n>>>>> - renamed SEND_FILES to SEND_FILE\n>>>>> - removed START_WAL_LOCATION from this because 'startptr' is now\n>>>>> accessible through\n>>>>> shared state.\n>>>>>\n>>>>> There is no change in other commands:\n>>>>> STOP_BACKUP [NOWAIT]\n>>>>> LIST_TABLESPACES [PROGRESS]\n>>>>> LIST_FILES [TABLESPACE]\n>>>>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>>>>\n>>>>> The current patches (v11) have been rebased to the latest master. The\n>>>>> backup manifest is enabled\n>>>>> by default, so I have disabled it for parallel backup mode and have\n>>>>> generated a warning so that\n>>>>> user is aware of it and not expect it in the backup.\n>>>>>\n>>>>> Hi Asif\n>>>>\n>>>> I have verified the bug fixes, one bug is fixed and working now as\n>>>> expected\n>>>>\n>>>> For the verification of the other bug fixes faced following issues,\n>>>> please have a look.\n>>>>\n>>>>\n>>>> 1) Following bug fixes mentioned below are generating segmentation\n>>>> fault.\n>>>>\n>>>> Please note for reference I have added a description only as steps were\n>>>> given in previous emails of each bug I tried to verify the fix. Backtrace\n>>>> is also added with each case which points to one bug for both the cases.\n>>>>\n>>>> a) The backup failed with errors \"error: could not connect to server:\n>>>> could not look up local user ID 1000: Too many open files\" when the\n>>>> max_wal_senders was set to 2000.\n>>>>\n>>>>\n>>>> [edb@localhost bin]$ ./pg_basebackup -v -j 1990 -D\n>>>> /home/edb/Desktop/backup/\n>>>> pg_basebackup: warning: backup manifest is disabled in parallel backup\n>>>> mode\n>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>> complete\n>>>> pg_basebackup: checkpoint completed\n>>>> pg_basebackup: write-ahead log start point: 0/2000028 on timeline 1\n>>>> pg_basebackup: starting background WAL receiver\n>>>> pg_basebackup: created temporary replication slot \"pg_basebackup_9925\"\n>>>> pg_basebackup: backup worker (0) created\n>>>> pg_basebackup: backup worker (1) created\n>>>> pg_basebackup: backup worker (2) created\n>>>> pg_basebackup: backup worker (3) created\n>>>> ….\n>>>> ….\n>>>> pg_basebackup: backup worker (1014) created\n>>>> pg_basebackup: backup worker (1015) created\n>>>> pg_basebackup: backup worker (1016) created\n>>>> pg_basebackup: backup worker (1017) created\n>>>> pg_basebackup: error: could not connect to server: could not look up\n>>>> local user ID 1000: Too many open files\n>>>> Segmentation fault\n>>>> [edb@localhost bin]$\n>>>>\n>>>>\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$ gdb pg_basebackup\n>>>> /tmp/cores/core.pg_basebackup.13219.localhost.localdomain.1586349551\n>>>> GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7\n>>>> Copyright (C) 2013 Free Software Foundation, Inc.\n>>>> License GPLv3+: GNU GPL version 3 or later <\n>>>> http://gnu.org/licenses/gpl.html>\n>>>> This is free software: you are free to change and redistribute it.\n>>>> There is NO WARRANTY, to the extent permitted by law. Type \"show\n>>>> copying\"\n>>>> and \"show warranty\" for details.\n>>>> This GDB was configured as \"x86_64-redhat-linux-gnu\".\n>>>> For bug reporting instructions, please see:\n>>>> <http://www.gnu.org/software/gdb/bugs/>...\n>>>> Reading symbols from\n>>>> /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.\n>>>> [New LWP 13219]\n>>>> [New LWP 13222]\n>>>> [Thread debugging using libthread_db enabled]\n>>>> Using host libthread_db library \"/lib64/libthread_db.so.1\".\n>>>> Core was generated by `./pg_basebackup -v -j 1990 -D\n>>>> /home/edb/Desktop/backup/'.\n>>>> Program terminated with signal 11, Segmentation fault.\n>>>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>>>> 47 if (INVALID_NOT_TERMINATED_TD_P (pd))\n>>>> (gdb) bt\n>>>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>>>> #1 0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978\n>>>> #2 0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332\n>>>> #3 0x00007f2226f76a49 in __run_exit_handlers (status=1,\n>>>> listp=0x7f22272f86c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true)\n>>>> at exit.c:77\n>>>> #4 0x00007f2226f76a95 in __GI_exit (status=<optimized out>) at\n>>>> exit.c:99\n>>>> #5 0x0000000000408c54 in create_parallel_workers (backupinfo=0x952ca0)\n>>>> at pg_basebackup.c:2811\n>>>> #6 0x000000000040798f in BaseBackup () at pg_basebackup.c:2211\n>>>> #7 0x0000000000408b4d in main (argc=6, argv=0x7ffe3dabc718) at\n>>>> pg_basebackup.c:2765\n>>>> (gdb)\n>>>>\n>>>>\n>>>>\n>>>>\n>>>> b) When executing two backups at the same time, getting FATAL error due\n>>>> to max_wal_senders and instead of exit Backup got completed.\n>>>>\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$ ./pg_basebackup -v -j 8 -D\n>>>> /home/edb/Desktop/backup1/\n>>>> pg_basebackup: warning: backup manifest is disabled in parallel backup\n>>>> mode\n>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>> complete\n>>>> pg_basebackup: checkpoint completed\n>>>> pg_basebackup: write-ahead log start point: 1/DA000028 on timeline 1\n>>>> pg_basebackup: starting background WAL receiver\n>>>> pg_basebackup: created temporary replication slot \"pg_basebackup_17066\"\n>>>> pg_basebackup: backup worker (0) created\n>>>> pg_basebackup: backup worker (1) created\n>>>> pg_basebackup: backup worker (2) created\n>>>> pg_basebackup: backup worker (3) created\n>>>> pg_basebackup: backup worker (4) created\n>>>> pg_basebackup: backup worker (5) created\n>>>> pg_basebackup: backup worker (6) created\n>>>> pg_basebackup: error: could not connect to server: FATAL: number of\n>>>> requested standby connections exceeds max_wal_senders (currently 10)\n>>>> Segmentation fault (core dumped)\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$ gdb pg_basebackup\n>>>> /tmp/cores/core.pg_basebackup.17041.localhost.localdomain.1586353696\n>>>> GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7\n>>>> Copyright (C) 2013 Free Software Foundation, Inc.\n>>>> License GPLv3+: GNU GPL version 3 or later <\n>>>> http://gnu.org/licenses/gpl.html>\n>>>> This is free software: you are free to change and redistribute it.\n>>>> There is NO WARRANTY, to the extent permitted by law. Type \"show\n>>>> copying\"\n>>>> and \"show warranty\" for details.\n>>>> This GDB was configured as \"x86_64-redhat-linux-gnu\".\n>>>> For bug reporting instructions, please see:\n>>>> <http://www.gnu.org/software/gdb/bugs/>...\n>>>> Reading symbols from\n>>>> /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.\n>>>> [New LWP 17041]\n>>>> [New LWP 17067]\n>>>> [Thread debugging using libthread_db enabled]\n>>>> Using host libthread_db library \"/lib64/libthread_db.so.1\".\n>>>> Core was generated by `./pg_basebackup -v -j 8 -D\n>>>> /home/edb/Desktop/backup1/'.\n>>>> Program terminated with signal 11, Segmentation fault.\n>>>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>>>> 47 if (INVALID_NOT_TERMINATED_TD_P (pd))\n>>>> (gdb) bt\n>>>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>>>> #1 0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978\n>>>> #2 0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332\n>>>> #3 0x00007f051edc1a49 in __run_exit_handlers (status=1,\n>>>> listp=0x7f051f1436c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true)\n>>>> at exit.c:77\n>>>> #4 0x00007f051edc1a95 in __GI_exit (status=<optimized out>) at\n>>>> exit.c:99\n>>>> #5 0x0000000000408c54 in create_parallel_workers\n>>>> (backupinfo=0x1c6dca0) at pg_basebackup.c:2811\n>>>> #6 0x000000000040798f in BaseBackup () at pg_basebackup.c:2211\n>>>> #7 0x0000000000408b4d in main (argc=6, argv=0x7ffdb76a6d68) at\n>>>> pg_basebackup.c:2765\n>>>> (gdb)\n>>>>\n>>>>\n>>>>\n>>>>\n>>>> 2) The following bug is not fixed yet\n>>>>\n>>>> A similar case is when DB Server is shut down while the Parallel Backup\n>>>> is in progress then the correct error is displayed but then the backup\n>>>> folder is not cleaned and leaves a corrupt backup.\n>>>>\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>>>> -j 8\n>>>> pg_basebackup: warning: backup manifest is disabled in parallel backup\n>>>> mode\n>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>> complete\n>>>> pg_basebackup: checkpoint completed\n>>>> pg_basebackup: write-ahead log start point: 0/A0000028 on timeline 1\n>>>> pg_basebackup: starting background WAL receiver\n>>>> pg_basebackup: created temporary replication slot \"pg_basebackup_16235\"\n>>>> pg_basebackup: backup worker (0) created\n>>>> pg_basebackup: backup worker (1) created\n>>>> pg_basebackup: backup worker (2) created\n>>>> pg_basebackup: backup worker (3) created\n>>>> pg_basebackup: backup worker (4) created\n>>>> pg_basebackup: backup worker (5) created\n>>>> pg_basebackup: backup worker (6) created\n>>>> pg_basebackup: backup worker (7) created\n>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>> connection unexpectedly\n>>>> This probably means the server terminated abnormally\n>>>> before or while processing the request.\n>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>> connection unexpectedly\n>>>> This probably means the server terminated abnormally\n>>>> before or while processing the request.\n>>>> pg_basebackup: removing contents of data directory\n>>>> \"/home/edb/Desktop/backup/\"\n>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>> connection unexpectedly\n>>>> This probably means the server terminated abnormally\n>>>> before or while processing the request.\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$\n>>>>\n>>>>\n>>>>\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$ ls /home/edb/Desktop/backup\n>>>> base pg_hba.conf pg_logical pg_notify pg_serial\n>>>> pg_stat pg_subtrans pg_twophase pg_xact postgresql.conf\n>>>> pg_dynshmem pg_ident.conf pg_multixact pg_replslot pg_snapshots\n>>>> pg_stat_tmp pg_tblspc PG_VERSION postgresql.auto.conf\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$\n>>>>\n>>>>\n>>>>\n>>>>\n>>>> Thanks\n>>>> Kashif Zeeshan\n>>>>\n>>>>>\n>>>>>\n>>>>> On Tue, Apr 7, 2020 at 4:03 PM Kashif Zeeshan <\n>>>>> kashif.zeeshan@enterprisedb.com> wrote:\n>>>>>\n>>>>>>\n>>>>>>\n>>>>>> On Fri, Apr 3, 2020 at 3:01 PM Kashif Zeeshan <\n>>>>>> kashif.zeeshan@enterprisedb.com> wrote:\n>>>>>>\n>>>>>>> Hi Asif\n>>>>>>>\n>>>>>>> When a non-existent slot is used with tablespace then correct error\n>>>>>>> is displayed but then the backup folder is not cleaned and leaves a corrupt\n>>>>>>> backup.\n>>>>>>>\n>>>>>>> Steps\n>>>>>>> =======\n>>>>>>>\n>>>>>>> edb@localhost bin]$\n>>>>>>> [edb@localhost bin]$ mkdir /home/edb/tbl1\n>>>>>>> [edb@localhost bin]$ mkdir /home/edb/tbl_res\n>>>>>>> [edb@localhost bin]$\n>>>>>>> postgres=# create tablespace tbl1 location '/home/edb/tbl1';\n>>>>>>> CREATE TABLESPACE\n>>>>>>> postgres=#\n>>>>>>> postgres=# create table t1 (a int) tablespace tbl1;\n>>>>>>> CREATE TABLE\n>>>>>>> postgres=# insert into t1 values(100);\n>>>>>>> INSERT 0 1\n>>>>>>> postgres=# insert into t1 values(200);\n>>>>>>> INSERT 0 1\n>>>>>>> postgres=# insert into t1 values(300);\n>>>>>>> INSERT 0 1\n>>>>>>> postgres=#\n>>>>>>>\n>>>>>>>\n>>>>>>> [edb@localhost bin]$\n>>>>>>> [edb@localhost bin]$ ./pg_basebackup -v -j 2 -D\n>>>>>>> /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test\n>>>>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>>>>> complete\n>>>>>>> pg_basebackup: checkpoint completed\n>>>>>>> pg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1\n>>>>>>> pg_basebackup: starting background WAL receiver\n>>>>>>> pg_basebackup: error: could not send replication command\n>>>>>>> \"START_REPLICATION\": ERROR: replication slot \"test\" does not exist\n>>>>>>> pg_basebackup: backup worker (0) created\n>>>>>>> pg_basebackup: backup worker (1) created\n>>>>>>> pg_basebackup: write-ahead log end point: 0/2E000100\n>>>>>>> pg_basebackup: waiting for background process to finish streaming ...\n>>>>>>> pg_basebackup: error: child thread exited with error 1\n>>>>>>> [edb@localhost bin]$\n>>>>>>>\n>>>>>>> backup folder not cleaned\n>>>>>>>\n>>>>>>> [edb@localhost bin]$\n>>>>>>> [edb@localhost bin]$\n>>>>>>> [edb@localhost bin]$\n>>>>>>> [edb@localhost bin]$ ls /home/edb/Desktop/backup\n>>>>>>> backup_label global pg_dynshmem pg_ident.conf pg_multixact\n>>>>>>> pg_replslot pg_snapshots pg_stat_tmp pg_tblspc PG_VERSION pg_xact\n>>>>>>> postgresql.conf\n>>>>>>> base pg_commit_ts pg_hba.conf pg_logical pg_notify\n>>>>>>> pg_serial pg_stat pg_subtrans pg_twophase pg_wal\n>>>>>>> postgresql.auto.conf\n>>>>>>> [edb@localhost bin]$\n>>>>>>>\n>>>>>>>\n>>>>>>>\n>>>>>>>\n>>>>>>> If the same case is executed without the parallel backup patch then\n>>>>>>> the backup folder is cleaned after the error is displayed.\n>>>>>>>\n>>>>>>> [edb@localhost bin]$ ./pg_basebackup -v -D\n>>>>>>> /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test999\n>>>>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>>>>> complete\n>>>>>>> pg_basebackup: checkpoint completed\n>>>>>>> pg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1\n>>>>>>> pg_basebackup: starting background WAL receiver\n>>>>>>> pg_basebackup: error: could not send replication command\n>>>>>>> \"START_REPLICATION\": ERROR: replication slot \"test999\" does not exist\n>>>>>>> pg_basebackup: write-ahead log end point: 0/2B000100\n>>>>>>> pg_basebackup: waiting for background process to finish streaming ...\n>>>>>>> pg_basebackup: error: child process exited with exit code 1\n>>>>>>> *pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"*\n>>>>>>> pg_basebackup: changes to tablespace directories will not be undone\n>>>>>>>\n>>>>>>\n>>>>>>\n>>>>>> Hi Asif\n>>>>>>\n>>>>>> A similar case is when DB Server is shut down while the Parallel\n>>>>>> Backup is in progress then the correct error is displayed but then the\n>>>>>> backup folder is not cleaned and leaves a corrupt backup. I think one bug\n>>>>>> fix will solve all these cases where clean up is not done when parallel\n>>>>>> backup is failed.\n>>>>>>\n>>>>>> [edb@localhost bin]$\n>>>>>> [edb@localhost bin]$\n>>>>>> [edb@localhost bin]$ ./pg_basebackup -v -D\n>>>>>> /home/edb/Desktop/backup/ -j 8\n>>>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>>>> complete\n>>>>>> pg_basebackup: checkpoint completed\n>>>>>> pg_basebackup: write-ahead log start point: 0/C1000028 on timeline 1\n>>>>>> pg_basebackup: starting background WAL receiver\n>>>>>> pg_basebackup: created temporary replication slot\n>>>>>> \"pg_basebackup_57337\"\n>>>>>> pg_basebackup: backup worker (0) created\n>>>>>> pg_basebackup: backup worker (1) created\n>>>>>> pg_basebackup: backup worker (2) created\n>>>>>> pg_basebackup: backup worker (3) created\n>>>>>> pg_basebackup: backup worker (4) created\n>>>>>> pg_basebackup: backup worker (5) created\n>>>>>> pg_basebackup: backup worker (6) created\n>>>>>> pg_basebackup: backup worker (7) created\n>>>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>>>> connection unexpectedly\n>>>>>> This probably means the server terminated abnormally\n>>>>>> before or while processing the request.\n>>>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>>>> connection unexpectedly\n>>>>>> This probably means the server terminated abnormally\n>>>>>> before or while processing the request.\n>>>>>> [edb@localhost bin]$\n>>>>>> [edb@localhost bin]$\n>>>>>>\n>>>>>> Same case when executed on pg_basebackup without the Parallel backup\n>>>>>> patch then proper clean up is done.\n>>>>>>\n>>>>>> [edb@localhost bin]$\n>>>>>> [edb@localhost bin]$ ./pg_basebackup -v -D\n>>>>>> /home/edb/Desktop/backup/\n>>>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>>>> complete\n>>>>>> pg_basebackup: checkpoint completed\n>>>>>> pg_basebackup: write-ahead log start point: 0/C5000028 on timeline 1\n>>>>>> pg_basebackup: starting background WAL receiver\n>>>>>> pg_basebackup: created temporary replication slot \"pg_basebackup_5590\"\n>>>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>>>> connection unexpectedly\n>>>>>> This probably means the server terminated abnormally\n>>>>>> before or while processing the request.\n>>>>>> pg_basebackup: removing contents of data directory\n>>>>>> \"/home/edb/Desktop/backup/\"\n>>>>>> [edb@localhost bin]$\n>>>>>>\n>>>>>> Thanks\n>>>>>>\n>>>>>>\n>>>>>>>\n>>>>>>> On Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com>\n>>>>>>> wrote:\n>>>>>>>\n>>>>>>>>\n>>>>>>>>\n>>>>>>>> On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com>\n>>>>>>>> wrote:\n>>>>>>>>\n>>>>>>>>> On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <\n>>>>>>>>> asifr.rehman@gmail.com> wrote:\n>>>>>>>>> >> Why would you need to do that? As long as the process where\n>>>>>>>>> >> STOP_BACKUP can do the check, that seems good enough.\n>>>>>>>>> >\n>>>>>>>>> > Yes, but the user will get the error only after the STOP_BACKUP,\n>>>>>>>>> not while the backup is\n>>>>>>>>> > in progress. So if the backup is a large one, early error\n>>>>>>>>> detection would be much beneficial.\n>>>>>>>>> > This is the current behavior of non-parallel backup as well.\n>>>>>>>>>\n>>>>>>>>> Because non-parallel backup does not feature early detection of\n>>>>>>>>> this\n>>>>>>>>> error, it is not necessary to make parallel backup do so. Indeed,\n>>>>>>>>> it\n>>>>>>>>> is undesirable. If you want to fix that problem, do it on a\n>>>>>>>>> separate\n>>>>>>>>> thread in a separate patch. A patch proposing to make parallel\n>>>>>>>>> backup\n>>>>>>>>> inconsistent in behavior with non-parallel backup will be\n>>>>>>>>> rejected, at\n>>>>>>>>> least if I have anything to say about it.\n>>>>>>>>>\n>>>>>>>>> TBH, fixing this doesn't seem like an urgent problem to me. The\n>>>>>>>>> current situation is not great, but promotions ought to be\n>>>>>>>>> relatively\n>>>>>>>>> infrequent, so I'm not sure it's a huge problem in practice. It is\n>>>>>>>>> also worth considering whether the right fix is to figure out how\n>>>>>>>>> to\n>>>>>>>>> make that case actually work, rather than just making it fail\n>>>>>>>>> quicker.\n>>>>>>>>> I don't currently understand the reason for the prohibition so I\n>>>>>>>>> can't\n>>>>>>>>> express an intelligent opinion on what the right answer is here,\n>>>>>>>>> but\n>>>>>>>>> it seems like it ought to be investigated before somebody goes and\n>>>>>>>>> builds a bunch of infrastructure to make the error more timely.\n>>>>>>>>>\n>>>>>>>>\n>>>>>>>> Non-parallel backup already does the early error checking. I only\n>>>>>>>> intended\n>>>>>>>>\n>>>>>>>> to make parallel behave the same as non-parallel here. So, I agree\n>>>>>>>> with\n>>>>>>>>\n>>>>>>>> you that the behavior of parallel backup should be consistent with\n>>>>>>>> the\n>>>>>>>>\n>>>>>>>> non-parallel one. Please see the code snippet below from\n>>>>>>>>\n>>>>>>>> basebackup.c:sendDir()\n>>>>>>>>\n>>>>>>>>\n>>>>>>>> /*\n>>>>>>>>>\n>>>>>>>>> * Check if the postmaster has signaled us to exit, and abort with\n>>>>>>>>> an\n>>>>>>>>>\n>>>>>>>>> * error in that case. The error handler further up will call\n>>>>>>>>>\n>>>>>>>>> * do_pg_abort_backup() for us. Also check that if the backup was\n>>>>>>>>>\n>>>>>>>>> * started while still in recovery, the server wasn't promoted.\n>>>>>>>>>\n>>>>>>>>> * do_pg_stop_backup() will check that too, but it's better to stop\n>>>>>>>>>\n>>>>>>>>> * the backup early than continue to the end and fail there.\n>>>>>>>>>\n>>>>>>>>> */\n>>>>>>>>>\n>>>>>>>>> CHECK_FOR_INTERRUPTS();\n>>>>>>>>>\n>>>>>>>>> *if* (RecoveryInProgress() != backup_started_in_recovery)\n>>>>>>>>>\n>>>>>>>>> ereport(ERROR,\n>>>>>>>>>\n>>>>>>>>> (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n>>>>>>>>>\n>>>>>>>>> errmsg(\"the standby was promoted during online backup\"),\n>>>>>>>>>\n>>>>>>>>> errhint(\"This means that the backup being taken is corrupt \"\n>>>>>>>>>\n>>>>>>>>> \"and should not be used. \"\n>>>>>>>>>\n>>>>>>>>> \"Try taking another online backup.\")));\n>>>>>>>>>\n>>>>>>>>>\n>>>>>>>>> > Okay, then I will add the shared state. And since we are adding\n>>>>>>>>> the shared state, we can use\n>>>>>>>>> > that for throttling, progress-reporting and standby early error\n>>>>>>>>> checking.\n>>>>>>>>>\n>>>>>>>>> Please propose a grammar here for all the new replication commands\n>>>>>>>>> you\n>>>>>>>>> plan to add before going and implement everything. That will make\n>>>>>>>>> it\n>>>>>>>>> easier to hash out the design without forcing you to keep changing\n>>>>>>>>> the\n>>>>>>>>> code. Your design should include a sketch of how several sets of\n>>>>>>>>> coordinating backends taking several concurrent parallel backups\n>>>>>>>>> will\n>>>>>>>>> end up with one shared state per parallel backup.\n>>>>>>>>>\n>>>>>>>>> > There are two possible options:\n>>>>>>>>> >\n>>>>>>>>> > (1) Server may generate a unique ID i.e.\n>>>>>>>>> BackupID=<unique_string> OR\n>>>>>>>>> > (2) (Preferred Option) Use the WAL start location as the\n>>>>>>>>> BackupID.\n>>>>>>>>> >\n>>>>>>>>> > This BackupID should be given back as a response to start backup\n>>>>>>>>> command. All client workers\n>>>>>>>>> > must append this ID to all parallel backup replication commands.\n>>>>>>>>> So that we can use this identifier\n>>>>>>>>> > to search for that particular backup. Does that sound good?\n>>>>>>>>>\n>>>>>>>>> Using the WAL start location as the backup ID seems like it might\n>>>>>>>>> be\n>>>>>>>>> problematic -- could a single checkpoint not end up as the start\n>>>>>>>>> location for multiple backups started at the same time? Whether\n>>>>>>>>> that's\n>>>>>>>>> possible now or not, it seems unwise to hard-wire that assumption\n>>>>>>>>> into\n>>>>>>>>> the wire protocol.\n>>>>>>>>>\n>>>>>>>>> I was thinking that perhaps the client should generate a unique\n>>>>>>>>> backup\n>>>>>>>>> ID, e.g. leader does:\n>>>>>>>>>\n>>>>>>>>> START_BACKUP unique_backup_id [options]...\n>>>>>>>>>\n>>>>>>>>> And then others do:\n>>>>>>>>>\n>>>>>>>>> JOIN_BACKUP unique_backup_id\n>>>>>>>>>\n>>>>>>>>> My thought is that you will have a number of shared memory\n>>>>>>>>> structure\n>>>>>>>>> equal to max_wal_senders, each one large enough to hold the shared\n>>>>>>>>> state for one backup. The shared state will include\n>>>>>>>>> char[NAMEDATALEN-or-something] which will be used to hold the\n>>>>>>>>> backup\n>>>>>>>>> ID. START_BACKUP would allocate one and copy the name into it;\n>>>>>>>>> JOIN_BACKUP would search for one by name.\n>>>>>>>>>\n>>>>>>>>> If you want to generate the name on the server side, then I suppose\n>>>>>>>>> START_BACKUP would return a result set that includes the backup ID,\n>>>>>>>>> and clients would have to specify that same backup ID when invoking\n>>>>>>>>> JOIN_BACKUP. The rest would stay the same. I am not sure which way\n>>>>>>>>> is\n>>>>>>>>> better. Either way, the backup ID should be something long and\n>>>>>>>>> hard to\n>>>>>>>>> guess, not e.g. the leader processes' PID. I think we should\n>>>>>>>>> generate\n>>>>>>>>> it using pg_strong_random, say 8 or 16 bytes, and then hex-encode\n>>>>>>>>> the\n>>>>>>>>> result to get a string. That way there's almost no risk of two\n>>>>>>>>> backup\n>>>>>>>>> IDs colliding accidentally, and even if we somehow had a malicious\n>>>>>>>>> user trying to screw up somebody else's parallel backup by\n>>>>>>>>> choosing a\n>>>>>>>>> colliding backup ID, it would be pretty hard to have any success. A\n>>>>>>>>> user with enough access to do that sort of thing can probably\n>>>>>>>>> cause a\n>>>>>>>>> lot worse problems anyway, but it seems pretty easy to guard\n>>>>>>>>> against\n>>>>>>>>> intentional collisions robustly here, so I think we should.\n>>>>>>>>>\n>>>>>>>>>\n>>>>>>>> Okay so If we are to add another replication command ‘JOIN_BACKUP\n>>>>>>>> unique_backup_id’\n>>>>>>>> to make workers find the relevant shared state. There won't be any\n>>>>>>>> need for changing\n>>>>>>>> the grammar for any other command. The START_BACKUP can return the\n>>>>>>>> unique_backup_id\n>>>>>>>> in the result set.\n>>>>>>>>\n>>>>>>>> I am thinking of the following struct for shared state:\n>>>>>>>>\n>>>>>>>>> *typedef* *struct*\n>>>>>>>>>\n>>>>>>>>> {\n>>>>>>>>>\n>>>>>>>>> *char* backupid[NAMEDATALEN];\n>>>>>>>>>\n>>>>>>>>> XLogRecPtr startptr;\n>>>>>>>>>\n>>>>>>>>>\n>>>>>>>>> slock_t lock;\n>>>>>>>>>\n>>>>>>>>> int64 throttling_counter;\n>>>>>>>>>\n>>>>>>>>> *bool* backup_started_in_recovery;\n>>>>>>>>>\n>>>>>>>>> } BackupSharedState;\n>>>>>>>>>\n>>>>>>>>>\n>>>>>>>> The shared state structure entries would be maintained by a shared\n>>>>>>>> hash table.\n>>>>>>>> There will be one structure per parallel backup. Since a single\n>>>>>>>> parallel backup\n>>>>>>>> can engage more than one wal sender, so I think max_wal_senders\n>>>>>>>> might be a little\n>>>>>>>> too much; perhaps max_wal_senders/2 since there will be at least 2\n>>>>>>>> connections\n>>>>>>>> per parallel backup? Alternatively, we can set a new GUC that\n>>>>>>>> defines the maximum\n>>>>>>>> number of for concurrent parallel backups i.e.\n>>>>>>>> ‘max_concurent_backups_allowed = 10’\n>>>>>>>> perhaps, or we can make it user-configurable.\n>>>>>>>>\n>>>>>>>> The key would be “backupid=hex_encode(pg_random_strong(16))”\n>>>>>>>>\n>>>>>>>> Checking for Standby Promotion:\n>>>>>>>> At the START_BACKUP command, we initialize\n>>>>>>>> BackupSharedState.backup_started_in_recovery\n>>>>>>>> and keep checking it whenever send_file () is called to send a new\n>>>>>>>> file.\n>>>>>>>>\n>>>>>>>> Throttling:\n>>>>>>>> BackupSharedState.throttling_counter - The throttling logic remains\n>>>>>>>> the same\n>>>>>>>> as for non-parallel backup with the exception that multiple threads\n>>>>>>>> will now be\n>>>>>>>> updating it. So in parallel backup, this will represent the overall\n>>>>>>>> bytes that\n>>>>>>>> have been transferred. So the workers would sleep if they have\n>>>>>>>> exceeded the\n>>>>>>>> limit. Hence, the shared state carries a lock to safely update the\n>>>>>>>> throttling\n>>>>>>>> value atomically.\n>>>>>>>>\n>>>>>>>> Progress Reporting:\n>>>>>>>> Although I think we should add progress-reporting for parallel\n>>>>>>>> backup as a\n>>>>>>>> separate patch. The relevant entries for progress-reporting such as\n>>>>>>>> ‘backup_total’ and ‘backup_streamed’ would be then added to this\n>>>>>>>> structure\n>>>>>>>> as well.\n>>>>>>>>\n>>>>>>>>\n>>>>>>>> Grammar:\n>>>>>>>> There is a change in the resultset being returned for START_BACKUP\n>>>>>>>> command;\n>>>>>>>> unique_backup_id is added. Additionally, JOIN_BACKUP replication\n>>>>>>>> command is\n>>>>>>>> added. SEND_FILES has been renamed to SEND_FILE. There are no other\n>>>>>>>> changes\n>>>>>>>> to the grammar.\n>>>>>>>>\n>>>>>>>> START_BACKUP [LABEL '<label>'] [FAST]\n>>>>>>>> - returns startptr, tli, backup_label, unique_backup_id\n>>>>>>>> STOP_BACKUP [NOWAIT]\n>>>>>>>> - returns startptr, tli, backup_label\n>>>>>>>> JOIN_BACKUP ‘unique_backup_id’\n>>>>>>>> - attaches a shared state identified by ‘unique_backup_id’ to a\n>>>>>>>> backend process.\n>>>>>>>>\n>>>>>>>> LIST_TABLESPACES [PROGRESS]\n>>>>>>>> LIST_FILES [TABLESPACE]\n>>>>>>>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>>>>>>> SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\n>>>>>>>>\n>>>>>>>>\n>>>>\n>>>\n>>> Hi,\n>>>\n>>> rebased and updated to the current master (8128b0c1). v13 is attached.\n>>>\n>>> - Fixes the above reported issues.\n>>>\n>>> - Added progress-reporting support for parallel:\n>>> For this, 'backup_streamed' is moved to a shared structure (BackupState)\n>>> as\n>>> pg_atomic_uint64 variable. The worker processes will keep incrementing\n>>> this\n>>> variable.\n>>>\n>>> While files are being transferred from server to client. The main\n>>> process remains\n>>> in an idle state. So after each increment, the worker process will\n>>> signal master to\n>>> update the stats in pg_stat_progress_basebackup view.\n>>>\n>>> The 'tablespace_streamed' column is not updated and will remain empty.\n>>> This is\n>>> because multiple workers may be copying files from different tablespaces.\n>>>\n>>>\n>>> - Added backup manifest:\n>>> The backend workers maintain their own manifest file which contains a\n>>> list of files\n>>> that are being transferred by the work. Once all backup files are\n>>> transferred, the\n>>> workers will create a temp file as\n>>> ('pg_tempdir/temp_file_prefix_backupid.workerid')\n>>> to write the content of the manifest file from BufFile. The workers\n>>> won’t add the\n>>> header, nor the WAL information in their manifest. These two will be\n>>> added by the\n>>> main process while merging all worker manifest files.\n>>>\n>>> The main process will read these individual files and concatenate them\n>>> into a single file\n>>> which is then sent back to the client.\n>>>\n>>> The manifest file is created when the following command is received:\n>>>\n>>>> BUILD_MANIFEST 'backupid'\n>>>\n>>>\n>>> This is a new replication command. It is sent when pg_basebackup has\n>>> copied all the\n>>> $PGDATA files including WAL files.\n>>>\n>>>\n>>>\n>>> --\n>>> Asif Rehman\n>>> Highgo Software (Canada/China/Pakistan)\n>>> URL : www.highgo.ca\n>>>\n>>>\n>>\n>> --\n>> Regards\n>> ====================================\n>> Kashif Zeeshan\n>> Lead Quality Assurance Engineer / Manager\n>>\n>> EnterpriseDB Corporation\n>> The Enterprise Postgres Company\n>>\n>>\n>\n> --\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\n-- \nRegards\n====================================\nKashif Zeeshan\nLead Quality Assurance Engineer / Manager\n\nEnterpriseDB Corporation\nThe Enterprise Postgres Company\n\nOn Tue, Apr 14, 2020 at 7:37 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Tue, Apr 14, 2020 at 6:32 PM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:Hi AsifGetting the following error on Parallel backup when --no-manifest option is used.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -j 5  -D  /home/edb/Desktop/backup/ --no-manifestpg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_10223\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: write-ahead log end point: 0/2000100pg_basebackup: error: could not get data for 'BUILD_MANIFEST': ERROR:  could not open file \"base/pgsql_tmp/pgsql_tmp_b4ef5ac0fd150b2a28caf626bbb1bef2.1\": No such file or directorypg_basebackup: removing contents of data directory \"/home/edb/Desktop/backup/\"[edb@localhost bin]$ I forgot to make a check for no-manifest. Fixed. Attached is the updated patch.Hi AsifVerified the fix, thanks.[edb@localhost bin]$\n[edb@localhost bin]$\n[edb@localhost bin]$ ./pg_basebackup -v -j 5 -D\n/home/edb/Desktop/backup --no-manifest\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 0/4000028 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: created temporary replication slot \"pg_basebackup_27407\"\npg_basebackup: backup worker (0) created\npg_basebackup: backup worker (1) created\npg_basebackup: backup worker (2) created\npg_basebackup: backup worker (3) created\npg_basebackup: backup worker (4) created\npg_basebackup: write-ahead log end point: 0/4000100\npg_basebackup: waiting for background process to finish streaming ...\npg_basebackup: syncing data to disk ...\npg_basebackup: base backup completed\n[edb@localhost bin]$\n[edb@localhost bin]$ ls /home/edb/Desktop/backup\nbackup_label  pg_commit_ts  pg_ident.conf  pg_notify    pg_snapshots\npg_subtrans  PG_VERSION  postgresql.auto.conf\nbase          pg_dynshmem   pg_logical     pg_replslot  pg_stat\npg_tblspc    pg_wal      postgresql.conf\nglobal        pg_hba.conf   pg_multixact   pg_serial    pg_stat_tmp\npg_twophase  pg_xact\n[edb@localhost bin]$\n[edb@localhost bin]$\n[edb@localhost bin]$RegardsKashif ZeeshanThanksOn Tue, Apr 14, 2020 at 5:33 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Wed, Apr 8, 2020 at 6:53 PM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:On Tue, Apr 7, 2020 at 9:44 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Hi,Thanks, Kashif and Rajkumar. I have fixed the reported issues.I have added the shared state as previously described. The new grammar changesare as follows:START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]    - This will generate a unique backupid using pg_strong_random(16) and hex-encoded      it. which is then returned as the result set.    - It will also create a shared state and add it to the hashtable. The hash table size is set      to BACKUP_HASH_SIZE=10, but since hashtable can expand dynamically, I think it's      sufficient initial size. max_wal_senders is not used, because it can be set to quite a       large values.JOIN_BACKUP 'backup_id'    - finds 'backup_id' in hashtable and attaches it to server process.SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]    - renamed SEND_FILES to SEND_FILE    - removed START_WAL_LOCATION from this because 'startptr' is now accessible through      shared state.There is no change in other commands:STOP_BACKUP [NOWAIT]LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']The current patches (v11) have been rebased to the latest master. The backup manifest is enabledby default, so I have disabled it for parallel backup mode and have generated a warning so thatuser is aware of it and not expect it in the backup.Hi AsifI have verified the bug fixes, one bug is fixed and working now as expected For the verification of the other bug fixes faced following issues, please have a look.1) Following bug fixes mentioned below are generating segmentation fault. Please note for reference I have added a description only as steps were given in previous emails of each bug I tried to verify the fix. Backtrace is also added with each case which points to one bug for both the cases.a) The backup failed with errors \"error: could not connect to server: could not look up local user ID 1000: Too many open files\" when the max_wal_senders was set to 2000. [edb@localhost bin]$ ./pg_basebackup -v -j 1990 -D  /home/edb/Desktop/backup/pg_basebackup: warning: backup manifest is disabled in parallel backup modepg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_9925\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) created….….pg_basebackup: backup worker (1014) createdpg_basebackup: backup worker (1015) createdpg_basebackup: backup worker (1016) createdpg_basebackup: backup worker (1017) createdpg_basebackup: error: could not connect to server: could not look up local user ID 1000: Too many open filesSegmentation fault[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ gdb pg_basebackup /tmp/cores/core.pg_basebackup.13219.localhost.localdomain.1586349551 GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7Copyright (C) 2013 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"and \"show warranty\" for details.This GDB was configured as \"x86_64-redhat-linux-gnu\".For bug reporting instructions, please see:<http://www.gnu.org/software/gdb/bugs/>...Reading symbols from /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.[New LWP 13219][New LWP 13222][Thread debugging using libthread_db enabled]Using host libthread_db library \"/lib64/libthread_db.so.1\".Core was generated by `./pg_basebackup -v -j 1990 -D /home/edb/Desktop/backup/'.Program terminated with signal 11, Segmentation fault.#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:4747\t  if (INVALID_NOT_TERMINATED_TD_P (pd))(gdb) bt#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47#1  0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978#2  0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332#3  0x00007f2226f76a49 in __run_exit_handlers (status=1, listp=0x7f22272f86c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true) at exit.c:77#4  0x00007f2226f76a95 in __GI_exit (status=<optimized out>) at exit.c:99#5  0x0000000000408c54 in create_parallel_workers (backupinfo=0x952ca0) at pg_basebackup.c:2811#6  0x000000000040798f in BaseBackup () at pg_basebackup.c:2211#7  0x0000000000408b4d in main (argc=6, argv=0x7ffe3dabc718) at pg_basebackup.c:2765(gdb) b) When\n executing two backups at the same time, getting FATAL error due to \nmax_wal_senders and instead of exit  Backup got completed.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -j 8 -D  /home/edb/Desktop/backup1/pg_basebackup: warning: backup manifest is disabled in parallel backup modepg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 1/DA000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_17066\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)Segmentation fault (core dumped)[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ gdb pg_basebackup /tmp/cores/core.pg_basebackup.17041.localhost.localdomain.1586353696 GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7Copyright (C) 2013 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"and \"show warranty\" for details.This GDB was configured as \"x86_64-redhat-linux-gnu\".For bug reporting instructions, please see:<http://www.gnu.org/software/gdb/bugs/>...Reading symbols from /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.[New LWP 17041][New LWP 17067][Thread debugging using libthread_db enabled]Using host libthread_db library \"/lib64/libthread_db.so.1\".Core was generated by `./pg_basebackup -v -j 8 -D /home/edb/Desktop/backup1/'.Program terminated with signal 11, Segmentation fault.#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:4747\t  if (INVALID_NOT_TERMINATED_TD_P (pd))(gdb) bt#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47#1  0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978#2  0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332#3  0x00007f051edc1a49 in __run_exit_handlers (status=1, listp=0x7f051f1436c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true) at exit.c:77#4  0x00007f051edc1a95 in __GI_exit (status=<optimized out>) at exit.c:99#5  0x0000000000408c54 in create_parallel_workers (backupinfo=0x1c6dca0) at pg_basebackup.c:2811#6  0x000000000040798f in BaseBackup () at pg_basebackup.c:2211#7  0x0000000000408b4d in main (argc=6, argv=0x7ffdb76a6d68) at pg_basebackup.c:2765(gdb) 2) The following bug is not fixed yetA similar case is when DB Server is shut down while the Parallel Backup is in progress then the correct error\n is displayed but then the backup folder is not cleaned and leaves a \ncorrupt backup. [edb@localhost bin]$ [edb@localhost bin]$ ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -j 8pg_basebackup: warning: backup manifest is disabled in parallel backup modepg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/A0000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_16235\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: backup worker (7) createdpg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: removing contents of data directory \"/home/edb/Desktop/backup/\"pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ ls /home/edb/Desktop/backupbase         pg_hba.conf    pg_logical    pg_notify    pg_serial     pg_stat      pg_subtrans  pg_twophase  pg_xact               postgresql.confpg_dynshmem  pg_ident.conf  pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    PG_VERSION   postgresql.auto.conf[edb@localhost bin]$ [edb@localhost bin]$ ThanksKashif ZeeshanOn Tue, Apr 7, 2020 at 4:03 PM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:On Fri, Apr 3, 2020 at 3:01 PM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:Hi AsifWhen a non-existent slot is used with tablespace then correct error is displayed but then the backup folder is not cleaned and leaves a corrupt backup.Steps=======edb@localhost bin]$ [edb@localhost bin]$ mkdir /home/edb/tbl1[edb@localhost bin]$ mkdir /home/edb/tbl_res[edb@localhost bin]$ postgres=#  create tablespace tbl1 location '/home/edb/tbl1';CREATE TABLESPACEpostgres=# postgres=# create table t1 (a int) tablespace tbl1;CREATE TABLEpostgres=# insert into t1 values(100);INSERT 0 1postgres=# insert into t1 values(200);INSERT 0 1postgres=# insert into t1 values(300);INSERT 0 1postgres=# [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -j 2 -D  /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S testpg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test\" does not existpg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: write-ahead log end point: 0/2E000100pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: error: child thread exited with error 1[edb@localhost bin]$ backup folder not cleaned[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ ls /home/edb/Desktop/backupbackup_label  global        pg_dynshmem  pg_ident.conf  pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    PG_VERSION  pg_xact               postgresql.confbase          pg_commit_ts  pg_hba.conf  pg_logical     pg_notify     pg_serial    pg_stat       pg_subtrans  pg_twophase  pg_wal      postgresql.auto.conf[edb@localhost bin]$ If the same case is executed without the parallel backup patch then the backup folder is cleaned after the error is displayed.[edb@localhost bin]$ ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test999pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test999\" does not existpg_basebackup: write-ahead log end point: 0/2B000100pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: error: child process exited with exit code 1pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"pg_basebackup: changes to tablespace directories will not be undoneHi AsifA similar case is when DB Server is shut down while the Parallel Backup is in progress then the correct error\n is displayed but then the backup folder is not cleaned and leaves a \ncorrupt backup. I think one bug fix will solve all these cases where clean up is not done when parallel backup is failed.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -j 8pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C1000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_57337\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: backup worker (7) createdpg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.[edb@localhost bin]$ [edb@localhost bin]$ Same case when executed on pg_basebackup without the Parallel backup patch then proper clean up is done.[edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -D  /home/edb/Desktop/backup/ pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C5000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_5590\"pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: removing contents of data directory \"/home/edb/Desktop/backup/\"[edb@localhost bin]$ ThanksOn Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com> wrote:On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>> Why would you need to do that? As long as the process where\n>> STOP_BACKUP can do the check, that seems good enough.\n>\n> Yes, but the user will get the error only after the STOP_BACKUP, not while the backup is\n> in progress. So if the backup is a large one, early error detection would be much beneficial.\n> This is the current behavior of non-parallel backup as well.\n\nBecause non-parallel backup does not feature early detection of this\nerror, it is not necessary to make parallel backup do so. Indeed, it\nis undesirable. If you want to fix that problem, do it on a separate\nthread in a separate patch. A patch proposing to make parallel backup\ninconsistent in behavior with non-parallel backup will be rejected, at\nleast if I have anything to say about it.\n\nTBH, fixing this doesn't seem like an urgent problem to me. The\ncurrent situation is not great, but promotions ought to be relatively\ninfrequent, so I'm not sure it's a huge problem in practice. It is\nalso worth considering whether the right fix is to figure out how to\nmake that case actually work, rather than just making it fail quicker.\nI don't currently understand the reason for the prohibition so I can't\nexpress an intelligent opinion on what the right answer is here, but\nit seems like it ought to be investigated before somebody goes and\nbuilds a bunch of infrastructure to make the error more timely.Non-parallel backup already does the early error checking. I only intendedto make parallel behave the same as non-parallel here. So, I agree withyou that the behavior of parallel backup should be consistent with thenon-parallel one.  Please see the code snippet below from basebackup.c:sendDir()/*\n * Check if the postmaster has signaled us to exit, and abort with an\n * error in that case. The error handler further up will call\n * do_pg_abort_backup() for us. Also check that if the backup was\n * started while still in recovery, the server wasn't promoted.\n * do_pg_stop_backup() will check that too, but it's better to stop\n * the backup early than continue to the end and fail there.\n */\nCHECK_FOR_INTERRUPTS();\nif (RecoveryInProgress() != backup_started_in_recovery)\n ereport(ERROR,\n (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n errmsg(\"the standby was promoted during online backup\"),\n errhint(\"This means that the backup being taken is corrupt \"\n \"and should not be used. \"\n \"Try taking another online backup.\"))); \n\n> Okay, then I will add the shared state. And since we are adding the shared state, we can use\n> that for throttling, progress-reporting and standby early error checking.\n\nPlease propose a grammar here for all the new replication commands you\nplan to add before going and implement everything. That will make it\neasier to hash out the design without forcing you to keep changing the\ncode. Your design should include a sketch of how several sets of\ncoordinating backends taking several concurrent parallel backups will\nend up with one shared state per parallel backup.\n\n> There are two possible options:\n>\n> (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n> (2) (Preferred Option) Use the WAL start location as the BackupID.\n>\n> This BackupID should be given back as a response to start backup command. All client workers\n> must append this ID to all parallel backup replication commands. So that we can use this identifier\n> to search for that particular backup. Does that sound good?\n\nUsing the WAL start location as the backup ID seems like it might be\nproblematic -- could a single checkpoint not end up as the start\nlocation for multiple backups started at the same time? Whether that's\npossible now or not, it seems unwise to hard-wire that assumption into\nthe wire protocol.\n\nI was thinking that perhaps the client should generate a unique backup\nID, e.g. leader does:\n\nSTART_BACKUP unique_backup_id [options]...\n\nAnd then others do:\n\nJOIN_BACKUP unique_backup_id\n\nMy thought is that you will have a number of shared memory structure\nequal to max_wal_senders, each one large enough to hold the shared\nstate for one backup. The shared state will include\nchar[NAMEDATALEN-or-something] which will be used to hold the backup\nID. START_BACKUP would allocate one and copy the name into it;\nJOIN_BACKUP would search for one by name.\n\nIf you want to generate the name on the server side, then I suppose\nSTART_BACKUP would return a result set that includes the backup ID,\nand clients would have to specify that same backup ID when invoking\nJOIN_BACKUP. The rest would stay the same. I am not sure which way is\nbetter. Either way, the backup ID should be something long and hard to\nguess, not e.g. the leader processes' PID. I think we should generate\nit using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\nresult to get a string. That way there's almost no risk of two backup\nIDs colliding accidentally, and even if we somehow had a malicious\nuser trying to screw up somebody else's parallel backup by choosing a\ncolliding backup ID, it would be pretty hard to have any success. A\nuser with enough access to do that sort of thing can probably cause a\nlot worse problems anyway, but it seems pretty easy to guard against\nintentional collisions robustly here, so I think we should.\nOkay so If we are to add another replication command ‘JOIN_BACKUP unique_backup_id’to make workers find the relevant shared state. There won't be any need for changingthe grammar for any other command. The START_BACKUP can return the unique_backup_idin the result set.I am thinking of the following struct for shared state:typedef struct\n{\n char backupid[NAMEDATALEN];\n XLogRecPtr startptr;\n\n slock_t lock;\n int64 throttling_counter;\n bool backup_started_in_recovery;\n} BackupSharedState;The shared state structure entries would be maintained by a shared hash table.There will be one structure per parallel backup. Since a single parallel backupcan engage more than one wal sender, so I think max_wal_senders might be a littletoo much; perhaps max_wal_senders/2 since there will be at least 2 connectionsper parallel backup? Alternatively, we can set a new GUC that defines the maximumnumber of for concurrent parallel backups i.e. ‘max_concurent_backups_allowed = 10’ perhaps, or we can make it user-configurable.The key would be “backupid=hex_encode(pg_random_strong(16))”Checking for Standby Promotion:At the START_BACKUP command, we initialize BackupSharedState.backup_started_in_recovery and keep checking it whenever send_file () is called to send a new file.Throttling:BackupSharedState.throttling_counter - The throttling logic remains the sameas for non-parallel backup with the exception that multiple threads will now beupdating it. So in parallel backup, this will represent the overall bytes thathave been transferred. So the workers would sleep if they have exceeded thelimit. Hence, the shared state carries a lock to safely update the throttlingvalue atomically. Progress Reporting:Although I think we should add progress-reporting for parallel backup as aseparate patch. The relevant entries for progress-reporting such as ‘backup_total’ and ‘backup_streamed’ would be then added to this structureas well.  Grammar:There is a change in the resultset being returned for START_BACKUP command; unique_backup_id is added. Additionally, JOIN_BACKUP replication command isadded. SEND_FILES has been renamed to SEND_FILE. There are no other changesto the grammar.START_BACKUP [LABEL '<label>'] [FAST]  - returns startptr, tli, backup_label, unique_backup_idSTOP_BACKUP [NOWAIT]  - returns startptr, tli, backup_labelJOIN_BACKUP ‘unique_backup_id’  - attaches a shared state identified by ‘unique_backup_id’ to a backend process. LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\nHi,rebased and updated to the current master (8128b0c1). v13 is attached.- Fixes the above reported issues.- Added progress-reporting support for parallel:For this, 'backup_streamed' is moved to a shared structure (BackupState) aspg_atomic_uint64 variable. The worker processes will keep incrementing thisvariable.While files are being transferred from server to client. The main process remainsin an idle state. So after each increment, the worker process will signal master toupdate the stats in pg_stat_progress_basebackup view.The 'tablespace_streamed' column is not updated and will remain empty. This isbecause multiple workers may be copying files from different tablespaces.- Added backup manifest:The backend workers maintain their own manifest file which contains a list of filesthat are being transferred by the work. Once all backup files are transferred, theworkers will create a temp file as ('pg_tempdir/temp_file_prefix_backupid.workerid')to write the content of the manifest file from BufFile. The workers won’t add theheader, nor the WAL information in their manifest. These two will be added by themain process while merging all worker manifest files.The main process will read these individual files and concatenate them into a single filewhich is then sent back to the client. The manifest file is created when the following command is received:    BUILD_MANIFEST 'backupid'This is a new replication command. It is sent when pg_basebackup has copied all the$PGDATA files including WAL files.--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- Regards====================================Kashif ZeeshanLead Quality Assurance Engineer / ManagerEnterpriseDB CorporationThe Enterprise Postgres Company\n-- --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- Regards====================================Kashif ZeeshanLead Quality Assurance Engineer / ManagerEnterpriseDB CorporationThe Enterprise Postgres Company", "msg_date": "Fri, 17 Apr 2020 11:00:55 +0500", "msg_from": "Kashif Zeeshan <kashif.zeeshan@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Apr 14, 2020 at 5:33 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Wed, Apr 8, 2020 at 6:53 PM Kashif Zeeshan <\n> kashif.zeeshan@enterprisedb.com> wrote:\n>\n>>\n>>\n>> On Tue, Apr 7, 2020 at 9:44 PM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>>\n>>> Hi,\n>>>\n>>> Thanks, Kashif and Rajkumar. I have fixed the reported issues.\n>>>\n>>> I have added the shared state as previously described. The new grammar\n>>> changes\n>>> are as follows:\n>>>\n>>> START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]\n>>> - This will generate a unique backupid using pg_strong_random(16)\n>>> and hex-encoded\n>>> it. which is then returned as the result set.\n>>> - It will also create a shared state and add it to the hashtable.\n>>> The hash table size is set\n>>> to BACKUP_HASH_SIZE=10, but since hashtable can expand\n>>> dynamically, I think it's\n>>> sufficient initial size. max_wal_senders is not used, because it\n>>> can be set to quite a\n>>> large values.\n>>>\n>>> JOIN_BACKUP 'backup_id'\n>>> - finds 'backup_id' in hashtable and attaches it to server process.\n>>>\n>>>\n>>> SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]\n>>> - renamed SEND_FILES to SEND_FILE\n>>> - removed START_WAL_LOCATION from this because 'startptr' is now\n>>> accessible through\n>>> shared state.\n>>>\n>>> There is no change in other commands:\n>>> STOP_BACKUP [NOWAIT]\n>>> LIST_TABLESPACES [PROGRESS]\n>>> LIST_FILES [TABLESPACE]\n>>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>>\n>>> The current patches (v11) have been rebased to the latest master. The\n>>> backup manifest is enabled\n>>> by default, so I have disabled it for parallel backup mode and have\n>>> generated a warning so that\n>>> user is aware of it and not expect it in the backup.\n>>>\n>>> Hi Asif\n>>\n>> I have verified the bug fixes, one bug is fixed and working now as\n>> expected\n>>\n>> For the verification of the other bug fixes faced following issues,\n>> please have a look.\n>>\n>>\n>> 1) Following bug fixes mentioned below are generating segmentation fault.\n>>\n>> Please note for reference I have added a description only as steps were\n>> given in previous emails of each bug I tried to verify the fix. Backtrace\n>> is also added with each case which points to one bug for both the cases.\n>>\n>> a) The backup failed with errors \"error: could not connect to server:\n>> could not look up local user ID 1000: Too many open files\" when the\n>> max_wal_senders was set to 2000.\n>>\n>>\n>> [edb@localhost bin]$ ./pg_basebackup -v -j 1990 -D\n>> /home/edb/Desktop/backup/\n>> pg_basebackup: warning: backup manifest is disabled in parallel backup\n>> mode\n>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>> pg_basebackup: checkpoint completed\n>> pg_basebackup: write-ahead log start point: 0/2000028 on timeline 1\n>> pg_basebackup: starting background WAL receiver\n>> pg_basebackup: created temporary replication slot \"pg_basebackup_9925\"\n>> pg_basebackup: backup worker (0) created\n>> pg_basebackup: backup worker (1) created\n>> pg_basebackup: backup worker (2) created\n>> pg_basebackup: backup worker (3) created\n>> ….\n>> ….\n>> pg_basebackup: backup worker (1014) created\n>> pg_basebackup: backup worker (1015) created\n>> pg_basebackup: backup worker (1016) created\n>> pg_basebackup: backup worker (1017) created\n>> pg_basebackup: error: could not connect to server: could not look up\n>> local user ID 1000: Too many open files\n>> Segmentation fault\n>> [edb@localhost bin]$\n>>\n>>\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ gdb pg_basebackup\n>> /tmp/cores/core.pg_basebackup.13219.localhost.localdomain.1586349551\n>> GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7\n>> Copyright (C) 2013 Free Software Foundation, Inc.\n>> License GPLv3+: GNU GPL version 3 or later <\n>> http://gnu.org/licenses/gpl.html>\n>> This is free software: you are free to change and redistribute it.\n>> There is NO WARRANTY, to the extent permitted by law. Type \"show copying\"\n>> and \"show warranty\" for details.\n>> This GDB was configured as \"x86_64-redhat-linux-gnu\".\n>> For bug reporting instructions, please see:\n>> <http://www.gnu.org/software/gdb/bugs/>...\n>> Reading symbols from\n>> /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.\n>> [New LWP 13219]\n>> [New LWP 13222]\n>> [Thread debugging using libthread_db enabled]\n>> Using host libthread_db library \"/lib64/libthread_db.so.1\".\n>> Core was generated by `./pg_basebackup -v -j 1990 -D\n>> /home/edb/Desktop/backup/'.\n>> Program terminated with signal 11, Segmentation fault.\n>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>> 47 if (INVALID_NOT_TERMINATED_TD_P (pd))\n>> (gdb) bt\n>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>> #1 0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978\n>> #2 0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332\n>> #3 0x00007f2226f76a49 in __run_exit_handlers (status=1,\n>> listp=0x7f22272f86c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true)\n>> at exit.c:77\n>> #4 0x00007f2226f76a95 in __GI_exit (status=<optimized out>) at exit.c:99\n>> #5 0x0000000000408c54 in create_parallel_workers (backupinfo=0x952ca0)\n>> at pg_basebackup.c:2811\n>> #6 0x000000000040798f in BaseBackup () at pg_basebackup.c:2211\n>> #7 0x0000000000408b4d in main (argc=6, argv=0x7ffe3dabc718) at\n>> pg_basebackup.c:2765\n>> (gdb)\n>>\n>>\n>>\n>>\n>> b) When executing two backups at the same time, getting FATAL error due\n>> to max_wal_senders and instead of exit Backup got completed.\n>>\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ ./pg_basebackup -v -j 8 -D\n>> /home/edb/Desktop/backup1/\n>> pg_basebackup: warning: backup manifest is disabled in parallel backup\n>> mode\n>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>> pg_basebackup: checkpoint completed\n>> pg_basebackup: write-ahead log start point: 1/DA000028 on timeline 1\n>> pg_basebackup: starting background WAL receiver\n>> pg_basebackup: created temporary replication slot \"pg_basebackup_17066\"\n>> pg_basebackup: backup worker (0) created\n>> pg_basebackup: backup worker (1) created\n>> pg_basebackup: backup worker (2) created\n>> pg_basebackup: backup worker (3) created\n>> pg_basebackup: backup worker (4) created\n>> pg_basebackup: backup worker (5) created\n>> pg_basebackup: backup worker (6) created\n>> pg_basebackup: error: could not connect to server: FATAL: number of\n>> requested standby connections exceeds max_wal_senders (currently 10)\n>> Segmentation fault (core dumped)\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ gdb pg_basebackup\n>> /tmp/cores/core.pg_basebackup.17041.localhost.localdomain.1586353696\n>> GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7\n>> Copyright (C) 2013 Free Software Foundation, Inc.\n>> License GPLv3+: GNU GPL version 3 or later <\n>> http://gnu.org/licenses/gpl.html>\n>> This is free software: you are free to change and redistribute it.\n>> There is NO WARRANTY, to the extent permitted by law. Type \"show copying\"\n>> and \"show warranty\" for details.\n>> This GDB was configured as \"x86_64-redhat-linux-gnu\".\n>> For bug reporting instructions, please see:\n>> <http://www.gnu.org/software/gdb/bugs/>...\n>> Reading symbols from\n>> /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.\n>> [New LWP 17041]\n>> [New LWP 17067]\n>> [Thread debugging using libthread_db enabled]\n>> Using host libthread_db library \"/lib64/libthread_db.so.1\".\n>> Core was generated by `./pg_basebackup -v -j 8 -D\n>> /home/edb/Desktop/backup1/'.\n>> Program terminated with signal 11, Segmentation fault.\n>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>> 47 if (INVALID_NOT_TERMINATED_TD_P (pd))\n>> (gdb) bt\n>> #0 pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47\n>> #1 0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978\n>> #2 0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332\n>> #3 0x00007f051edc1a49 in __run_exit_handlers (status=1,\n>> listp=0x7f051f1436c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true)\n>> at exit.c:77\n>> #4 0x00007f051edc1a95 in __GI_exit (status=<optimized out>) at exit.c:99\n>> #5 0x0000000000408c54 in create_parallel_workers (backupinfo=0x1c6dca0)\n>> at pg_basebackup.c:2811\n>> #6 0x000000000040798f in BaseBackup () at pg_basebackup.c:2211\n>> #7 0x0000000000408b4d in main (argc=6, argv=0x7ffdb76a6d68) at\n>> pg_basebackup.c:2765\n>> (gdb)\n>>\n>>\n>>\n>>\n>> 2) The following bug is not fixed yet\n>>\n>> A similar case is when DB Server is shut down while the Parallel Backup\n>> is in progress then the correct error is displayed but then the backup\n>> folder is not cleaned and leaves a corrupt backup.\n>>\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/ -j\n>> 8\n>> pg_basebackup: warning: backup manifest is disabled in parallel backup\n>> mode\n>> pg_basebackup: initiating base backup, waiting for checkpoint to complete\n>> pg_basebackup: checkpoint completed\n>> pg_basebackup: write-ahead log start point: 0/A0000028 on timeline 1\n>> pg_basebackup: starting background WAL receiver\n>> pg_basebackup: created temporary replication slot \"pg_basebackup_16235\"\n>> pg_basebackup: backup worker (0) created\n>> pg_basebackup: backup worker (1) created\n>> pg_basebackup: backup worker (2) created\n>> pg_basebackup: backup worker (3) created\n>> pg_basebackup: backup worker (4) created\n>> pg_basebackup: backup worker (5) created\n>> pg_basebackup: backup worker (6) created\n>> pg_basebackup: backup worker (7) created\n>> pg_basebackup: error: could not read COPY data: server closed the\n>> connection unexpectedly\n>> This probably means the server terminated abnormally\n>> before or while processing the request.\n>> pg_basebackup: error: could not read COPY data: server closed the\n>> connection unexpectedly\n>> This probably means the server terminated abnormally\n>> before or while processing the request.\n>> pg_basebackup: removing contents of data directory\n>> \"/home/edb/Desktop/backup/\"\n>> pg_basebackup: error: could not read COPY data: server closed the\n>> connection unexpectedly\n>> This probably means the server terminated abnormally\n>> before or while processing the request.\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>>\n>>\n>>\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$ ls /home/edb/Desktop/backup\n>> base pg_hba.conf pg_logical pg_notify pg_serial\n>> pg_stat pg_subtrans pg_twophase pg_xact postgresql.conf\n>> pg_dynshmem pg_ident.conf pg_multixact pg_replslot pg_snapshots\n>> pg_stat_tmp pg_tblspc PG_VERSION postgresql.auto.conf\n>> [edb@localhost bin]$\n>> [edb@localhost bin]$\n>>\n>>\n>>\n>>\n>> Thanks\n>> Kashif Zeeshan\n>>\n>>>\n>>>\n>>> On Tue, Apr 7, 2020 at 4:03 PM Kashif Zeeshan <\n>>> kashif.zeeshan@enterprisedb.com> wrote:\n>>>\n>>>>\n>>>>\n>>>> On Fri, Apr 3, 2020 at 3:01 PM Kashif Zeeshan <\n>>>> kashif.zeeshan@enterprisedb.com> wrote:\n>>>>\n>>>>> Hi Asif\n>>>>>\n>>>>> When a non-existent slot is used with tablespace then correct error is\n>>>>> displayed but then the backup folder is not cleaned and leaves a corrupt\n>>>>> backup.\n>>>>>\n>>>>> Steps\n>>>>> =======\n>>>>>\n>>>>> edb@localhost bin]$\n>>>>> [edb@localhost bin]$ mkdir /home/edb/tbl1\n>>>>> [edb@localhost bin]$ mkdir /home/edb/tbl_res\n>>>>> [edb@localhost bin]$\n>>>>> postgres=# create tablespace tbl1 location '/home/edb/tbl1';\n>>>>> CREATE TABLESPACE\n>>>>> postgres=#\n>>>>> postgres=# create table t1 (a int) tablespace tbl1;\n>>>>> CREATE TABLE\n>>>>> postgres=# insert into t1 values(100);\n>>>>> INSERT 0 1\n>>>>> postgres=# insert into t1 values(200);\n>>>>> INSERT 0 1\n>>>>> postgres=# insert into t1 values(300);\n>>>>> INSERT 0 1\n>>>>> postgres=#\n>>>>>\n>>>>>\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$ ./pg_basebackup -v -j 2 -D\n>>>>> /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test\n>>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>>> complete\n>>>>> pg_basebackup: checkpoint completed\n>>>>> pg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1\n>>>>> pg_basebackup: starting background WAL receiver\n>>>>> pg_basebackup: error: could not send replication command\n>>>>> \"START_REPLICATION\": ERROR: replication slot \"test\" does not exist\n>>>>> pg_basebackup: backup worker (0) created\n>>>>> pg_basebackup: backup worker (1) created\n>>>>> pg_basebackup: write-ahead log end point: 0/2E000100\n>>>>> pg_basebackup: waiting for background process to finish streaming ...\n>>>>> pg_basebackup: error: child thread exited with error 1\n>>>>> [edb@localhost bin]$\n>>>>>\n>>>>> backup folder not cleaned\n>>>>>\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$\n>>>>> [edb@localhost bin]$ ls /home/edb/Desktop/backup\n>>>>> backup_label global pg_dynshmem pg_ident.conf pg_multixact\n>>>>> pg_replslot pg_snapshots pg_stat_tmp pg_tblspc PG_VERSION pg_xact\n>>>>> postgresql.conf\n>>>>> base pg_commit_ts pg_hba.conf pg_logical pg_notify\n>>>>> pg_serial pg_stat pg_subtrans pg_twophase pg_wal\n>>>>> postgresql.auto.conf\n>>>>> [edb@localhost bin]$\n>>>>>\n>>>>>\n>>>>>\n>>>>>\n>>>>> If the same case is executed without the parallel backup patch then\n>>>>> the backup folder is cleaned after the error is displayed.\n>>>>>\n>>>>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>>>>> -T /home/edb/tbl1=/home/edb/tbl_res -S test999\n>>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>>> complete\n>>>>> pg_basebackup: checkpoint completed\n>>>>> pg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1\n>>>>> pg_basebackup: starting background WAL receiver\n>>>>> pg_basebackup: error: could not send replication command\n>>>>> \"START_REPLICATION\": ERROR: replication slot \"test999\" does not exist\n>>>>> pg_basebackup: write-ahead log end point: 0/2B000100\n>>>>> pg_basebackup: waiting for background process to finish streaming ...\n>>>>> pg_basebackup: error: child process exited with exit code 1\n>>>>> *pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"*\n>>>>> pg_basebackup: changes to tablespace directories will not be undone\n>>>>>\n>>>>\n>>>>\n>>>> Hi Asif\n>>>>\n>>>> A similar case is when DB Server is shut down while the Parallel Backup\n>>>> is in progress then the correct error is displayed but then the backup\n>>>> folder is not cleaned and leaves a corrupt backup. I think one bug fix will\n>>>> solve all these cases where clean up is not done when parallel backup is\n>>>> failed.\n>>>>\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>>>> -j 8\n>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>> complete\n>>>> pg_basebackup: checkpoint completed\n>>>> pg_basebackup: write-ahead log start point: 0/C1000028 on timeline 1\n>>>> pg_basebackup: starting background WAL receiver\n>>>> pg_basebackup: created temporary replication slot \"pg_basebackup_57337\"\n>>>> pg_basebackup: backup worker (0) created\n>>>> pg_basebackup: backup worker (1) created\n>>>> pg_basebackup: backup worker (2) created\n>>>> pg_basebackup: backup worker (3) created\n>>>> pg_basebackup: backup worker (4) created\n>>>> pg_basebackup: backup worker (5) created\n>>>> pg_basebackup: backup worker (6) created\n>>>> pg_basebackup: backup worker (7) created\n>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>> connection unexpectedly\n>>>> This probably means the server terminated abnormally\n>>>> before or while processing the request.\n>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>> connection unexpectedly\n>>>> This probably means the server terminated abnormally\n>>>> before or while processing the request.\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$\n>>>>\n>>>> Same case when executed on pg_basebackup without the Parallel backup\n>>>> patch then proper clean up is done.\n>>>>\n>>>> [edb@localhost bin]$\n>>>> [edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/\n>>>> pg_basebackup: initiating base backup, waiting for checkpoint to\n>>>> complete\n>>>> pg_basebackup: checkpoint completed\n>>>> pg_basebackup: write-ahead log start point: 0/C5000028 on timeline 1\n>>>> pg_basebackup: starting background WAL receiver\n>>>> pg_basebackup: created temporary replication slot \"pg_basebackup_5590\"\n>>>> pg_basebackup: error: could not read COPY data: server closed the\n>>>> connection unexpectedly\n>>>> This probably means the server terminated abnormally\n>>>> before or while processing the request.\n>>>> pg_basebackup: removing contents of data directory\n>>>> \"/home/edb/Desktop/backup/\"\n>>>> [edb@localhost bin]$\n>>>>\n>>>> Thanks\n>>>>\n>>>>\n>>>>>\n>>>>> On Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com>\n>>>>> wrote:\n>>>>>\n>>>>>>\n>>>>>>\n>>>>>> On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com>\n>>>>>> wrote:\n>>>>>>\n>>>>>>> On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com>\n>>>>>>> wrote:\n>>>>>>> >> Why would you need to do that? As long as the process where\n>>>>>>> >> STOP_BACKUP can do the check, that seems good enough.\n>>>>>>> >\n>>>>>>> > Yes, but the user will get the error only after the STOP_BACKUP,\n>>>>>>> not while the backup is\n>>>>>>> > in progress. So if the backup is a large one, early error\n>>>>>>> detection would be much beneficial.\n>>>>>>> > This is the current behavior of non-parallel backup as well.\n>>>>>>>\n>>>>>>> Because non-parallel backup does not feature early detection of this\n>>>>>>> error, it is not necessary to make parallel backup do so. Indeed, it\n>>>>>>> is undesirable. If you want to fix that problem, do it on a separate\n>>>>>>> thread in a separate patch. A patch proposing to make parallel backup\n>>>>>>> inconsistent in behavior with non-parallel backup will be rejected,\n>>>>>>> at\n>>>>>>> least if I have anything to say about it.\n>>>>>>>\n>>>>>>> TBH, fixing this doesn't seem like an urgent problem to me. The\n>>>>>>> current situation is not great, but promotions ought to be relatively\n>>>>>>> infrequent, so I'm not sure it's a huge problem in practice. It is\n>>>>>>> also worth considering whether the right fix is to figure out how to\n>>>>>>> make that case actually work, rather than just making it fail\n>>>>>>> quicker.\n>>>>>>> I don't currently understand the reason for the prohibition so I\n>>>>>>> can't\n>>>>>>> express an intelligent opinion on what the right answer is here, but\n>>>>>>> it seems like it ought to be investigated before somebody goes and\n>>>>>>> builds a bunch of infrastructure to make the error more timely.\n>>>>>>>\n>>>>>>\n>>>>>> Non-parallel backup already does the early error checking. I only\n>>>>>> intended\n>>>>>>\n>>>>>> to make parallel behave the same as non-parallel here. So, I agree\n>>>>>> with\n>>>>>>\n>>>>>> you that the behavior of parallel backup should be consistent with the\n>>>>>>\n>>>>>> non-parallel one. Please see the code snippet below from\n>>>>>>\n>>>>>> basebackup.c:sendDir()\n>>>>>>\n>>>>>>\n>>>>>> /*\n>>>>>>>\n>>>>>>> * Check if the postmaster has signaled us to exit, and abort with an\n>>>>>>>\n>>>>>>> * error in that case. The error handler further up will call\n>>>>>>>\n>>>>>>> * do_pg_abort_backup() for us. Also check that if the backup was\n>>>>>>>\n>>>>>>> * started while still in recovery, the server wasn't promoted.\n>>>>>>>\n>>>>>>> * do_pg_stop_backup() will check that too, but it's better to stop\n>>>>>>>\n>>>>>>> * the backup early than continue to the end and fail there.\n>>>>>>>\n>>>>>>> */\n>>>>>>>\n>>>>>>> CHECK_FOR_INTERRUPTS();\n>>>>>>>\n>>>>>>> *if* (RecoveryInProgress() != backup_started_in_recovery)\n>>>>>>>\n>>>>>>> ereport(ERROR,\n>>>>>>>\n>>>>>>> (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n>>>>>>>\n>>>>>>> errmsg(\"the standby was promoted during online backup\"),\n>>>>>>>\n>>>>>>> errhint(\"This means that the backup being taken is corrupt \"\n>>>>>>>\n>>>>>>> \"and should not be used. \"\n>>>>>>>\n>>>>>>> \"Try taking another online backup.\")));\n>>>>>>>\n>>>>>>>\n>>>>>>> > Okay, then I will add the shared state. And since we are adding\n>>>>>>> the shared state, we can use\n>>>>>>> > that for throttling, progress-reporting and standby early error\n>>>>>>> checking.\n>>>>>>>\n>>>>>>> Please propose a grammar here for all the new replication commands\n>>>>>>> you\n>>>>>>> plan to add before going and implement everything. That will make it\n>>>>>>> easier to hash out the design without forcing you to keep changing\n>>>>>>> the\n>>>>>>> code. Your design should include a sketch of how several sets of\n>>>>>>> coordinating backends taking several concurrent parallel backups will\n>>>>>>> end up with one shared state per parallel backup.\n>>>>>>>\n>>>>>>> > There are two possible options:\n>>>>>>> >\n>>>>>>> > (1) Server may generate a unique ID i.e. BackupID=<unique_string>\n>>>>>>> OR\n>>>>>>> > (2) (Preferred Option) Use the WAL start location as the BackupID.\n>>>>>>> >\n>>>>>>> > This BackupID should be given back as a response to start backup\n>>>>>>> command. All client workers\n>>>>>>> > must append this ID to all parallel backup replication commands.\n>>>>>>> So that we can use this identifier\n>>>>>>> > to search for that particular backup. Does that sound good?\n>>>>>>>\n>>>>>>> Using the WAL start location as the backup ID seems like it might be\n>>>>>>> problematic -- could a single checkpoint not end up as the start\n>>>>>>> location for multiple backups started at the same time? Whether\n>>>>>>> that's\n>>>>>>> possible now or not, it seems unwise to hard-wire that assumption\n>>>>>>> into\n>>>>>>> the wire protocol.\n>>>>>>>\n>>>>>>> I was thinking that perhaps the client should generate a unique\n>>>>>>> backup\n>>>>>>> ID, e.g. leader does:\n>>>>>>>\n>>>>>>> START_BACKUP unique_backup_id [options]...\n>>>>>>>\n>>>>>>> And then others do:\n>>>>>>>\n>>>>>>> JOIN_BACKUP unique_backup_id\n>>>>>>>\n>>>>>>> My thought is that you will have a number of shared memory structure\n>>>>>>> equal to max_wal_senders, each one large enough to hold the shared\n>>>>>>> state for one backup. The shared state will include\n>>>>>>> char[NAMEDATALEN-or-something] which will be used to hold the backup\n>>>>>>> ID. START_BACKUP would allocate one and copy the name into it;\n>>>>>>> JOIN_BACKUP would search for one by name.\n>>>>>>>\n>>>>>>> If you want to generate the name on the server side, then I suppose\n>>>>>>> START_BACKUP would return a result set that includes the backup ID,\n>>>>>>> and clients would have to specify that same backup ID when invoking\n>>>>>>> JOIN_BACKUP. The rest would stay the same. I am not sure which way is\n>>>>>>> better. Either way, the backup ID should be something long and hard\n>>>>>>> to\n>>>>>>> guess, not e.g. the leader processes' PID. I think we should generate\n>>>>>>> it using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\n>>>>>>> result to get a string. That way there's almost no risk of two backup\n>>>>>>> IDs colliding accidentally, and even if we somehow had a malicious\n>>>>>>> user trying to screw up somebody else's parallel backup by choosing a\n>>>>>>> colliding backup ID, it would be pretty hard to have any success. A\n>>>>>>> user with enough access to do that sort of thing can probably cause a\n>>>>>>> lot worse problems anyway, but it seems pretty easy to guard against\n>>>>>>> intentional collisions robustly here, so I think we should.\n>>>>>>>\n>>>>>>>\n>>>>>> Okay so If we are to add another replication command ‘JOIN_BACKUP\n>>>>>> unique_backup_id’\n>>>>>> to make workers find the relevant shared state. There won't be any\n>>>>>> need for changing\n>>>>>> the grammar for any other command. The START_BACKUP can return the\n>>>>>> unique_backup_id\n>>>>>> in the result set.\n>>>>>>\n>>>>>> I am thinking of the following struct for shared state:\n>>>>>>\n>>>>>>> *typedef* *struct*\n>>>>>>>\n>>>>>>> {\n>>>>>>>\n>>>>>>> *char* backupid[NAMEDATALEN];\n>>>>>>>\n>>>>>>> XLogRecPtr startptr;\n>>>>>>>\n>>>>>>>\n>>>>>>> slock_t lock;\n>>>>>>>\n>>>>>>> int64 throttling_counter;\n>>>>>>>\n>>>>>>> *bool* backup_started_in_recovery;\n>>>>>>>\n>>>>>>> } BackupSharedState;\n>>>>>>>\n>>>>>>>\n>>>>>> The shared state structure entries would be maintained by a shared\n>>>>>> hash table.\n>>>>>> There will be one structure per parallel backup. Since a single\n>>>>>> parallel backup\n>>>>>> can engage more than one wal sender, so I think max_wal_senders might\n>>>>>> be a little\n>>>>>> too much; perhaps max_wal_senders/2 since there will be at least 2\n>>>>>> connections\n>>>>>> per parallel backup? Alternatively, we can set a new GUC that defines\n>>>>>> the maximum\n>>>>>> number of for concurrent parallel backups i.e.\n>>>>>> ‘max_concurent_backups_allowed = 10’\n>>>>>> perhaps, or we can make it user-configurable.\n>>>>>>\n>>>>>> The key would be “backupid=hex_encode(pg_random_strong(16))”\n>>>>>>\n>>>>>> Checking for Standby Promotion:\n>>>>>> At the START_BACKUP command, we initialize\n>>>>>> BackupSharedState.backup_started_in_recovery\n>>>>>> and keep checking it whenever send_file () is called to send a new\n>>>>>> file.\n>>>>>>\n>>>>>> Throttling:\n>>>>>> BackupSharedState.throttling_counter - The throttling logic remains\n>>>>>> the same\n>>>>>> as for non-parallel backup with the exception that multiple threads\n>>>>>> will now be\n>>>>>> updating it. So in parallel backup, this will represent the overall\n>>>>>> bytes that\n>>>>>> have been transferred. So the workers would sleep if they have\n>>>>>> exceeded the\n>>>>>> limit. Hence, the shared state carries a lock to safely update the\n>>>>>> throttling\n>>>>>> value atomically.\n>>>>>>\n>>>>>> Progress Reporting:\n>>>>>> Although I think we should add progress-reporting for parallel backup\n>>>>>> as a\n>>>>>> separate patch. The relevant entries for progress-reporting such as\n>>>>>> ‘backup_total’ and ‘backup_streamed’ would be then added to this\n>>>>>> structure\n>>>>>> as well.\n>>>>>>\n>>>>>>\n>>>>>> Grammar:\n>>>>>> There is a change in the resultset being returned for START_BACKUP\n>>>>>> command;\n>>>>>> unique_backup_id is added. Additionally, JOIN_BACKUP replication\n>>>>>> command is\n>>>>>> added. SEND_FILES has been renamed to SEND_FILE. There are no other\n>>>>>> changes\n>>>>>> to the grammar.\n>>>>>>\n>>>>>> START_BACKUP [LABEL '<label>'] [FAST]\n>>>>>> - returns startptr, tli, backup_label, unique_backup_id\n>>>>>> STOP_BACKUP [NOWAIT]\n>>>>>> - returns startptr, tli, backup_label\n>>>>>> JOIN_BACKUP ‘unique_backup_id’\n>>>>>> - attaches a shared state identified by ‘unique_backup_id’ to a\n>>>>>> backend process.\n>>>>>>\n>>>>>> LIST_TABLESPACES [PROGRESS]\n>>>>>> LIST_FILES [TABLESPACE]\n>>>>>> LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']\n>>>>>> SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\n>>>>>>\n>>>>>>\n>>\n>\n> Hi,\n>\n> rebased and updated to the current master (8128b0c1). v13 is attached.\n>\n> - Fixes the above reported issues.\n>\n\nHi Asif\n\nI have verified the bug fixes, out of 3 bugs 2 are now fixed but the\nfollowing issue is still not fixed.\n\n*A similar case is when DB Server is shut down while the Parallel Backup is\nin progress then the correct error is displayed but then the backup folder\nis not cleaned and leaves a corrupt backup. *\n\n[edb@localhost bin]$\n[edb@localhost bin]$ ./pg_basebackup -v -D /home/edb/Desktop/backup/ -j 8\npg_basebackup: warning: backup manifest is disabled in parallel backup mode\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 0/A0000028 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: created temporary replication slot \"pg_basebackup_16235\"\npg_basebackup: backup worker (0) created\npg_basebackup: backup worker (1) created\npg_basebackup: backup worker (2) created\npg_basebackup: backup worker (3) created\npg_basebackup: backup worker (4) created\npg_basebackup: backup worker (5) created\npg_basebackup: backup worker (6) created\npg_basebackup: backup worker (7) created\npg_basebackup: error: could not read COPY data: server closed the\nconnection unexpectedly\nThis probably means the server terminated abnormally\nbefore or while processing the request.\npg_basebackup: error: could not read COPY data: server closed the\nconnection unexpectedly\nThis probably means the server terminated abnormally\nbefore or while processing the request.\npg_basebackup: removing contents of data directory\n\"/home/edb/Desktop/backup/\"\npg_basebackup: error: could not read COPY data: server closed the\nconnection unexpectedly\nThis probably means the server terminated abnormally\nbefore or while processing the request.\n[edb@localhost bin]$\n[edb@localhost bin]$\n[edb@localhost bin]$\n\n\n\n[edb@localhost bin]$\n[edb@localhost bin]$ ls /home/edb/Desktop/backup\nbase pg_hba.conf pg_logical pg_notify pg_serial\npg_stat pg_subtrans pg_twophase pg_xact postgresql.conf\npg_dynshmem pg_ident.conf pg_multixact pg_replslot pg_snapshots\n pg_stat_tmp pg_tblspc PG_VERSION postgresql.auto.conf\n[edb@localhost bin]$\n[edb@localhost bin]$\n\n\n\nThanks\nKashif zeeshan\n\n\n>\n> - Added progress-reporting support for parallel:\n> For this, 'backup_streamed' is moved to a shared structure (BackupState) as\n> pg_atomic_uint64 variable. The worker processes will keep incrementing this\n> variable.\n>\n> While files are being transferred from server to client. The main process\n> remains\n> in an idle state. So after each increment, the worker process will signal\n> master to\n> update the stats in pg_stat_progress_basebackup view.\n>\n> The 'tablespace_streamed' column is not updated and will remain empty.\n> This is\n> because multiple workers may be copying files from different tablespaces.\n>\n>\n> - Added backup manifest:\n> The backend workers maintain their own manifest file which contains a list\n> of files\n> that are being transferred by the work. Once all backup files are\n> transferred, the\n> workers will create a temp file as\n> ('pg_tempdir/temp_file_prefix_backupid.workerid')\n> to write the content of the manifest file from BufFile. The workers won’t\n> add the\n> header, nor the WAL information in their manifest. These two will be added\n> by the\n> main process while merging all worker manifest files.\n>\n> The main process will read these individual files and concatenate them\n> into a single file\n> which is then sent back to the client.\n>\n> The manifest file is created when the following command is received:\n>\n>> BUILD_MANIFEST 'backupid'\n>\n>\n> This is a new replication command. It is sent when pg_basebackup has\n> copied all the\n> $PGDATA files including WAL files.\n>\n>\n>\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\n-- \nRegards\n====================================\nKashif Zeeshan\nLead Quality Assurance Engineer / Manager\n\nEnterpriseDB Corporation\nThe Enterprise Postgres Company\n\nOn Tue, Apr 14, 2020 at 5:33 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Wed, Apr 8, 2020 at 6:53 PM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:On Tue, Apr 7, 2020 at 9:44 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Hi,Thanks, Kashif and Rajkumar. I have fixed the reported issues.I have added the shared state as previously described. The new grammar changesare as follows:START_BACKUP [LABEL '<label>'] [FAST] [MAX_RATE %d]    - This will generate a unique backupid using pg_strong_random(16) and hex-encoded      it. which is then returned as the result set.    - It will also create a shared state and add it to the hashtable. The hash table size is set      to BACKUP_HASH_SIZE=10, but since hashtable can expand dynamically, I think it's      sufficient initial size. max_wal_senders is not used, because it can be set to quite a       large values.JOIN_BACKUP 'backup_id'    - finds 'backup_id' in hashtable and attaches it to server process.SEND_FILE '(' 'FILE' ')' [NOVERIFY_CHECKSUMS]    - renamed SEND_FILES to SEND_FILE    - removed START_WAL_LOCATION from this because 'startptr' is now accessible through      shared state.There is no change in other commands:STOP_BACKUP [NOWAIT]LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']The current patches (v11) have been rebased to the latest master. The backup manifest is enabledby default, so I have disabled it for parallel backup mode and have generated a warning so thatuser is aware of it and not expect it in the backup.Hi AsifI have verified the bug fixes, one bug is fixed and working now as expected For the verification of the other bug fixes faced following issues, please have a look.1) Following bug fixes mentioned below are generating segmentation fault. Please note for reference I have added a description only as steps were given in previous emails of each bug I tried to verify the fix. Backtrace is also added with each case which points to one bug for both the cases.a) The backup failed with errors \"error: could not connect to server: could not look up local user ID 1000: Too many open files\" when the max_wal_senders was set to 2000. [edb@localhost bin]$ ./pg_basebackup -v -j 1990 -D  /home/edb/Desktop/backup/pg_basebackup: warning: backup manifest is disabled in parallel backup modepg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_9925\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) created….….pg_basebackup: backup worker (1014) createdpg_basebackup: backup worker (1015) createdpg_basebackup: backup worker (1016) createdpg_basebackup: backup worker (1017) createdpg_basebackup: error: could not connect to server: could not look up local user ID 1000: Too many open filesSegmentation fault[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ gdb pg_basebackup /tmp/cores/core.pg_basebackup.13219.localhost.localdomain.1586349551 GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7Copyright (C) 2013 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"and \"show warranty\" for details.This GDB was configured as \"x86_64-redhat-linux-gnu\".For bug reporting instructions, please see:<http://www.gnu.org/software/gdb/bugs/>...Reading symbols from /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.[New LWP 13219][New LWP 13222][Thread debugging using libthread_db enabled]Using host libthread_db library \"/lib64/libthread_db.so.1\".Core was generated by `./pg_basebackup -v -j 1990 -D /home/edb/Desktop/backup/'.Program terminated with signal 11, Segmentation fault.#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:4747\t  if (INVALID_NOT_TERMINATED_TD_P (pd))(gdb) bt#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47#1  0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978#2  0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332#3  0x00007f2226f76a49 in __run_exit_handlers (status=1, listp=0x7f22272f86c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true) at exit.c:77#4  0x00007f2226f76a95 in __GI_exit (status=<optimized out>) at exit.c:99#5  0x0000000000408c54 in create_parallel_workers (backupinfo=0x952ca0) at pg_basebackup.c:2811#6  0x000000000040798f in BaseBackup () at pg_basebackup.c:2211#7  0x0000000000408b4d in main (argc=6, argv=0x7ffe3dabc718) at pg_basebackup.c:2765(gdb) b) When\n executing two backups at the same time, getting FATAL error due to \nmax_wal_senders and instead of exit  Backup got completed.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -j 8 -D  /home/edb/Desktop/backup1/pg_basebackup: warning: backup manifest is disabled in parallel backup modepg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 1/DA000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_17066\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: error: could not connect to server: FATAL:  number of requested standby connections exceeds max_wal_senders (currently 10)Segmentation fault (core dumped)[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ gdb pg_basebackup /tmp/cores/core.pg_basebackup.17041.localhost.localdomain.1586353696 GNU gdb (GDB) Red Hat Enterprise Linux 7.6.1-115.el7Copyright (C) 2013 Free Software Foundation, Inc.License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"and \"show warranty\" for details.This GDB was configured as \"x86_64-redhat-linux-gnu\".For bug reporting instructions, please see:<http://www.gnu.org/software/gdb/bugs/>...Reading symbols from /home/edb/Communtiy_Parallel_backup/postgresql/inst/bin/pg_basebackup...done.[New LWP 17041][New LWP 17067][Thread debugging using libthread_db enabled]Using host libthread_db library \"/lib64/libthread_db.so.1\".Core was generated by `./pg_basebackup -v -j 8 -D /home/edb/Desktop/backup1/'.Program terminated with signal 11, Segmentation fault.#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:4747\t  if (INVALID_NOT_TERMINATED_TD_P (pd))(gdb) bt#0  pthread_join (threadid=0, thread_return=0x0) at pthread_join.c:47#1  0x000000000040904a in cleanup_workers () at pg_basebackup.c:2978#2  0x0000000000403806 in disconnect_atexit () at pg_basebackup.c:332#3  0x00007f051edc1a49 in __run_exit_handlers (status=1, listp=0x7f051f1436c8 <__exit_funcs>, run_list_atexit=run_list_atexit@entry=true) at exit.c:77#4  0x00007f051edc1a95 in __GI_exit (status=<optimized out>) at exit.c:99#5  0x0000000000408c54 in create_parallel_workers (backupinfo=0x1c6dca0) at pg_basebackup.c:2811#6  0x000000000040798f in BaseBackup () at pg_basebackup.c:2211#7  0x0000000000408b4d in main (argc=6, argv=0x7ffdb76a6d68) at pg_basebackup.c:2765(gdb) 2) The following bug is not fixed yetA similar case is when DB Server is shut down while the Parallel Backup is in progress then the correct error\n is displayed but then the backup folder is not cleaned and leaves a \ncorrupt backup. [edb@localhost bin]$ [edb@localhost bin]$ ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -j 8pg_basebackup: warning: backup manifest is disabled in parallel backup modepg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/A0000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_16235\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: backup worker (7) createdpg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: removing contents of data directory \"/home/edb/Desktop/backup/\"pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ ls /home/edb/Desktop/backupbase         pg_hba.conf    pg_logical    pg_notify    pg_serial     pg_stat      pg_subtrans  pg_twophase  pg_xact               postgresql.confpg_dynshmem  pg_ident.conf  pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    PG_VERSION   postgresql.auto.conf[edb@localhost bin]$ [edb@localhost bin]$ ThanksKashif ZeeshanOn Tue, Apr 7, 2020 at 4:03 PM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:On Fri, Apr 3, 2020 at 3:01 PM Kashif Zeeshan <kashif.zeeshan@enterprisedb.com> wrote:Hi AsifWhen a non-existent slot is used with tablespace then correct error is displayed but then the backup folder is not cleaned and leaves a corrupt backup.Steps=======edb@localhost bin]$ [edb@localhost bin]$ mkdir /home/edb/tbl1[edb@localhost bin]$ mkdir /home/edb/tbl_res[edb@localhost bin]$ postgres=#  create tablespace tbl1 location '/home/edb/tbl1';CREATE TABLESPACEpostgres=# postgres=# create table t1 (a int) tablespace tbl1;CREATE TABLEpostgres=# insert into t1 values(100);INSERT 0 1postgres=# insert into t1 values(200);INSERT 0 1postgres=# insert into t1 values(300);INSERT 0 1postgres=# [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -j 2 -D  /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S testpg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2E000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test\" does not existpg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: write-ahead log end point: 0/2E000100pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: error: child thread exited with error 1[edb@localhost bin]$ backup folder not cleaned[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ ls /home/edb/Desktop/backupbackup_label  global        pg_dynshmem  pg_ident.conf  pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    PG_VERSION  pg_xact               postgresql.confbase          pg_commit_ts  pg_hba.conf  pg_logical     pg_notify     pg_serial    pg_stat       pg_subtrans  pg_twophase  pg_wal      postgresql.auto.conf[edb@localhost bin]$ If the same case is executed without the parallel backup patch then the backup folder is cleaned after the error is displayed.[edb@localhost bin]$ ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -T /home/edb/tbl1=/home/edb/tbl_res -S test999pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/2B000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: error: could not send replication command \"START_REPLICATION\": ERROR:  replication slot \"test999\" does not existpg_basebackup: write-ahead log end point: 0/2B000100pg_basebackup: waiting for background process to finish streaming ...pg_basebackup: error: child process exited with exit code 1pg_basebackup: removing data directory \" /home/edb/Desktop/backup\"pg_basebackup: changes to tablespace directories will not be undoneHi AsifA similar case is when DB Server is shut down while the Parallel Backup is in progress then the correct error\n is displayed but then the backup folder is not cleaned and leaves a \ncorrupt backup. I think one bug fix will solve all these cases where clean up is not done when parallel backup is failed.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -j 8pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C1000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_57337\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: backup worker (7) createdpg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.[edb@localhost bin]$ [edb@localhost bin]$ Same case when executed on pg_basebackup without the Parallel backup patch then proper clean up is done.[edb@localhost bin]$ [edb@localhost bin]$  ./pg_basebackup -v -D  /home/edb/Desktop/backup/ pg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/C5000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_5590\"pg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\tThis probably means the server terminated abnormally\tbefore or while processing the request.pg_basebackup: removing contents of data directory \"/home/edb/Desktop/backup/\"[edb@localhost bin]$ ThanksOn Fri, Apr 3, 2020 at 1:46 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Thu, Apr 2, 2020 at 8:45 PM Robert Haas <robertmhaas@gmail.com> wrote:On Thu, Apr 2, 2020 at 11:17 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>> Why would you need to do that? As long as the process where\n>> STOP_BACKUP can do the check, that seems good enough.\n>\n> Yes, but the user will get the error only after the STOP_BACKUP, not while the backup is\n> in progress. So if the backup is a large one, early error detection would be much beneficial.\n> This is the current behavior of non-parallel backup as well.\n\nBecause non-parallel backup does not feature early detection of this\nerror, it is not necessary to make parallel backup do so. Indeed, it\nis undesirable. If you want to fix that problem, do it on a separate\nthread in a separate patch. A patch proposing to make parallel backup\ninconsistent in behavior with non-parallel backup will be rejected, at\nleast if I have anything to say about it.\n\nTBH, fixing this doesn't seem like an urgent problem to me. The\ncurrent situation is not great, but promotions ought to be relatively\ninfrequent, so I'm not sure it's a huge problem in practice. It is\nalso worth considering whether the right fix is to figure out how to\nmake that case actually work, rather than just making it fail quicker.\nI don't currently understand the reason for the prohibition so I can't\nexpress an intelligent opinion on what the right answer is here, but\nit seems like it ought to be investigated before somebody goes and\nbuilds a bunch of infrastructure to make the error more timely.Non-parallel backup already does the early error checking. I only intendedto make parallel behave the same as non-parallel here. So, I agree withyou that the behavior of parallel backup should be consistent with thenon-parallel one.  Please see the code snippet below from basebackup.c:sendDir()/*\n * Check if the postmaster has signaled us to exit, and abort with an\n * error in that case. The error handler further up will call\n * do_pg_abort_backup() for us. Also check that if the backup was\n * started while still in recovery, the server wasn't promoted.\n * do_pg_stop_backup() will check that too, but it's better to stop\n * the backup early than continue to the end and fail there.\n */\nCHECK_FOR_INTERRUPTS();\nif (RecoveryInProgress() != backup_started_in_recovery)\n ereport(ERROR,\n (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),\n errmsg(\"the standby was promoted during online backup\"),\n errhint(\"This means that the backup being taken is corrupt \"\n \"and should not be used. \"\n \"Try taking another online backup.\"))); \n\n> Okay, then I will add the shared state. And since we are adding the shared state, we can use\n> that for throttling, progress-reporting and standby early error checking.\n\nPlease propose a grammar here for all the new replication commands you\nplan to add before going and implement everything. That will make it\neasier to hash out the design without forcing you to keep changing the\ncode. Your design should include a sketch of how several sets of\ncoordinating backends taking several concurrent parallel backups will\nend up with one shared state per parallel backup.\n\n> There are two possible options:\n>\n> (1) Server may generate a unique ID i.e. BackupID=<unique_string> OR\n> (2) (Preferred Option) Use the WAL start location as the BackupID.\n>\n> This BackupID should be given back as a response to start backup command. All client workers\n> must append this ID to all parallel backup replication commands. So that we can use this identifier\n> to search for that particular backup. Does that sound good?\n\nUsing the WAL start location as the backup ID seems like it might be\nproblematic -- could a single checkpoint not end up as the start\nlocation for multiple backups started at the same time? Whether that's\npossible now or not, it seems unwise to hard-wire that assumption into\nthe wire protocol.\n\nI was thinking that perhaps the client should generate a unique backup\nID, e.g. leader does:\n\nSTART_BACKUP unique_backup_id [options]...\n\nAnd then others do:\n\nJOIN_BACKUP unique_backup_id\n\nMy thought is that you will have a number of shared memory structure\nequal to max_wal_senders, each one large enough to hold the shared\nstate for one backup. The shared state will include\nchar[NAMEDATALEN-or-something] which will be used to hold the backup\nID. START_BACKUP would allocate one and copy the name into it;\nJOIN_BACKUP would search for one by name.\n\nIf you want to generate the name on the server side, then I suppose\nSTART_BACKUP would return a result set that includes the backup ID,\nand clients would have to specify that same backup ID when invoking\nJOIN_BACKUP. The rest would stay the same. I am not sure which way is\nbetter. Either way, the backup ID should be something long and hard to\nguess, not e.g. the leader processes' PID. I think we should generate\nit using pg_strong_random, say 8 or 16 bytes, and then hex-encode the\nresult to get a string. That way there's almost no risk of two backup\nIDs colliding accidentally, and even if we somehow had a malicious\nuser trying to screw up somebody else's parallel backup by choosing a\ncolliding backup ID, it would be pretty hard to have any success. A\nuser with enough access to do that sort of thing can probably cause a\nlot worse problems anyway, but it seems pretty easy to guard against\nintentional collisions robustly here, so I think we should.\nOkay so If we are to add another replication command ‘JOIN_BACKUP unique_backup_id’to make workers find the relevant shared state. There won't be any need for changingthe grammar for any other command. The START_BACKUP can return the unique_backup_idin the result set.I am thinking of the following struct for shared state:typedef struct\n{\n char backupid[NAMEDATALEN];\n XLogRecPtr startptr;\n\n slock_t lock;\n int64 throttling_counter;\n bool backup_started_in_recovery;\n} BackupSharedState;The shared state structure entries would be maintained by a shared hash table.There will be one structure per parallel backup. Since a single parallel backupcan engage more than one wal sender, so I think max_wal_senders might be a littletoo much; perhaps max_wal_senders/2 since there will be at least 2 connectionsper parallel backup? Alternatively, we can set a new GUC that defines the maximumnumber of for concurrent parallel backups i.e. ‘max_concurent_backups_allowed = 10’ perhaps, or we can make it user-configurable.The key would be “backupid=hex_encode(pg_random_strong(16))”Checking for Standby Promotion:At the START_BACKUP command, we initialize BackupSharedState.backup_started_in_recovery and keep checking it whenever send_file () is called to send a new file.Throttling:BackupSharedState.throttling_counter - The throttling logic remains the sameas for non-parallel backup with the exception that multiple threads will now beupdating it. So in parallel backup, this will represent the overall bytes thathave been transferred. So the workers would sleep if they have exceeded thelimit. Hence, the shared state carries a lock to safely update the throttlingvalue atomically. Progress Reporting:Although I think we should add progress-reporting for parallel backup as aseparate patch. The relevant entries for progress-reporting such as ‘backup_total’ and ‘backup_streamed’ would be then added to this structureas well.  Grammar:There is a change in the resultset being returned for START_BACKUP command; unique_backup_id is added. Additionally, JOIN_BACKUP replication command isadded. SEND_FILES has been renamed to SEND_FILE. There are no other changesto the grammar.START_BACKUP [LABEL '<label>'] [FAST]  - returns startptr, tli, backup_label, unique_backup_idSTOP_BACKUP [NOWAIT]  - returns startptr, tli, backup_labelJOIN_BACKUP ‘unique_backup_id’  - attaches a shared state identified by ‘unique_backup_id’ to a backend process. LIST_TABLESPACES [PROGRESS]LIST_FILES [TABLESPACE]LIST_WAL_FILES [START_WAL_LOCATION 'X/X'] [END_WAL_LOCATION 'X/X']SEND_FILE '(' FILE ')' [NOVERIFY_CHECKSUMS]\nHi,rebased and updated to the current master (8128b0c1). v13 is attached.- Fixes the above reported issues.Hi AsifI have verified the bug fixes, out of 3 bugs 2 are now fixed but the following issue is still not fixed.A similar case is when DB Server is shut down while the Parallel Backup is in progress then the correct error is displayed but then the backup folder is not cleaned and leaves a corrupt backup. [edb@localhost bin]$ [edb@localhost bin]$ ./pg_basebackup -v -D  /home/edb/Desktop/backup/ -j 8pg_basebackup: warning: backup manifest is disabled in parallel backup modepg_basebackup: initiating base backup, waiting for checkpoint to completepg_basebackup: checkpoint completedpg_basebackup: write-ahead log start point: 0/A0000028 on timeline 1pg_basebackup: starting background WAL receiverpg_basebackup: created temporary replication slot \"pg_basebackup_16235\"pg_basebackup: backup worker (0) createdpg_basebackup: backup worker (1) createdpg_basebackup: backup worker (2) createdpg_basebackup: backup worker (3) createdpg_basebackup: backup worker (4) createdpg_basebackup: backup worker (5) createdpg_basebackup: backup worker (6) createdpg_basebackup: backup worker (7) createdpg_basebackup: error: could not read COPY data: server closed the connection unexpectedlyThis probably means the server terminated abnormallybefore or while processing the request.pg_basebackup: error: could not read COPY data: server closed the connection unexpectedlyThis probably means the server terminated abnormallybefore or while processing the request.pg_basebackup: removing contents of data directory \"/home/edb/Desktop/backup/\"pg_basebackup: error: could not read COPY data: server closed the connection unexpectedlyThis probably means the server terminated abnormallybefore or while processing the request.[edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ [edb@localhost bin]$ ls /home/edb/Desktop/backupbase         pg_hba.conf    pg_logical    pg_notify    pg_serial     pg_stat      pg_subtrans  pg_twophase  pg_xact               postgresql.confpg_dynshmem  pg_ident.conf  pg_multixact  pg_replslot  pg_snapshots  pg_stat_tmp  pg_tblspc    PG_VERSION   postgresql.auto.conf[edb@localhost bin]$ [edb@localhost bin]$ ThanksKashif zeeshan - Added progress-reporting support for parallel:For this, 'backup_streamed' is moved to a shared structure (BackupState) aspg_atomic_uint64 variable. The worker processes will keep incrementing thisvariable.While files are being transferred from server to client. The main process remainsin an idle state. So after each increment, the worker process will signal master toupdate the stats in pg_stat_progress_basebackup view.The 'tablespace_streamed' column is not updated and will remain empty. This isbecause multiple workers may be copying files from different tablespaces.- Added backup manifest:The backend workers maintain their own manifest file which contains a list of filesthat are being transferred by the work. Once all backup files are transferred, theworkers will create a temp file as ('pg_tempdir/temp_file_prefix_backupid.workerid')to write the content of the manifest file from BufFile. The workers won’t add theheader, nor the WAL information in their manifest. These two will be added by themain process while merging all worker manifest files.The main process will read these individual files and concatenate them into a single filewhich is then sent back to the client. The manifest file is created when the following command is received:    BUILD_MANIFEST 'backupid'This is a new replication command. It is sent when pg_basebackup has copied all the$PGDATA files including WAL files.--Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n-- Regards====================================Kashif ZeeshanLead Quality Assurance Engineer / ManagerEnterpriseDB CorporationThe Enterprise Postgres Company", "msg_date": "Fri, 17 Apr 2020 12:08:14 +0500", "msg_from": "Kashif Zeeshan <kashif.zeeshan@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Apr 14, 2020 at 8:07 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n> I forgot to make a check for no-manifest. Fixed. Attached is the updated\n> patch.\n>\n>\nHave we done any performance testing with this patch to see the benefits?\nIf so, can you point me to the results? If not, then can we perform some\ntests on large backups to see the benefits of this patch/idea?\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\nOn Tue, Apr 14, 2020 at 8:07 PM Asif Rehman <asifr.rehman@gmail.com> wrote:I forgot to make a check for no-manifest. Fixed. Attached is the updated patch.Have we done any performance testing with this patch to see the benefits? If so, can you point me to the results? If not, then can we perform some tests on large backups to see the benefits of this patch/idea?-- With Regards,Amit Kapila.EnterpriseDB: http://www.enterprisedb.com", "msg_date": "Tue, 21 Apr 2020 09:57:31 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi,\n\nI did some tests a while back, and here are the results. The tests were\ndone to simulate\na live database environment using pgbench.\n\nmachine configuration used for this test:\nInstance Type: t2.xlarge\nVolume Type : io1\nMemory (MiB) : 16384\nvCPU # : 4\nArchitecture : X86_64\nIOP : 16000\nDatabase Size (GB) : 102\n\nThe setup consist of 3 machines.\n- one for database instances\n- one for pg_basebackup client and\n- one for pgbench with some parallel workers, simulating SELECT loads.\n\n basebackup | 4 workers | 8 Workers | 16\nworkers\nBackup Duration(Min): 69.25 | 20.44 | 19.86 | 20.15\n(pgbench running with 50 parallel client simulating SELECT load)\n\nBackup Duration(Min): 154.75 | 49.28 | 45.27 | 20.35\n(pgbench running with 100 parallel client simulating SELECT load)\n\n\n\nOn Tue, Apr 21, 2020 at 9:27 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> On Tue, Apr 14, 2020 at 8:07 PM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n>\n>>\n>> I forgot to make a check for no-manifest. Fixed. Attached is the updated\n>> patch.\n>>\n>>\n> Have we done any performance testing with this patch to see the benefits?\n> If so, can you point me to the results? If not, then can we perform some\n> tests on large backups to see the benefits of this patch/idea?\n>\n> --\n> With Regards,\n> Amit Kapila.\n> EnterpriseDB: http://www.enterprisedb.com\n>\n\n\n-- \n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nHi,I did some tests a while back, and here are the results. The tests were done to simulatea live database environment using pgbench.machine configuration used for this test:Instance Type:    t2.xlargeVolume Type  :    io1Memory (MiB) :    16384vCPU #           :    4Architecture    :    X86_64IOP                 :    16000Database Size (GB) :    102The setup consist of 3 machines.- one for database instances- one for pg_basebackup client and- one for pgbench with some parallel workers, simulating SELECT loads.                                   basebackup | 4 workers | 8 Workers  | 16 workersBackup Duration(Min):       69.25    |  20.44      | 19.86          | 20.15 (pgbench running with 50 parallel client simulating SELECT load)Backup Duration(Min):       154.75   |  49.28     | 45.27         | 20.35(pgbench running with 100 parallel client simulating SELECT load)On Tue, Apr 21, 2020 at 9:27 AM Amit Kapila <amit.kapila16@gmail.com> wrote:On Tue, Apr 14, 2020 at 8:07 PM Asif Rehman <asifr.rehman@gmail.com> wrote:I forgot to make a check for no-manifest. Fixed. Attached is the updated patch.Have we done any performance testing with this patch to see the benefits? If so, can you point me to the results? If not, then can we perform some tests on large backups to see the benefits of this patch/idea?-- With Regards,Amit Kapila.EnterpriseDB: http://www.enterprisedb.com\n-- --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Tue, 21 Apr 2020 12:29:47 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif,\n\nOn Tue, Apr 21, 2020 at 1:00 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n> Hi,\n>\n> I did some tests a while back, and here are the results. The tests were\n> done to simulate\n> a live database environment using pgbench.\n>\n> machine configuration used for this test:\n> Instance Type: t2.xlarge\n> Volume Type : io1\n> Memory (MiB) : 16384\n> vCPU # : 4\n> Architecture : X86_64\n> IOP : 16000\n> Database Size (GB) : 102\n>\n> The setup consist of 3 machines.\n> - one for database instances\n> - one for pg_basebackup client and\n> - one for pgbench with some parallel workers, simulating SELECT loads.\n>\n> basebackup | 4 workers | 8 Workers |\n> 16 workers\n> Backup Duration(Min): 69.25 | 20.44 | 19.86 |\n> 20.15\n> (pgbench running with 50 parallel client simulating SELECT load)\n>\n\n\nWell that looks a bit strange. All 4, 8 and 16 workers backup configurations\nseem to have taken the same time. Is it because the machine CPUs are\nonly 4? In that case did you try to run with 2-workers and compare that\nwith 4-workers time?\n\nAlso, just to clarify and be sure - was there anything else running on any\nof\nthese 3 machines while the backup was in progress.\n\nRegards,\nJeevan Ladhe\n\n\n> Backup Duration(Min): 154.75 | 49.28 | 45.27 | 20.35\n> (pgbench running with 100 parallel client simulating SELECT load)\n>\n>\n>\n> On Tue, Apr 21, 2020 at 9:27 AM Amit Kapila <amit.kapila16@gmail.com>\n> wrote:\n>\n>> On Tue, Apr 14, 2020 at 8:07 PM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>>\n>>>\n>>> I forgot to make a check for no-manifest. Fixed. Attached is the updated\n>>> patch.\n>>>\n>>>\n>> Have we done any performance testing with this patch to see the benefits?\n>> If so, can you point me to the results? If not, then can we perform some\n>> tests on large backups to see the benefits of this patch/idea?\n>>\n>> --\n>> With Regards,\n>> Amit Kapila.\n>> EnterpriseDB: http://www.enterprisedb.com\n>>\n>\n>\n> --\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\nHi Asif,On Tue, Apr 21, 2020 at 1:00 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Hi,I did some tests a while back, and here are the results. The tests were done to simulatea live database environment using pgbench.machine configuration used for this test:Instance Type:    t2.xlargeVolume Type  :    io1Memory (MiB) :    16384vCPU #           :    4Architecture    :    X86_64IOP                 :    16000Database Size (GB) :    102The setup consist of 3 machines.- one for database instances- one for pg_basebackup client and- one for pgbench with some parallel workers, simulating SELECT loads.                                   basebackup | 4 workers | 8 Workers  | 16 workersBackup Duration(Min):       69.25    |  20.44      | 19.86          | 20.15 (pgbench running with 50 parallel client simulating SELECT load)Well that looks a bit strange. All 4, 8 and 16 workers backup configurationsseem to have taken the same time. Is it because the machine CPUs areonly 4? In that case did you try to run with 2-workers and compare thatwith 4-workers time?Also, just to clarify and be sure - was there anything else running on any ofthese 3 machines while the backup was in progress.Regards,Jeevan LadheBackup Duration(Min):       154.75   |  49.28     | 45.27         | 20.35(pgbench running with 100 parallel client simulating SELECT load)On Tue, Apr 21, 2020 at 9:27 AM Amit Kapila <amit.kapila16@gmail.com> wrote:On Tue, Apr 14, 2020 at 8:07 PM Asif Rehman <asifr.rehman@gmail.com> wrote:I forgot to make a check for no-manifest. Fixed. Attached is the updated patch.Have we done any performance testing with this patch to see the benefits? If so, can you point me to the results? If not, then can we perform some tests on large backups to see the benefits of this patch/idea?-- With Regards,Amit Kapila.EnterpriseDB: http://www.enterprisedb.com\n-- --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Tue, 21 Apr 2020 15:05:38 +0530", "msg_from": "Jeevan Ladhe <jeevan.ladhe@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, 21 Apr 2020 at 2:36 PM, Jeevan Ladhe <jeevan.ladhe@enterprisedb.com>\nwrote:\n\n> Hi Asif,\n>\n> On Tue, Apr 21, 2020 at 1:00 PM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n>\n>> Hi,\n>>\n>> I did some tests a while back, and here are the results. The tests were\n>> done to simulate\n>> a live database environment using pgbench.\n>>\n>> machine configuration used for this test:\n>> Instance Type: t2.xlarge\n>> Volume Type : io1\n>> Memory (MiB) : 16384\n>> vCPU # : 4\n>> Architecture : X86_64\n>> IOP : 16000\n>> Database Size (GB) : 102\n>>\n>> The setup consist of 3 machines.\n>> - one for database instances\n>> - one for pg_basebackup client and\n>> - one for pgbench with some parallel workers, simulating SELECT loads.\n>>\n>> basebackup | 4 workers | 8 Workers |\n>> 16 workers\n>> Backup Duration(Min): 69.25 | 20.44 | 19.86 |\n>> 20.15\n>> (pgbench running with 50 parallel client simulating SELECT load)\n>>\n>\n>\n> Well that looks a bit strange. All 4, 8 and 16 workers backup\n> configurations\n> seem to have taken the same time. Is it because the machine CPUs are\n> only 4? In that case did you try to run with 2-workers and compare that\n> with 4-workers time?\n>\n> Also, just to clarify and be sure - was there anything else running on any\n> of\n> these 3 machines while the backup was in progress.\n>\n\nThe tests were performed only for 4, 8 and 16 at the time and there was\nnothing else running on any of the machines.\n\n\n> Regards,\n> Jeevan Ladhe\n>\n>\n>> Backup Duration(Min): 154.75 | 49.28 | 45.27 | 20.35\n>> (pgbench running with 100 parallel client simulating SELECT load)\n>>\n>>\n>>\n>> On Tue, Apr 21, 2020 at 9:27 AM Amit Kapila <amit.kapila16@gmail.com>\n>> wrote:\n>>\n>>> On Tue, Apr 14, 2020 at 8:07 PM Asif Rehman <asifr.rehman@gmail.com>\n>>> wrote:\n>>>\n>>>>\n>>>> I forgot to make a check for no-manifest. Fixed. Attached is the\n>>>> updated patch.\n>>>>\n>>>>\n>>> Have we done any performance testing with this patch to see the\n>>> benefits? If so, can you point me to the results? If not, then can we\n>>> perform some tests on large backups to see the benefits of this patch/idea?\n>>>\n>>> --\n>>> With Regards,\n>>> Amit Kapila.\n>>> EnterpriseDB: http://www.enterprisedb.com\n>>>\n>>\n>>\n>> --\n>> --\n>> Asif Rehman\n>> Highgo Software (Canada/China/Pakistan)\n>> URL : www.highgo.ca\n>>\n>> --\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nOn Tue, 21 Apr 2020 at 2:36 PM, Jeevan Ladhe <jeevan.ladhe@enterprisedb.com> wrote:Hi Asif,On Tue, Apr 21, 2020 at 1:00 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Hi,I did some tests a while back, and here are the results. The tests were done to simulatea live database environment using pgbench.machine configuration used for this test:Instance Type:    t2.xlargeVolume Type  :    io1Memory (MiB) :    16384vCPU #           :    4Architecture    :    X86_64IOP                 :    16000Database Size (GB) :    102The setup consist of 3 machines.- one for database instances- one for pg_basebackup client and- one for pgbench with some parallel workers, simulating SELECT loads.                                   basebackup | 4 workers | 8 Workers  | 16 workersBackup Duration(Min):       69.25    |  20.44      | 19.86          | 20.15 (pgbench running with 50 parallel client simulating SELECT load)Well that looks a bit strange. All 4, 8 and 16 workers backup configurationsseem to have taken the same time. Is it because the machine CPUs areonly 4? In that case did you try to run with 2-workers and compare thatwith 4-workers time?Also, just to clarify and be sure - was there anything else running on any ofthese 3 machines while the backup was in progress.The tests were performed only for 4, 8 and 16 at the time and there was nothing else running on any of the machines.Regards,Jeevan LadheBackup Duration(Min):       154.75   |  49.28     | 45.27         | 20.35(pgbench running with 100 parallel client simulating SELECT load)On Tue, Apr 21, 2020 at 9:27 AM Amit Kapila <amit.kapila16@gmail.com> wrote:On Tue, Apr 14, 2020 at 8:07 PM Asif Rehman <asifr.rehman@gmail.com> wrote:I forgot to make a check for no-manifest. Fixed. Attached is the updated patch.Have we done any performance testing with this patch to see the benefits? If so, can you point me to the results? If not, then can we perform some tests on large backups to see the benefits of this patch/idea?-- With Regards,Amit Kapila.EnterpriseDB: http://www.enterprisedb.com\n-- --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca \n\n-- --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Tue, 21 Apr 2020 15:16:33 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Apr 21, 2020 at 1:00 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>\n> I did some tests a while back, and here are the results. The tests were done to simulate\n> a live database environment using pgbench.\n>\n> machine configuration used for this test:\n> Instance Type: t2.xlarge\n> Volume Type : io1\n> Memory (MiB) : 16384\n> vCPU # : 4\n> Architecture : X86_64\n> IOP : 16000\n> Database Size (GB) : 102\n>\n> The setup consist of 3 machines.\n> - one for database instances\n> - one for pg_basebackup client and\n> - one for pgbench with some parallel workers, simulating SELECT loads.\n>\n> basebackup | 4 workers | 8 Workers | 16 workers\n> Backup Duration(Min): 69.25 | 20.44 | 19.86 | 20.15\n> (pgbench running with 50 parallel client simulating SELECT load)\n>\n> Backup Duration(Min): 154.75 | 49.28 | 45.27 | 20.35\n> (pgbench running with 100 parallel client simulating SELECT load)\n>\n\nThanks for sharing the results, these show nice speedup! However, I\nthink we should try to find what exactly causes this speed up. If you\nsee the recent discussion on another thread related to this topic,\nAndres, pointed out that he doesn't think that we can gain much by\nhaving multiple connections[1]. It might be due to some internal\nlimitations (like small buffers) [2] due to which we are seeing these\nspeedups. It might help if you can share the perf reports of the\nserver-side and pg_basebackup side. We don't need pgbench type\nworkload to see what caused speed up.\n\n[1] - https://www.postgresql.org/message-id/20200420201922.55ab7ovg6535suyz%40alap3.anarazel.de\n[2] - https://www.postgresql.org/message-id/20200421064420.z7eattzqbunbutz3%40alap3.anarazel.de\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 21 Apr 2020 17:18:17 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Apr 21, 2020 at 5:18 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Tue, Apr 21, 2020 at 1:00 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> >\n> > I did some tests a while back, and here are the results. The tests were done to simulate\n> > a live database environment using pgbench.\n> >\n> > machine configuration used for this test:\n> > Instance Type: t2.xlarge\n> > Volume Type : io1\n> > Memory (MiB) : 16384\n> > vCPU # : 4\n> > Architecture : X86_64\n> > IOP : 16000\n> > Database Size (GB) : 102\n> >\n> > The setup consist of 3 machines.\n> > - one for database instances\n> > - one for pg_basebackup client and\n> > - one for pgbench with some parallel workers, simulating SELECT loads.\n> >\n> > basebackup | 4 workers | 8 Workers | 16 workers\n> > Backup Duration(Min): 69.25 | 20.44 | 19.86 | 20.15\n> > (pgbench running with 50 parallel client simulating SELECT load)\n> >\n> > Backup Duration(Min): 154.75 | 49.28 | 45.27 | 20.35\n> > (pgbench running with 100 parallel client simulating SELECT load)\n> >\n>\n> Thanks for sharing the results, these show nice speedup! However, I\n> think we should try to find what exactly causes this speed up. If you\n> see the recent discussion on another thread related to this topic,\n> Andres, pointed out that he doesn't think that we can gain much by\n> having multiple connections[1]. It might be due to some internal\n> limitations (like small buffers) [2] due to which we are seeing these\n> speedups. It might help if you can share the perf reports of the\n> server-side and pg_basebackup side.\n>\n\nJust to be clear, we need perf reports both with and without patch-set.\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 21 Apr 2020 17:19:45 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Apr 21, 2020 at 4:50 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> On Tue, Apr 21, 2020 at 5:18 PM Amit Kapila <amit.kapila16@gmail.com>\n> wrote:\n> >\n> > On Tue, Apr 21, 2020 at 1:00 PM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n> > >\n> > > I did some tests a while back, and here are the results. The tests\n> were done to simulate\n> > > a live database environment using pgbench.\n> > >\n> > > machine configuration used for this test:\n> > > Instance Type: t2.xlarge\n> > > Volume Type : io1\n> > > Memory (MiB) : 16384\n> > > vCPU # : 4\n> > > Architecture : X86_64\n> > > IOP : 16000\n> > > Database Size (GB) : 102\n> > >\n> > > The setup consist of 3 machines.\n> > > - one for database instances\n> > > - one for pg_basebackup client and\n> > > - one for pgbench with some parallel workers, simulating SELECT loads.\n> > >\n> > > basebackup | 4 workers | 8 Workers\n> | 16 workers\n> > > Backup Duration(Min): 69.25 | 20.44 | 19.86 |\n> 20.15\n> > > (pgbench running with 50 parallel client simulating SELECT load)\n> > >\n> > > Backup Duration(Min): 154.75 | 49.28 | 45.27 |\n> 20.35\n> > > (pgbench running with 100 parallel client simulating SELECT load)\n> > >\n> >\n> > Thanks for sharing the results, these show nice speedup! However, I\n> > think we should try to find what exactly causes this speed up. If you\n> > see the recent discussion on another thread related to this topic,\n> > Andres, pointed out that he doesn't think that we can gain much by\n> > having multiple connections[1]. It might be due to some internal\n> > limitations (like small buffers) [2] due to which we are seeing these\n> > speedups. It might help if you can share the perf reports of the\n> > server-side and pg_basebackup side.\n> >\n>\n> Just to be clear, we need perf reports both with and without patch-set.\n>\n\nThese tests were done a while back, I think it would be good to run the\nbenchmark again with the latest patches of parallel backup and share the\nresults and perf reports.\n\n>\n> --\n> With Regards,\n> Amit Kapila.\n> EnterpriseDB: http://www.enterprisedb.com\n>\n>\n>\n\n-- \nHighgo Software (Canada/China/Pakistan)\nURL : http://www.highgo.ca\nADDR: 10318 WHALLEY BLVD, Surrey, BC\nEMAIL: mailto: ahsan.hadi@highgo.ca\n\nOn Tue, Apr 21, 2020 at 4:50 PM Amit Kapila <amit.kapila16@gmail.com> wrote:On Tue, Apr 21, 2020 at 5:18 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Tue, Apr 21, 2020 at 1:00 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> >\n> > I did some tests a while back, and here are the results. The tests were done to simulate\n> > a live database environment using pgbench.\n> >\n> > machine configuration used for this test:\n> > Instance Type:    t2.xlarge\n> > Volume Type  :    io1\n> > Memory (MiB) :    16384\n> > vCPU #           :    4\n> > Architecture    :    X86_64\n> > IOP                 :    16000\n> > Database Size (GB) :    102\n> >\n> > The setup consist of 3 machines.\n> > - one for database instances\n> > - one for pg_basebackup client and\n> > - one for pgbench with some parallel workers, simulating SELECT loads.\n> >\n> >                                    basebackup | 4 workers | 8 Workers  | 16 workers\n> > Backup Duration(Min):       69.25    |  20.44      | 19.86          | 20.15\n> > (pgbench running with 50 parallel client simulating SELECT load)\n> >\n> > Backup Duration(Min):       154.75   |  49.28     | 45.27         | 20.35\n> > (pgbench running with 100 parallel client simulating SELECT load)\n> >\n>\n> Thanks for sharing the results, these show nice speedup!  However, I\n> think we should try to find what exactly causes this speed up.  If you\n> see the recent discussion on another thread related to this topic,\n> Andres, pointed out that he doesn't think that we can gain much by\n> having multiple connections[1].  It might be due to some internal\n> limitations (like small buffers) [2] due to which we are seeing these\n> speedups.  It might help if you can share the perf reports of the\n> server-side and pg_basebackup side.\n>\n\nJust to be clear, we need perf reports both with and without patch-set.These tests were done a while back, I think it would be good to run the benchmark again with the latest patches of parallel backup and share the results and perf reports.\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n-- Highgo Software (Canada/China/Pakistan)URL : http://www.highgo.caADDR: 10318 WHALLEY BLVD, Surrey, BCEMAIL: mailto: ahsan.hadi@highgo.ca", "msg_date": "Tue, 21 Apr 2020 16:56:16 +0500", "msg_from": "Ahsan Hadi <ahsan.hadi@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Tue, Apr 21, 2020 at 5:26 PM Ahsan Hadi <ahsan.hadi@gmail.com> wrote:\n>\n> On Tue, Apr 21, 2020 at 4:50 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>\n>> On Tue, Apr 21, 2020 at 5:18 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>> >\n>> > On Tue, Apr 21, 2020 at 1:00 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>> > >\n>> > > I did some tests a while back, and here are the results. The tests were done to simulate\n>> > > a live database environment using pgbench.\n>> > >\n>> > > machine configuration used for this test:\n>> > > Instance Type: t2.xlarge\n>> > > Volume Type : io1\n>> > > Memory (MiB) : 16384\n>> > > vCPU # : 4\n>> > > Architecture : X86_64\n>> > > IOP : 16000\n>> > > Database Size (GB) : 102\n>> > >\n>> > > The setup consist of 3 machines.\n>> > > - one for database instances\n>> > > - one for pg_basebackup client and\n>> > > - one for pgbench with some parallel workers, simulating SELECT loads.\n>> > >\n>> > > basebackup | 4 workers | 8 Workers | 16 workers\n>> > > Backup Duration(Min): 69.25 | 20.44 | 19.86 | 20.15\n>> > > (pgbench running with 50 parallel client simulating SELECT load)\n>> > >\n>> > > Backup Duration(Min): 154.75 | 49.28 | 45.27 | 20.35\n>> > > (pgbench running with 100 parallel client simulating SELECT load)\n>> > >\n>> >\n>> > Thanks for sharing the results, these show nice speedup! However, I\n>> > think we should try to find what exactly causes this speed up. If you\n>> > see the recent discussion on another thread related to this topic,\n>> > Andres, pointed out that he doesn't think that we can gain much by\n>> > having multiple connections[1]. It might be due to some internal\n>> > limitations (like small buffers) [2] due to which we are seeing these\n>> > speedups. It might help if you can share the perf reports of the\n>> > server-side and pg_basebackup side.\n>> >\n>>\n>> Just to be clear, we need perf reports both with and without patch-set.\n>\n>\n> These tests were done a while back, I think it would be good to run the benchmark again with the latest patches of parallel backup and share the results and perf reports.\n>\n\nSounds good. I think we should also try to run the test with 1 worker\nas well. The reason it will be good to see the results with 1 worker\nis that we can know if the technique to send file by file as is done\nin this patch is better or worse than the current HEAD code. So, it\nwill be good to see the results of an unpatched code, 1 worker, 2\nworkers, 4 workers, etc.\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 21 Apr 2020 19:42:37 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Asif,\r\n\r\nI am reviewing your recent patch and found the patch is not applicable on latest master. \r\n\r\nCould you please resolve the conflicts and update a new patch?\r\n\r\nThanks,\r\nDipesh\r\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Wed, 22 Apr 2020 11:07:25 +0000", "msg_from": "Dipesh Pandit <dipesh.pandit@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi Dipesh,\n\nThe rebased and updated patch is attached. Its rebased to (9f2c4ede).\n\n\n> +typedef struct\n> +{\n> ...\n> +} BackupFile;\n> +\n> +typedef struct\n> +{\n> ...\n> +} BackupState;\n>\n> These structures need comments.\n>\nDone.\n\n\n>\n> +list_wal_files_opt_list:\n> + SCONST SCONST\n> {\n> - $$ = makeDefElem(\"manifest_checksums\",\n> -\n> (Node *)makeString($2), -1);\n> + $$ = list_make2(\n> + makeDefElem(\"start_wal_location\",\n> + (Node *)makeString($2),\n> -1),\n> + makeDefElem(\"end_wal_location\",\n> + (Node *)makeString($2),\n> -1));\n> +\n> }\n>\n> This seems like an unnecessarily complicated parse representation. The\n> DefElems seem to be completely unnecessary here.\n>\n\nThe startptr and endptr are now in a shared state. so this command does not\nneed to have these two options now. So I have removed this rule entirely.\n\n\n> @@ -998,7 +1110,37 @@ SendBaseBackup(BaseBackupCmd *cmd)\n> set_ps_display(activitymsg);\n> }\n>\n> - perform_base_backup(&opt);\n> + switch (cmd->cmdtag)\n>\n> So the design here is that SendBaseBackup() is now going to do a bunch\n> of things that are NOT sending a base backup? With no updates to the\n> comments of that function and no change to the process title it sets?\n>\n\nOkay. I have renamed the function and have updated the comments.\n\n\n>\n> - return (manifest->buffile != NULL);\n> + return (manifest && manifest->buffile != NULL);\n>\n> Heck no. It appears that you didn't even bother reading the function\n> header comment.\n>\n\nOkay, I forgot to remove this check. In the backup manifest patch,\nmanifest_info\nobject is always available. Anyways I have removed this check for 003 patch\nas well.\n\n\n>\n> + * Send a single resultset containing XLogRecPtr record (in text format)\n> + * TimelineID and backup label.\n> */\n> static void\n> -SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli)\n> +SendXlogRecPtrResult(XLogRecPtr ptr, TimeLineID tli,\n> + StringInfo label, char *backupid)\n>\n> This just casually breaks wire protocol compatibility, which seems\n> completely unacceptable.\n>\n\nNon-parallal backup returns startptr and tli in the result set. The\nSTART_BACKUP\nreturns startptr, tli, backup label and backupid. So I had extended this\nresult set.\n\nI have removed the changes from SendXlogRecPtrResult and have added another\nfunction just for returning the result set for parallel backup.\n\n\n>\n> + if (strlen(opt->tablespace) > 0)\n> + sendTablespace(opt->tablespace, NULL, true, NULL, &files);\n> + else\n> + sendDir(\".\", 1, true, NIL, true, NULL, NULL, &files);\n> +\n> + SendFilesHeader(files);\n>\n> So I guess the idea here is that we buffer the entire list of files in\n> memory, regardless of size, and then we send it out afterwards. That\n> doesn't seem like a good idea. The list of files might be very large.\n> We probably need some code refactoring here rather than just piling\n> more and more different responsibilities onto sendTablespace() and\n> sendDir().\n>\n\nI don't foresee memory to be a challenge here. Assuming a database\ncontaining 10240\nrelation files (that max reach to 10 TB of size), the list will occupy\napproximately 102MB\nof space in memory. This obviously can be reduced, but it doesn’t seem too\nbad either.\nOne way of doing it is by fetching a smaller set of files and clients can\nresult in the next\nset if the current one is processed; perhaps fetch initially per table\nspace and request for\nnext one once the current one is done with.\n\nCurrently, basebackup only does compression on the client-side. So, I\nsuggest we stick with\nthe existing behavior. On the other thread, you have mentioned that the\nbackend should send\nthe tarballs and that the server should decide which files per tarball. I\nbelieve the current\ndesign can accommodate that easily if it's the client deciding the files\nper tarball. The current\ndesign can also accommodate server-side compression and encryption with\nminimal changes.\nIs there a point I’m overlooking here?\n\n\n\n>\n> + if (state->parallel_mode)\n> + SpinLockAcquire(&state->lock);\n> +\n> + state->throttling_counter += increment;\n> +\n> + if (state->parallel_mode)\n> + SpinLockRelease(&state->lock);\n>\n> I don't like this much. It seems to me that we would do better to use\n> atomics here all the time, instead of conditional spinlocks.\n>\n\nOkay have added throttling_counter as atomic. however a lock is still\nrequired\nfor throttling_counter%=throttling_sample.\n\n\n\n\n>\n> +static void\n> +send_file(basebackup_options *opt, char *file, bool missing_ok)\n> ...\n> + if (file == NULL)\n> + return;\n>\n> That seems totally inappropriate.\n>\n\nRemoved.\n\n\n> + sendFile(file, file + basepathlen, &statbuf,\n> true, InvalidOid, NULL, NULL);\n>\n> Maybe I'm misunderstanding, but this looks like it's going to write a\n> tar header, even though we're not writing a tarfile.\n>\n\nsendFile() always sends files with tar header included, even if the backup\nmode\n\nis plain. pg_basebackup also expects the same. That's the current behavior\nof\n\nthe system.\n\nOtherwise, we will have to duplicate this function which would be doing the\npretty\n\nmuch same thing, except the tar header.\n\n\n\n>\n> + else\n> + ereport(WARNING,\n> + (errmsg(\"skipping special file\n> or directory \\\"%s\\\"\", file)));\n>\n> So, if the user asks for a directory or symlink, what's going to\n> happen is that they're going to receive an empty file, and get a\n> warning. That sounds like terrible behavior.\n>\n\nRemoved the warning and generated an error if other then a regular file is\nrequested.\n\n\n>\n>\n> + /*\n> + * Check for checksum failures. If there are failures across\n> multiple\n> + * processes it may not report total checksum count, but it will\n> error\n> + * out,terminating the backup.\n> + */\n>\n> In other words, the patch breaks the feature. Not that the feature in\n> question works particularly well as things stand, but this makes it\n> worse.\n>\n\nAdded an atomic uint64 total_checksum_failures to shared state to keep\nthe total count across workers, So it will have the same behavior as\ncurrent.\n\n\n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca", "msg_date": "Wed, 22 Apr 2020 19:18:20 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, Apr 22, 2020 at 10:18 AM Asif Rehman <asifr.rehman@gmail.com> wrote:\n> I don't foresee memory to be a challenge here. Assuming a database containing 10240\n> relation files (that max reach to 10 TB of size), the list will occupy approximately 102MB\n> of space in memory. This obviously can be reduced, but it doesn’t seem too bad either.\n> One way of doing it is by fetching a smaller set of files and clients can result in the next\n> set if the current one is processed; perhaps fetch initially per table space and request for\n> next one once the current one is done with.\n\nThe more concerning case is when someone has a lot of small files.\n\n> Okay have added throttling_counter as atomic. however a lock is still required\n> for throttling_counter%=throttling_sample.\n\nWell, if you can't get rid of the lock, using a atomics is pointless.\n\n>> + sendFile(file, file + basepathlen, &statbuf,\n>> true, InvalidOid, NULL, NULL);\n>>\n>> Maybe I'm misunderstanding, but this looks like it's going to write a\n>> tar header, even though we're not writing a tarfile.\n>\n> sendFile() always sends files with tar header included, even if the backup mode\n> is plain. pg_basebackup also expects the same. That's the current behavior of\n> the system.\n>\n> Otherwise, we will have to duplicate this function which would be doing the pretty\n> much same thing, except the tar header.\n\nWell, as I said before, the solution to that problem is refactoring,\nnot crummy interfaces. You're never going to persuade any committer\nwho understands what that code actually does to commit it.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Wed, 22 Apr 2020 12:27:35 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, Apr 22, 2020 at 7:48 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n> Hi Dipesh,\n>\n> The rebased and updated patch is attached. Its rebased to (9f2c4ede).\n>\n\nMake is failing for v15 patch.\n\ngcc -std=gnu99 -Wall -Wmissing-prototypes -Wpointer-arith\n-Wdeclaration-after-statement -Werror=vla -Wendif-labels\n-Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv\n-g -g -O0 -I. -I. -I../../../src/include -D_GNU_SOURCE -c -o\nbasebackup.o basebackup.c -MMD -MP -MF .deps/basebackup.Po\nIn file included from basebackup.c:33:\n../../../src/include/replication/backup_manifest.h:37: error: redefinition\nof typedef ‘manifest_info’\n../../../src/include/replication/basebackup.h:35: note: previous\ndeclaration of ‘manifest_info’ was here\nmake[3]: *** [basebackup.o] Error 1\nmake[3]: Leaving directory\n`/home/edb/WORKDB/PG2/postgresql/src/backend/replication'\nmake[2]: *** [replication-recursive] Error 2\n\n\n>\n>\n\nOn Wed, Apr 22, 2020 at 7:48 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Hi Dipesh,The rebased and updated patch is attached. Its rebased to (9f2c4ede).Make is failing for v15 patch.gcc -std=gnu99 -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -g -g -O0 -I. -I. -I../../../src/include  -D_GNU_SOURCE   -c -o basebackup.o basebackup.c -MMD -MP -MF .deps/basebackup.PoIn file included from basebackup.c:33:../../../src/include/replication/backup_manifest.h:37: error: redefinition of typedef ‘manifest_info’../../../src/include/replication/basebackup.h:35: note: previous declaration of ‘manifest_info’ was heremake[3]: *** [basebackup.o] Error 1make[3]: Leaving directory `/home/edb/WORKDB/PG2/postgresql/src/backend/replication'make[2]: *** [replication-recursive] Error 2", "msg_date": "Thu, 23 Apr 2020 12:13:33 +0530", "msg_from": "Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Apr 23, 2020 at 11:43 AM Rajkumar Raghuwanshi <\nrajkumar.raghuwanshi@enterprisedb.com> wrote:\n\n>\n>\n> On Wed, Apr 22, 2020 at 7:48 PM Asif Rehman <asifr.rehman@gmail.com>\n> wrote:\n>\n>>\n>> Hi Dipesh,\n>>\n>> The rebased and updated patch is attached. Its rebased to (9f2c4ede).\n>>\n>\n> Make is failing for v15 patch.\n>\n> gcc -std=gnu99 -Wall -Wmissing-prototypes -Wpointer-arith\n> -Wdeclaration-after-statement -Werror=vla -Wendif-labels\n> -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv\n> -g -g -O0 -I. -I. -I../../../src/include -D_GNU_SOURCE -c -o\n> basebackup.o basebackup.c -MMD -MP -MF .deps/basebackup.Po\n> In file included from basebackup.c:33:\n> ../../../src/include/replication/backup_manifest.h:37: error: redefinition\n> of typedef ‘manifest_info’\n> ../../../src/include/replication/basebackup.h:35: note: previous\n> declaration of ‘manifest_info’ was here\n> make[3]: *** [basebackup.o] Error 1\n> make[3]: Leaving directory\n> `/home/edb/WORKDB/PG2/postgresql/src/backend/replication'\n> make[2]: *** [replication-recursive] Error 2\n>\n>\nJust compiled on clean source and its compiling fine. Can you see if you\nhave a clean source tree?\n\n\n-- \n--\nAsif Rehman\nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\n\nOn Thu, Apr 23, 2020 at 11:43 AM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:On Wed, Apr 22, 2020 at 7:48 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Hi Dipesh,The rebased and updated patch is attached. Its rebased to (9f2c4ede).Make is failing for v15 patch.gcc -std=gnu99 -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -g -g -O0 -I. -I. -I../../../src/include  -D_GNU_SOURCE   -c -o basebackup.o basebackup.c -MMD -MP -MF .deps/basebackup.PoIn file included from basebackup.c:33:../../../src/include/replication/backup_manifest.h:37: error: redefinition of typedef ‘manifest_info’../../../src/include/replication/basebackup.h:35: note: previous declaration of ‘manifest_info’ was heremake[3]: *** [basebackup.o] Error 1make[3]: Leaving directory `/home/edb/WORKDB/PG2/postgresql/src/backend/replication'make[2]: *** [replication-recursive] Error 2Just compiled on clean source and its compiling fine. Can you see if you have a clean source tree?-- --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Thu, 23 Apr 2020 13:17:03 +0500", "msg_from": "Asif Rehman <asifr.rehman@gmail.com>", "msg_from_op": true, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Apr 23, 2020 at 1:47 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n\n>\n>\n> On Thu, Apr 23, 2020 at 11:43 AM Rajkumar Raghuwanshi <\n> rajkumar.raghuwanshi@enterprisedb.com> wrote:\n>\n>>\n>>\n>> On Wed, Apr 22, 2020 at 7:48 PM Asif Rehman <asifr.rehman@gmail.com>\n>> wrote:\n>>\n>>>\n>>> Hi Dipesh,\n>>>\n>>> The rebased and updated patch is attached. Its rebased to (9f2c4ede).\n>>>\n>>\n>> Make is failing for v15 patch.\n>>\n>> gcc -std=gnu99 -Wall -Wmissing-prototypes -Wpointer-arith\n>> -Wdeclaration-after-statement -Werror=vla -Wendif-labels\n>> -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv\n>> -g -g -O0 -I. -I. -I../../../src/include -D_GNU_SOURCE -c -o\n>> basebackup.o basebackup.c -MMD -MP -MF .deps/basebackup.Po\n>> In file included from basebackup.c:33:\n>> ../../../src/include/replication/backup_manifest.h:37: error:\n>> redefinition of typedef ‘manifest_info’\n>> ../../../src/include/replication/basebackup.h:35: note: previous\n>> declaration of ‘manifest_info’ was here\n>> make[3]: *** [basebackup.o] Error 1\n>> make[3]: Leaving directory\n>> `/home/edb/WORKDB/PG2/postgresql/src/backend/replication'\n>> make[2]: *** [replication-recursive] Error 2\n>>\n>>\n> Just compiled on clean source and its compiling fine. Can you see if you\n> have a clean source tree?\n>\nYeah, my machine is not cleaned. My colleague Suraj is also able to compile.\nThanks, sorry for the noise.\n\n\n>\n>\n> --\n> --\n> Asif Rehman\n> Highgo Software (Canada/China/Pakistan)\n> URL : www.highgo.ca\n>\n>\n\nOn Thu, Apr 23, 2020 at 1:47 PM Asif Rehman <asifr.rehman@gmail.com> wrote:On Thu, Apr 23, 2020 at 11:43 AM Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com> wrote:On Wed, Apr 22, 2020 at 7:48 PM Asif Rehman <asifr.rehman@gmail.com> wrote:Hi Dipesh,The rebased and updated patch is attached. Its rebased to (9f2c4ede).Make is failing for v15 patch.gcc -std=gnu99 -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -g -g -O0 -I. -I. -I../../../src/include  -D_GNU_SOURCE   -c -o basebackup.o basebackup.c -MMD -MP -MF .deps/basebackup.PoIn file included from basebackup.c:33:../../../src/include/replication/backup_manifest.h:37: error: redefinition of typedef ‘manifest_info’../../../src/include/replication/basebackup.h:35: note: previous declaration of ‘manifest_info’ was heremake[3]: *** [basebackup.o] Error 1make[3]: Leaving directory `/home/edb/WORKDB/PG2/postgresql/src/backend/replication'make[2]: *** [replication-recursive] Error 2Just compiled on clean source and its compiling fine. Can you see if you have a clean source tree?Yeah, my machine is not cleaned. My colleague Suraj is also able to compile.Thanks, sorry for the noise. -- --Asif RehmanHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca", "msg_date": "Thu, 23 Apr 2020 15:23:05 +0530", "msg_from": "Rajkumar Raghuwanshi <rajkumar.raghuwanshi@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi,\n\nHere is the parallel backup performance test results with and without \nthe patch \"parallel_backup_v15\" on AWS cloud environment. Two \n\"t2.xlarge\" machines were used: one for Postgres server and the other \none for pg_basebackup with the same machine configuration showing below.\n\nMachine configuration:\n     Instance Type        :t2.xlarge\n     Volume type          :io1\n     Memory (MiB)         :16GB\n     vCPU #               :4\n     Architecture         :x86_64\n     IOP                  :6000\n     Database Size (GB)   :108\n\nPerformance test results:\nwithout patch:\n     real 18m49.346s\n     user 1m24.178s\n     sys 7m2.966s\n\n1 worker with patch:\n     real 18m43.201s\n     user 1m55.787s\n     sys 7m24.724s\n\n2 worker with patch:\n     real 18m47.373s\n     user 2m22.970s\n     sys 11m23.891s\n\n4 worker with patch:\n     real 18m46.878s\n     user 2m26.791s\n     sys 13m14.716s\n\nAs required, I didn't have the pgbench running in parallel like we did \nin the previous benchmark.\n\nThe perf report files for both Postgres server and pg_basebackup sides \nare attached.\n\nThe files are listed like below. i.e. without patch 1 worker, and with \npatch 1, 2, 4 workers.\n\nperf report on Postgres server side:\n     perf.data-postgres-without-parallel_backup_v15.txt\n     perf.data-postgres-with-parallel_backup_v15-j1.txt\n     perf.data-postgres-with-parallel_backup_v15-j2.txt\n     perf.data-postgres-with-parallel_backup_v15-j4.txt\n\nperf report on pg_basebackup side:\n     perf.data-pg_basebackup-without-parallel_backup_v15.txt\n     perf.data-pg_basebackup-with-parallel_backup_v15-j1.txt\n     perf.data-pg_basebackup-with-parallel_backup_v15-j2.txt\n     perf.data-pg_basebackup-with-parallel_backup_v15-j4.txt\n\n\nIf any more information required please let me know.\n\n\nOn 2020-04-21 7:12 a.m., Amit Kapila wrote:\n> On Tue, Apr 21, 2020 at 5:26 PM Ahsan Hadi <ahsan.hadi@gmail.com> wrote:\n>> On Tue, Apr 21, 2020 at 4:50 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>> On Tue, Apr 21, 2020 at 5:18 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>>> On Tue, Apr 21, 2020 at 1:00 PM Asif Rehman <asifr.rehman@gmail.com> wrote:\n>>>>> I did some tests a while back, and here are the results. The tests were done to simulate\n>>>>> a live database environment using pgbench.\n>>>>>\n>>>>> machine configuration used for this test:\n>>>>> Instance Type: t2.xlarge\n>>>>> Volume Type : io1\n>>>>> Memory (MiB) : 16384\n>>>>> vCPU # : 4\n>>>>> Architecture : X86_64\n>>>>> IOP : 16000\n>>>>> Database Size (GB) : 102\n>>>>>\n>>>>> The setup consist of 3 machines.\n>>>>> - one for database instances\n>>>>> - one for pg_basebackup client and\n>>>>> - one for pgbench with some parallel workers, simulating SELECT loads.\n>>>>>\n>>>>> basebackup | 4 workers | 8 Workers | 16 workers\n>>>>> Backup Duration(Min): 69.25 | 20.44 | 19.86 | 20.15\n>>>>> (pgbench running with 50 parallel client simulating SELECT load)\n>>>>>\n>>>>> Backup Duration(Min): 154.75 | 49.28 | 45.27 | 20.35\n>>>>> (pgbench running with 100 parallel client simulating SELECT load)\n>>>>>\n>>>> Thanks for sharing the results, these show nice speedup! However, I\n>>>> think we should try to find what exactly causes this speed up. If you\n>>>> see the recent discussion on another thread related to this topic,\n>>>> Andres, pointed out that he doesn't think that we can gain much by\n>>>> having multiple connections[1]. It might be due to some internal\n>>>> limitations (like small buffers) [2] due to which we are seeing these\n>>>> speedups. It might help if you can share the perf reports of the\n>>>> server-side and pg_basebackup side.\n>>>>\n>>> Just to be clear, we need perf reports both with and without patch-set.\n>>\n>> These tests were done a while back, I think it would be good to run the benchmark again with the latest patches of parallel backup and share the results and perf reports.\n>>\n> Sounds good. I think we should also try to run the test with 1 worker\n> as well. The reason it will be good to see the results with 1 worker\n> is that we can know if the technique to send file by file as is done\n> in this patch is better or worse than the current HEAD code. So, it\n> will be good to see the results of an unpatched code, 1 worker, 2\n> workers, 4 workers, etc.\n>\n-- \nDavid\n\nSoftware Engineer\nHighgo Software Inc. (Canada)\nwww.highgo.ca", "msg_date": "Mon, 27 Apr 2020 09:53:16 -0700", "msg_from": "David Zhang <david.zhang@highgo.ca>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Apr 27, 2020 at 10:23 PM David Zhang <david.zhang@highgo.ca> wrote:\n>\n> Hi,\n>\n> Here is the parallel backup performance test results with and without\n> the patch \"parallel_backup_v15\" on AWS cloud environment. Two\n> \"t2.xlarge\" machines were used: one for Postgres server and the other\n> one for pg_basebackup with the same machine configuration showing below.\n>\n> Machine configuration:\n> Instance Type :t2.xlarge\n> Volume type :io1\n> Memory (MiB) :16GB\n> vCPU # :4\n> Architecture :x86_64\n> IOP :6000\n> Database Size (GB) :108\n>\n> Performance test results:\n> without patch:\n> real 18m49.346s\n> user 1m24.178s\n> sys 7m2.966s\n>\n> 1 worker with patch:\n> real 18m43.201s\n> user 1m55.787s\n> sys 7m24.724s\n>\n> 2 worker with patch:\n> real 18m47.373s\n> user 2m22.970s\n> sys 11m23.891s\n>\n> 4 worker with patch:\n> real 18m46.878s\n> user 2m26.791s\n> sys 13m14.716s\n>\n> As required, I didn't have the pgbench running in parallel like we did\n> in the previous benchmark.\n>\n\nSo, there doesn't seem to be any significant improvement in this\nscenario. Now, it is not clear why there was a significant\nimprovement in the previous run where pgbench was also running\nsimultaneously. I am not sure but maybe it is because when a lot of\nother backends were running (performing read-only workload) the\nbackend that was responsible for doing backup was getting frequently\nscheduled out and it slowed down the overall backup process. And when\nwe start using multiple backends for backup one or other backup\nprocess is always running making the overall backup faster. One idea\nto find this out is to check how much time backup takes when we run it\nwith and without pgbench workload on HEAD (aka unpatched code). Even\nif what I am saying is true or there is some other reason due to which\nwe are seeing speedup in some cases (where there is a concurrent\nworkload), it might not make the case for using multiple backends for\nbackup but still, it is good to find that information as it might help\nin designing this feature better.\n\n> The perf report files for both Postgres server and pg_basebackup sides\n> are attached.\n>\n\nIt is not clear which functions are taking more time or for which\nfunctions time is reduced as function symbols are not present in the\nreports. I think you can refer\n\"https://wiki.postgresql.org/wiki/Profiling_with_perf\" to see how to\ntake profiles and additionally use -fno-omit-frame-pointer during\nconfigure (you can use CFLAGS=\"-fno-omit-frame-pointer during\nconfigure).\n\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 28 Apr 2020 08:45:55 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi,\n\nWe at EnterpriseDB did some performance testing around this\nparallel backup to check how this is beneficial and below are the results.\nIn this testing, we run the backup -\n1) Without Asif’s patch\n2) With Asif’s patch and combination of workers 1,2,4,8.\n\nWe run those test on two setup\n\n1) Client and Server both on the same machine (Local backups)\n\n2) Client and server on a different machine (remote backups)\n\n\n*Machine details: *\n\n1: Server (on which local backups performed and used as server for remote\nbackups)\n\n2: Client (Used as a client for remote backups)\n\n\n*Server:*\n\nRAM: 500 GB\nCPU details:\nArchitecture: x86_64\nCPU op-mode(s): 32-bit, 64-bit\nByte Order: Little Endian\nCPU(s): 128\nOn-line CPU(s) list: 0-127\nThread(s) per core: 2\nCore(s) per socket: 8\nSocket(s): 8\nNUMA node(s): 8\nFilesystem: ext4\n\n\n*Client:*\nRAM: 490 GB\nCPU details:\nArchitecture: ppc64le\nByte Order: Little Endian\nCPU(s): 192\nOn-line CPU(s) list: 0-191\nThread(s) per core: 8\nCore(s) per socket: 1\nSocket(s): 24\nFilesystem: ext4\n\nBelow are the results for the local test:\n\nData size without paralle backup\npatch parallel backup with\n1 worker % performance\nincreased/decreased\ncompare to normal\nbackup\n(without patch) parallel backup with\n2 worker % performance\nincreased/decreased\ncompare to normal\nbackup\n(without patch) parallel backup with\n4 worker % performance\nincreased/decreased\ncompare to normal\nbackup\n(without patch) parallel backup with\n8 worker % performance\nincreased/decreased\ncompare to normal\nbackup\n(without patch)\n10 GB\n(10 tables - each table around 1.05 GB) real 0m27.016s\nuser 0m3.378s\nsys 0m23.059s real 0m30.314s\nuser 0m3.575s\nsys 0m22.946s 12% performance\ndecreased real 0m20.400s\nuser 0m3.622s\nsys 0m29.670s 27% performace\nincreased real 0m15.331s\nuser 0m3.706s\nsys 0m39.189s 43% performance\nincreased real 0m15.094s\nuser 0m3.915s\nsys 1m23.350s 44% performace\nincreased.\n50GB\n(50 tables - each table around 1.05 GB) real 2m11.049s\nuser 0m16.464s\nsys 2m1.757s real 2m26.621s\nuser 0m18.497s\nsys 2m4.792s 21% performance\ndecreased real 1m9.581s\nuser 0m18.298s\nsys 2m12.030s 46% performance\nincreased real 0m53.894s\nuser 0m18.588s\nsys 2m47.390s 58% performance\nincreased. real 0m55.373s\nuser 0m18.423s\nsys 5m57.470s 57% performance\nincreased.\n100GB\n(100 tables - each table around 1.05 GB) real 4m4.776s\nuser 0m33.699s\nsys 3m27.777s real 4m20.862s\nuser 0m35.753s\nsys 3m28.262s 6% performance\ndecreased real 2m37.411s\nuser 0m36.440s\nsys 4m16.424s\" 35% performance\nincreased real 1m49.503s\nuser 0m37.200s\nsys 5m58.077s 55% performace\nincreased real 1m36.762s\nuser 0m36.987s\nsys 9m36.906s 60% performace\nincreased.\n200GB\n(200 tables - each table around 1.05 GB) real 10m34.998s\nuser 1m8.471s\nsys 7m21.520s real 11m30.899s\nuser 1m12.933s\nsys 8m14.496s 8% performance\ndecreased real 6m8.481s\nuser 1m13.771s\nsys 9m31.216s 41% performance\nincreased real 4m2.403s\nuser 1m18.331s\nsys 12m29.661s 61% performance\nincreased real 4m3.768s\nuser 1m24.547s\nsys 15m21.421s 61% performance\nincreased\n\nResults for the remote test:\n\nData size without paralle backup\npatch parallel backup with\n1 worker % performance\nincreased/decreased\ncompare to normal\nbackup\n(without patch) parallel backup with\n2 worker % performance\nincreased/decreased\ncompare to normal\nbackup\n(without patch) parallel backup with\n4 worker % performance\nincreased/decreased\ncompare to normal\nbackup\n(without patch) parallel backup with\n8 worker % performance\nincreased/decreased\ncompare to normal\nbackup\n(without patch)\n10 GB\n(10 tables - each table around 1.05 GB) real 1m36.829s\nuser 0m2.124s\nsys 0m14.004s real 1m37.598s\nuser 0m3.272s\nsys 0m11.110s 0.8% performance\ndecreased real 1m36.753s\nuser 0m2.627s\nsys 0m15.312s 0.08% performance\nincreased. real 1m37.212s\nuser 0m3.835s\nsys 0m13.221s 0.3% performance\ndecreased. real 1m36.977s\nuser 0m4.475s\nsys 0m17.937s 0.1% perfomance\ndecreased.\n50GB\n(50 tables - each table around 1.05 GB) real 7m54.211s\nuser 0m10.826s\nsys 1m10.435s real 7m55.603s\nuser 0m16.535s\nsys 1m8.147s 0.2% performance\ndecreased real 7m53.499s\nuser 0m18.131s\nsys 1m8.822s 0.1% performance\nincreased. real 7m54.687s\nuser 0m15.818s\nsys 1m30.991s 0.1% performance\ndecreased real 7m54.658s\nuser 0m20.783s\nsys 1m34.460s 0.1% performance\ndecreased\n100GB\n(100 tables - each table around 1.05 GB) real 15m45.776s\nuser 0m21.802s\nsys 2m59.006s real 15m46.315s\nuser 0m32.499s\nsys 2m47.245s 0.05% performance\ndecreased real 15m46.065s\nuser 0m28.877s\nsys 2m21.181s 0.03% performacne\ndrcreased real 15m47.793s\nuser 0m30.932s\nsys 2m36.708s 0.2% performance\ndecresed real 15m47.129s\nuser 0m35.151s\nsys 3m23.572s 0.14% performance\ndecreased.\n200GB\n(200 tables - each table around 1.05 GB) real 32m55.720s\nuser 0m50.602s\nsys 5m38.875s real 31m30.602s\nuser 0m45.377s\nsys 4m57.405s 4% performance\nincreased real 31m30.214s\nuser 0m55.023s\nsys 5m8.689s 4% performance\nincreased real 31m31.187s\nuser 1m13.390s\nsys 5m40.861s 4% performance\nincreased real 31m31.729s\nuser 1m4.955s\nsys 6m35.774s 4% performance\ndecreased\n\n\nClient & Server on the same machine, the result shows around 50%\nimprovement in parallel run with worker 4 and 8. We don’t see the huge\nperformance improvement with more workers been added.\n\n\nWhereas, when the client and server on a different machine, we don’t see\nany major benefit in performance. This testing result matches the testing\nresults posted by David Zhang up thread.\n\n\n\nWe ran the test for 100GB backup with parallel worker 4 to see the CPU\nusage and other information. What we noticed is that server is consuming\nthe CPU almost 100% whole the time and pg_stat_activity shows that server\nis busy with ClientWrite most of the time.\n\n\nAttaching captured output for\n\n1) Top command output on the server after every 5 second\n\n2) pg_stat_activity output after every 5 second\n\n3) Top command output on the client after every 5 second\n\n\nDo let me know if anyone has further questions/inputs for the benchmarking.\n\nThanks to Rushabh Lathia for helping me with this testing.\n\nOn Tue, Apr 28, 2020 at 8:46 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> On Mon, Apr 27, 2020 at 10:23 PM David Zhang <david.zhang@highgo.ca>\n> wrote:\n> >\n> > Hi,\n> >\n> > Here is the parallel backup performance test results with and without\n> > the patch \"parallel_backup_v15\" on AWS cloud environment. Two\n> > \"t2.xlarge\" machines were used: one for Postgres server and the other\n> > one for pg_basebackup with the same machine configuration showing below.\n> >\n> > Machine configuration:\n> > Instance Type :t2.xlarge\n> > Volume type :io1\n> > Memory (MiB) :16GB\n> > vCPU # :4\n> > Architecture :x86_64\n> > IOP :6000\n> > Database Size (GB) :108\n> >\n> > Performance test results:\n> > without patch:\n> > real 18m49.346s\n> > user 1m24.178s\n> > sys 7m2.966s\n> >\n> > 1 worker with patch:\n> > real 18m43.201s\n> > user 1m55.787s\n> > sys 7m24.724s\n> >\n> > 2 worker with patch:\n> > real 18m47.373s\n> > user 2m22.970s\n> > sys 11m23.891s\n> >\n> > 4 worker with patch:\n> > real 18m46.878s\n> > user 2m26.791s\n> > sys 13m14.716s\n> >\n> > As required, I didn't have the pgbench running in parallel like we did\n> > in the previous benchmark.\n> >\n>\n> So, there doesn't seem to be any significant improvement in this\n> scenario. Now, it is not clear why there was a significant\n> improvement in the previous run where pgbench was also running\n> simultaneously. I am not sure but maybe it is because when a lot of\n> other backends were running (performing read-only workload) the\n> backend that was responsible for doing backup was getting frequently\n> scheduled out and it slowed down the overall backup process. And when\n> we start using multiple backends for backup one or other backup\n> process is always running making the overall backup faster. One idea\n> to find this out is to check how much time backup takes when we run it\n> with and without pgbench workload on HEAD (aka unpatched code). Even\n> if what I am saying is true or there is some other reason due to which\n> we are seeing speedup in some cases (where there is a concurrent\n> workload), it might not make the case for using multiple backends for\n> backup but still, it is good to find that information as it might help\n> in designing this feature better.\n>\n> > The perf report files for both Postgres server and pg_basebackup sides\n> > are attached.\n> >\n>\n> It is not clear which functions are taking more time or for which\n> functions time is reduced as function symbols are not present in the\n> reports. I think you can refer\n> \"https://wiki.postgresql.org/wiki/Profiling_with_perf\" to see how to\n> take profiles and additionally use -fno-omit-frame-pointer during\n> configure (you can use CFLAGS=\"-fno-omit-frame-pointer during\n> configure).\n>\n>\n> --\n> With Regards,\n> Amit Kapila.\n> EnterpriseDB: http://www.enterprisedb.com\n>\n>\n>\n\n-- \n--\n\nThanks & Regards,\nSuraj kharage,\nEnterpriseDB Corporation,\nThe Postgres Database Company.", "msg_date": "Wed, 29 Apr 2020 18:11:07 +0530", "msg_from": "Suraj Kharage <suraj.kharage@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi,\n\nThanks a lot for sharing the test results. Here is the our test results \nusing perf on three ASW t2.xlarge with below configuration.\n\nMachine configuration:\n       Instance Type        :t2.xlarge\n       Volume type          :io1\n       Memory (MiB)         :16GB\n       vCPU #                   :4\n       Architecture           :x86_64\n       IOP                         :6000\n       Database Size (GB)  :45 (Server)\n\ncase 1: postgres server: without patch and without load\n\n* Disk I/O:\n\n# Samples: 342K of event 'block:block_rq_insert'\n# Event count (approx.): 342834\n#\n# Overhead  Command          Shared Object Symbol\n# ........  ...............  ................. .....................\n#\n     97.65%  postgres         [kernel.kallsyms]  [k] __elv_add_request\n      2.27%  kworker/u30:0    [kernel.kallsyms]  [k] __elv_add_request\n\n\n* CPU:\n\n# Samples: 6M of event 'cpu-clock'\n# Event count (approx.): 1559444750000\n#\n# Overhead  Command          Shared Object Symbol\n# ........  ...............  .................... \n.............................................\n#\n     64.73%  swapper          [kernel.kallsyms]     [k] native_safe_halt\n     10.89%  postgres         [vdso]                [.] __vdso_gettimeofday\n      5.64%  postgres         [kernel.kallsyms]     [k] do_syscall_64\n      5.43%  postgres         libpthread-2.26.so    [.] __libc_recv\n      1.72%  postgres         [kernel.kallsyms]     [k] \npvclock_clocksource_read\n\n* Network:\n\n# Samples: 2M of event 'skb:consume_skb'\n# Event count (approx.): 2739785\n#\n# Overhead  Command          Shared Object Symbol\n# ........  ...............  ................. ...........................\n#\n     91.58%  swapper          [kernel.kallsyms]  [k] consume_skb\n      7.09%  postgres         [kernel.kallsyms]  [k] consume_skb\n      0.61%  kswapd0          [kernel.kallsyms]  [k] consume_skb\n      0.44%  ksoftirqd/3      [kernel.kallsyms]  [k] consume_skb\n\n\ncase 1: pg_basebackup client: without patch and without load\n\n* Disk I/O:\n\n# Samples: 371K of event 'block:block_rq_insert'\n# Event count (approx.): 371362\n#\n# Overhead  Command          Shared Object Symbol\n# ........  ...............  ................. .....................\n#\n     96.78%  kworker/u30:0    [kernel.kallsyms]  [k] __elv_add_request\n      2.82%  pg_basebackup    [kernel.kallsyms]  [k] __elv_add_request\n      0.29%  kworker/u30:1    [kernel.kallsyms]  [k] __elv_add_request\n      0.09%  xfsaild/xvda1    [kernel.kallsyms]  [k] __elv_add_request\n\n\n* CPU:\n\n# Samples: 3M of event 'cpu-clock'\n# Event count (approx.): 903527000000\n#\n# Overhead  Command          Shared Object Symbol\n# ........  ...............  .................. \n.............................................\n#\n     87.99%  swapper          [kernel.kallsyms]   [k] native_safe_halt\n      3.14%  swapper          [kernel.kallsyms]   [k] __lock_text_start\n      0.48%  swapper          [kernel.kallsyms]   [k] \n__softirqentry_text_start\n      0.37%  pg_basebackup    [kernel.kallsyms]   [k] \ncopy_user_enhanced_fast_string\n      0.35%  swapper          [kernel.kallsyms]   [k] do_csum\n\n* Network:\n\n# Samples: 12M of event 'skb:consume_skb'\n# Event count (approx.): 12260713\n#\n# Overhead  Command          Shared Object Symbol\n# ........  ...............  ................. ...........................\n#\n     95.12%  swapper          [kernel.kallsyms]  [k] consume_skb\n      3.23%  pg_basebackup    [kernel.kallsyms]  [k] consume_skb\n      0.83%  ksoftirqd/1      [kernel.kallsyms]  [k] consume_skb\n      0.45%  kswapd0          [kernel.kallsyms]  [k] consume_skb\n\n\ncase 2: postgres server: with patch and with load, 4 backup workers on \nclient side\n\n* Disk I/O:\n\n# Samples: 3M of event 'block:block_rq_insert'\n# Event count (approx.): 3634542\n#\n# Overhead  Command          Shared Object Symbol\n# ........  ...............  ................. .....................\n#\n     98.88%  postgres         [kernel.kallsyms]  [k] __elv_add_request\n      0.66%  perf             [kernel.kallsyms]  [k] __elv_add_request\n      0.42%  kworker/u30:1    [kernel.kallsyms]  [k] __elv_add_request\n      0.01%  sshd             [kernel.kallsyms]  [k] __elv_add_request\n\n* CPU:\n\n# Samples: 9M of event 'cpu-clock'\n# Event count (approx.): 2299129250000\n#\n# Overhead  Command          Shared Object Symbol\n# ........  ...............  ..................... \n.............................................\n#\n     52.73%  swapper          [kernel.kallsyms]      [k] native_safe_halt\n      8.31%  postgres         [vdso]                 [.] __vdso_gettimeofday\n      4.46%  postgres         [kernel.kallsyms]      [k] do_syscall_64\n      4.16%  postgres         libpthread-2.26.so     [.] __libc_recv\n      1.58%  postgres         [kernel.kallsyms]      [k] __lock_text_start\n      1.52%  postgres         [kernel.kallsyms]      [k] \npvclock_clocksource_read\n      0.81%  postgres         [kernel.kallsyms]      [k] \ncopy_user_enhanced_fast_string\n\n\n* Network:\n\n# Samples: 6M of event 'skb:consume_skb'\n# Event count (approx.): 6048795\n#\n# Overhead  Command          Shared Object Symbol\n# ........  ...............  ................. ...........................\n#\n     85.81%  postgres         [kernel.kallsyms]  [k] consume_skb\n     12.03%  swapper          [kernel.kallsyms]  [k] consume_skb\n      0.97%  postgres         [kernel.kallsyms]  [k] __consume_stateless_skb\n      0.85%  ksoftirqd/3      [kernel.kallsyms]  [k] consume_skb\n      0.24%  perf             [kernel.kallsyms]  [k] consume_skb\n\n\ncase 2: pg_basebackup 4 workers: with patch and with load\n\n* Disk I/O:\n\n# Samples: 372K of event 'block:block_rq_insert'\n# Event count (approx.): 372360\n#\n# Overhead  Command          Shared Object Symbol\n# ........  ...............  ................. .....................\n#\n     97.26%  kworker/u30:0    [kernel.kallsyms]  [k] __elv_add_request\n      1.45%  pg_basebackup    [kernel.kallsyms]  [k] __elv_add_request\n      0.95%  kworker/u30:1    [kernel.kallsyms]  [k] __elv_add_request\n      0.14%  xfsaild/xvda1    [kernel.kallsyms]  [k] __elv_add_request\n\n\n* CPU:\n\n# Samples: 4M of event 'cpu-clock'\n# Event count (approx.): 1234071000000\n#\n# Overhead  Command          Shared Object Symbol\n# ........  ...............  ........................ \n.................................................\n#\n     89.25%  swapper          [kernel.kallsyms]         [k] native_safe_halt\n      0.93%  pg_basebackup    [kernel.kallsyms]         [k] \n__lock_text_start\n      0.91%  swapper          [kernel.kallsyms]         [k] \n__lock_text_start\n      0.69%  pg_basebackup    [kernel.kallsyms]         [k] \ncopy_user_enhanced_fast_string\n      0.45%  swapper          [kernel.kallsyms]         [k] do_csum\n\n\n* Network:\n\n# Samples: 6M of event 'skb:consume_skb'\n# Event count (approx.): 6449013\n#\n# Overhead  Command          Shared Object Symbol\n# ........  ...............  ................. ...........................\n#\n     90.28%  pg_basebackup    [kernel.kallsyms]  [k] consume_skb\n      9.09%  swapper          [kernel.kallsyms]  [k] consume_skb\n      0.29%  ksoftirqd/1      [kernel.kallsyms]  [k] consume_skb\n      0.21%  sshd             [kernel.kallsyms]  [k] consume_skb\n\n\nThe detailed perf report is attached, with different scenarios, i.e. \nwithout patch (with and without load for server and client) , with patch \n(with and without load for 1, 2, 4, 8 workers for both server and \nclient). The file name should self explain the cases.\n\nLet me know if more information required.\n\nBest regards,\n\nDavid\n\nOn 2020-04-29 5:41 a.m., Suraj Kharage wrote:\n> Hi,\n>\n> We at EnterpriseDB did some performance testing around this \n> parallel backup to check how this is beneficial and below are the \n> results. In this testing, we run the backup -\n> 1) Without Asif’s patch\n> 2) With Asif’s patch and combination of workers 1,2,4,8.\n>\n> We run those test on two setup\n>\n> 1) Client and Server both on the same machine (Local backups)\n>\n> 2) Client and server on a different machine (remote backups)\n>\n>\n> *Machine details: *\n>\n> 1: Server (on which local backups performed and used as server for \n> remote backups)\n>\n> 2: Client (Used as a client for remote backups)\n>\n>\n> *Server:*\n>\n> RAM:500 GB\n> CPU details:\n> Architecture: x86_64\n> CPU op-mode(s): 32-bit, 64-bit\n> Byte Order: Little Endian\n> CPU(s): 128\n> On-line CPU(s) list: 0-127\n> Thread(s) per core: 2\n> Core(s) per socket: 8\n> Socket(s): 8\n> NUMA node(s): 8\n> Filesystem:ext4\n>\n>\n> *Client:*\n> RAM:490 GB\n> CPU details:\n> Architecture: ppc64le\n> Byte Order: Little Endian\n> CPU(s): 192\n> On-line CPU(s) list: 0-191\n> Thread(s) per core: 8\n> Core(s) per socket: 1\n> Socket(s): 24\n> Filesystem:ext4\n>\n> Below are the results for the local test:\n>\n> Data size \twithout paralle backup\n> patch \tparallel backup with\n> 1 worker \t% performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch) \tparallel backup with\n> 2 worker \t% performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch) \tparallel backup with\n> 4 worker \t% performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch) \tparallel backup with\n> 8 worker \t% performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch)\n> 10 GB\n> (10 tables - each table around 1.05 GB) \treal 0m27.016s\n> user 0m3.378s\n> sys 0m23.059s \treal 0m30.314s\n> user 0m3.575s\n> sys 0m22.946s \t12% performance\n> decreased \treal 0m20.400s\n> user 0m3.622s\n> sys 0m29.670s \t27% performace\n> increased \treal 0m15.331s\n> user 0m3.706s\n> sys 0m39.189s \t43% performance\n> increased \treal 0m15.094s\n> user 0m3.915s\n> sys 1m23.350s \t44% performace\n> increased.\n> 50GB\n> (50 tables - each table around 1.05 GB) \treal 2m11.049s\n> user 0m16.464s\n> sys 2m1.757s \treal 2m26.621s\n> user 0m18.497s\n> sys 2m4.792s \t21% performance\n> decreased \treal 1m9.581s\n> user 0m18.298s\n> sys 2m12.030s \t46% performance\n> increased \treal 0m53.894s\n> user 0m18.588s\n> sys 2m47.390s \t58% performance\n> increased. \treal 0m55.373s\n> user 0m18.423s\n> sys 5m57.470s \t57% performance\n> increased.\n> 100GB\n> (100 tables - each table around 1.05 GB) \treal 4m4.776s\n> user 0m33.699s\n> sys 3m27.777s \treal 4m20.862s\n> user 0m35.753s\n> sys 3m28.262s \t6% performance\n> decreased \treal 2m37.411s\n> user 0m36.440s\n> sys 4m16.424s\" \t35% performance\n> increased \treal 1m49.503s\n> user 0m37.200s\n> sys 5m58.077s \t55% performace\n> increased \treal 1m36.762s\n> user 0m36.987s\n> sys 9m36.906s \t60% performace\n> increased.\n> 200GB\n> (200 tables - each table around 1.05 GB) \treal 10m34.998s\n> user 1m8.471s\n> sys 7m21.520s \treal 11m30.899s\n> user 1m12.933s\n> sys 8m14.496s \t8% performance\n> decreased \treal 6m8.481s\n> user 1m13.771s\n> sys 9m31.216s \t41% performance\n> increased \treal 4m2.403s\n> user 1m18.331s\n> sys 12m29.661s \t61% performance\n> increased \treal 4m3.768s\n> user 1m24.547s\n> sys 15m21.421s \t61% performance\n> increased\n>\n>\n> Results for the remote test:\n>\n> Data size \twithout paralle backup\n> patch \tparallel backup with\n> 1 worker \t% performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch) \tparallel backup with\n> 2 worker \t% performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch) \tparallel backup with\n> 4 worker \t% performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch) \tparallel backup with\n> 8 worker \t% performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch)\n> 10 GB\n> (10 tables - each table around 1.05 GB) \treal 1m36.829s\n> user 0m2.124s\n> sys 0m14.004s \treal 1m37.598s\n> user 0m3.272s\n> sys 0m11.110s \t0.8% performance\n> decreased \treal 1m36.753s\n> user 0m2.627s\n> sys 0m15.312s \t0.08% performance\n> increased. \treal 1m37.212s\n> user 0m3.835s\n> sys 0m13.221s \t0.3% performance\n> decreased. \treal 1m36.977s\n> user 0m4.475s\n> sys 0m17.937s \t0.1% perfomance\n> decreased.\n> 50GB\n> (50 tables - each table around 1.05 GB) \treal 7m54.211s\n> user 0m10.826s\n> sys 1m10.435s \treal 7m55.603s\n> user 0m16.535s\n> sys 1m8.147s \t0.2% performance\n> decreased \treal 7m53.499s\n> user 0m18.131s\n> sys 1m8.822s \t0.1% performance\n> increased. \treal 7m54.687s\n> user 0m15.818s\n> sys 1m30.991s \t0.1% performance\n> decreased \treal 7m54.658s\n> user 0m20.783s\n> sys 1m34.460s \t0.1% performance\n> decreased\n> 100GB\n> (100 tables - each table around 1.05 GB) \treal 15m45.776s\n> user 0m21.802s\n> sys 2m59.006s \treal 15m46.315s\n> user 0m32.499s\n> sys 2m47.245s \t0.05% performance\n> decreased \treal 15m46.065s\n> user 0m28.877s\n> sys 2m21.181s \t0.03% performacne\n> drcreased \treal 15m47.793s\n> user 0m30.932s\n> sys 2m36.708s \t0.2% performance\n> decresed \treal 15m47.129s\n> user 0m35.151s\n> sys 3m23.572s \t0.14% performance\n> decreased.\n> 200GB\n> (200 tables - each table around 1.05 GB) \treal 32m55.720s\n> user 0m50.602s\n> sys 5m38.875s \treal 31m30.602s\n> user 0m45.377s\n> sys 4m57.405s \t4% performance\n> increased \treal 31m30.214s\n> user 0m55.023s\n> sys 5m8.689s \t4% performance\n> increased \treal 31m31.187s\n> user 1m13.390s\n> sys 5m40.861s \t4% performance\n> increased \treal 31m31.729s\n> user 1m4.955s\n> sys 6m35.774s \t4% performance\n> decreased\n>\n>\n>\n> Client & Server on the same machine, the result shows around 50% \n> improvement in parallel run with worker 4 and 8.  We don’t see the \n> huge performance improvement with more workers been added.\n>\n>\n> Whereas, when the client and server on a different machine, we don’t \n> see any major benefit in performance.  This testing result matches the \n> testing results posted by David Zhang up thread.\n>\n>\n>\n> We ran the test for 100GB backup with parallel worker 4 to see the CPU \n> usage and other information. What we noticed is that server is \n> consuming the CPU almost 100% whole the time and pg_stat_activity \n> shows that server is busy with ClientWrite most of the time.\n>\n>\n> Attaching captured output for\n>\n> 1) Top command output on the server after every 5 second\n>\n> 2) pg_stat_activity output after every 5 second\n>\n> 3) Top command output on the client after every 5 second\n>\n>\n> Do let me know if anyone has further questions/inputs for the \n> benchmarking.\n>\n>\n> Thanks to Rushabh Lathia for helping me with this testing.\n>\n> On Tue, Apr 28, 2020 at 8:46 AM Amit Kapila <amit.kapila16@gmail.com \n> <mailto:amit.kapila16@gmail.com>> wrote:\n>\n> On Mon, Apr 27, 2020 at 10:23 PM David Zhang\n> <david.zhang@highgo.ca <mailto:david.zhang@highgo.ca>> wrote:\n> >\n> > Hi,\n> >\n> > Here is the parallel backup performance test results with and\n> without\n> > the patch \"parallel_backup_v15\" on AWS cloud environment. Two\n> > \"t2.xlarge\" machines were used: one for Postgres server and the\n> other\n> > one for pg_basebackup with the same machine configuration\n> showing below.\n> >\n> > Machine configuration:\n> >      Instance Type        :t2.xlarge\n> >      Volume type          :io1\n> >      Memory (MiB)         :16GB\n> >      vCPU #               :4\n> >      Architecture         :x86_64\n> >      IOP                  :6000\n> >      Database Size (GB)   :108\n> >\n> > Performance test results:\n> > without patch:\n> >      real 18m49.346s\n> >      user 1m24.178s\n> >      sys 7m2.966s\n> >\n> > 1 worker with patch:\n> >      real 18m43.201s\n> >      user 1m55.787s\n> >      sys 7m24.724s\n> >\n> > 2 worker with patch:\n> >      real 18m47.373s\n> >      user 2m22.970s\n> >      sys 11m23.891s\n> >\n> > 4 worker with patch:\n> >      real 18m46.878s\n> >      user 2m26.791s\n> >      sys 13m14.716s\n> >\n> > As required, I didn't have the pgbench running in parallel like\n> we did\n> > in the previous benchmark.\n> >\n>\n> So, there doesn't seem to be any significant improvement in this\n> scenario.  Now, it is not clear why there was a significant\n> improvement in the previous run where pgbench was also running\n> simultaneously.  I am not sure but maybe it is because when a lot of\n> other backends were running (performing read-only workload) the\n> backend that was responsible for doing backup was getting frequently\n> scheduled out and it slowed down the overall backup process. And when\n> we start using multiple backends for backup one or other backup\n> process is always running making the overall backup faster. One idea\n> to find this out is to check how much time backup takes when we run it\n> with and without pgbench workload on HEAD (aka unpatched code).  Even\n> if what I am saying is true or there is some other reason due to which\n> we are seeing speedup in some cases (where there is a concurrent\n> workload), it might not make the case for using multiple backends for\n> backup but still, it is good to find that information as it might help\n> in designing this feature better.\n>\n> > The perf report files for both Postgres server and pg_basebackup\n> sides\n> > are attached.\n> >\n>\n> It is not clear which functions are taking more time or for which\n> functions time is reduced as function symbols are not present in the\n> reports.  I think you can refer\n> \"https://wiki.postgresql.org/wiki/Profiling_with_perf\" to see how to\n> take profiles and additionally use -fno-omit-frame-pointer during\n> configure (you can use CFLAGS=\"-fno-omit-frame-pointer during\n> configure).\n>\n>\n> -- \n> With Regards,\n> Amit Kapila.\n> EnterpriseDB: http://www.enterprisedb.com\n>\n>\n>\n>\n> -- \n> -- \n>\n> Thanks & Regards,\n> Suraj kharage,\n> EnterpriseDB Corporation,\n> The Postgres Database Company.\n-- \nDavid\n\nSoftware Engineer\nHighgo Software Inc. (Canada)\nwww.highgo.ca", "msg_date": "Wed, 29 Apr 2020 23:26:16 -0700", "msg_from": "David Zhang <david.zhang@highgo.ca>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "Hi,\n\nWould it be possible to put in the absolute numbers of the perf\nso that it is easier to understand the amount of improvement with\nand without the patch and different loads and workers.\n\nI am also unsure why the swapper is taking such a huge percentage of the\nabsolute time\nin the base run of just the postgres server and pg_basebackup client.\n\nWith Regards,\nSumanta Mukherjee.\nEnterpriseDB: http://www.enterprisedb.com\n\n\nOn Thu, Apr 30, 2020 at 1:18 PM David Zhang <david.zhang@highgo.ca> wrote:\n\n> Hi,\n>\n> Thanks a lot for sharing the test results. Here is the our test results\n> using perf on three ASW t2.xlarge with below configuration.\n>\n> Machine configuration:\n> Instance Type :t2.xlarge\n> Volume type :io1\n> Memory (MiB) :16GB\n> vCPU # :4\n> Architecture :x86_64\n> IOP :6000\n> Database Size (GB) :45 (Server)\n>\n> case 1: postgres server: without patch and without load\n>\n> * Disk I/O:\n>\n> # Samples: 342K of event 'block:block_rq_insert'\n> # Event count (approx.): 342834\n> #\n> # Overhead Command Shared Object Symbol\n> # ........ ............... ................. .....................\n> #\n> 97.65% postgres [kernel.kallsyms] [k] __elv_add_request\n> 2.27% kworker/u30:0 [kernel.kallsyms] [k] __elv_add_request\n>\n>\n> * CPU:\n>\n> # Samples: 6M of event 'cpu-clock'\n> # Event count (approx.): 1559444750000\n> #\n> # Overhead Command Shared Object\n> Symbol\n> # ........ ............... ....................\n> .............................................\n> #\n> 64.73% swapper [kernel.kallsyms] [k] native_safe_halt\n> 10.89% postgres [vdso] [.] __vdso_gettimeofday\n> 5.64% postgres [kernel.kallsyms] [k] do_syscall_64\n> 5.43% postgres libpthread-2.26.so [.] __libc_recv\n> 1.72% postgres [kernel.kallsyms] [k]\n> pvclock_clocksource_read\n>\n> * Network:\n>\n> # Samples: 2M of event 'skb:consume_skb'\n> # Event count (approx.): 2739785\n> #\n> # Overhead Command Shared Object Symbol\n> # ........ ............... ................. ...........................\n> #\n> 91.58% swapper [kernel.kallsyms] [k] consume_skb\n> 7.09% postgres [kernel.kallsyms] [k] consume_skb\n> 0.61% kswapd0 [kernel.kallsyms] [k] consume_skb\n> 0.44% ksoftirqd/3 [kernel.kallsyms] [k] consume_skb\n>\n>\n> case 1: pg_basebackup client: without patch and without load\n>\n> * Disk I/O:\n>\n> # Samples: 371K of event 'block:block_rq_insert'\n> # Event count (approx.): 371362\n> #\n> # Overhead Command Shared Object Symbol\n> # ........ ............... ................. .....................\n> #\n> 96.78% kworker/u30:0 [kernel.kallsyms] [k] __elv_add_request\n> 2.82% pg_basebackup [kernel.kallsyms] [k] __elv_add_request\n> 0.29% kworker/u30:1 [kernel.kallsyms] [k] __elv_add_request\n> 0.09% xfsaild/xvda1 [kernel.kallsyms] [k] __elv_add_request\n>\n>\n> * CPU:\n>\n> # Samples: 3M of event 'cpu-clock'\n> # Event count (approx.): 903527000000\n> #\n> # Overhead Command Shared Object\n> Symbol\n> # ........ ............... ..................\n> .............................................\n> #\n> 87.99% swapper [kernel.kallsyms] [k] native_safe_halt\n> 3.14% swapper [kernel.kallsyms] [k] __lock_text_start\n> 0.48% swapper [kernel.kallsyms] [k]\n> __softirqentry_text_start\n> 0.37% pg_basebackup [kernel.kallsyms] [k]\n> copy_user_enhanced_fast_string\n> 0.35% swapper [kernel.kallsyms] [k] do_csum\n>\n> * Network:\n>\n> # Samples: 12M of event 'skb:consume_skb'\n> # Event count (approx.): 12260713\n> #\n> # Overhead Command Shared Object Symbol\n> # ........ ............... ................. ...........................\n> #\n> 95.12% swapper [kernel.kallsyms] [k] consume_skb\n> 3.23% pg_basebackup [kernel.kallsyms] [k] consume_skb\n> 0.83% ksoftirqd/1 [kernel.kallsyms] [k] consume_skb\n> 0.45% kswapd0 [kernel.kallsyms] [k] consume_skb\n>\n>\n> case 2: postgres server: with patch and with load, 4 backup workers on\n> client side\n>\n> * Disk I/O:\n>\n> # Samples: 3M of event 'block:block_rq_insert'\n> # Event count (approx.): 3634542\n> #\n> # Overhead Command Shared Object Symbol\n> # ........ ............... ................. .....................\n> #\n> 98.88% postgres [kernel.kallsyms] [k] __elv_add_request\n> 0.66% perf [kernel.kallsyms] [k] __elv_add_request\n> 0.42% kworker/u30:1 [kernel.kallsyms] [k] __elv_add_request\n> 0.01% sshd [kernel.kallsyms] [k] __elv_add_request\n>\n> * CPU:\n>\n> # Samples: 9M of event 'cpu-clock'\n> # Event count (approx.): 2299129250000\n> #\n> # Overhead Command Shared Object\n> Symbol\n> # ........ ............... .....................\n> .............................................\n> #\n> 52.73% swapper [kernel.kallsyms] [k] native_safe_halt\n> 8.31% postgres [vdso] [.] __vdso_gettimeofday\n> 4.46% postgres [kernel.kallsyms] [k] do_syscall_64\n> 4.16% postgres libpthread-2.26.so [.] __libc_recv\n> 1.58% postgres [kernel.kallsyms] [k] __lock_text_start\n> 1.52% postgres [kernel.kallsyms] [k]\n> pvclock_clocksource_read\n> 0.81% postgres [kernel.kallsyms] [k]\n> copy_user_enhanced_fast_string\n>\n>\n> * Network:\n>\n> # Samples: 6M of event 'skb:consume_skb'\n> # Event count (approx.): 6048795\n> #\n> # Overhead Command Shared Object Symbol\n> # ........ ............... ................. ...........................\n> #\n> 85.81% postgres [kernel.kallsyms] [k] consume_skb\n> 12.03% swapper [kernel.kallsyms] [k] consume_skb\n> 0.97% postgres [kernel.kallsyms] [k] __consume_stateless_skb\n> 0.85% ksoftirqd/3 [kernel.kallsyms] [k] consume_skb\n> 0.24% perf [kernel.kallsyms] [k] consume_skb\n>\n>\n> case 2: pg_basebackup 4 workers: with patch and with load\n>\n> * Disk I/O:\n>\n> # Samples: 372K of event 'block:block_rq_insert'\n> # Event count (approx.): 372360\n> #\n> # Overhead Command Shared Object Symbol\n> # ........ ............... ................. .....................\n> #\n> 97.26% kworker/u30:0 [kernel.kallsyms] [k] __elv_add_request\n> 1.45% pg_basebackup [kernel.kallsyms] [k] __elv_add_request\n> 0.95% kworker/u30:1 [kernel.kallsyms] [k] __elv_add_request\n> 0.14% xfsaild/xvda1 [kernel.kallsyms] [k] __elv_add_request\n>\n>\n> * CPU:\n>\n> # Samples: 4M of event 'cpu-clock'\n> # Event count (approx.): 1234071000000\n> #\n> # Overhead Command Shared Object\n> Symbol\n> # ........ ............... ........................\n> .................................................\n> #\n> 89.25% swapper [kernel.kallsyms] [k] native_safe_halt\n> 0.93% pg_basebackup [kernel.kallsyms] [k]\n> __lock_text_start\n> 0.91% swapper [kernel.kallsyms] [k]\n> __lock_text_start\n> 0.69% pg_basebackup [kernel.kallsyms] [k]\n> copy_user_enhanced_fast_string\n> 0.45% swapper [kernel.kallsyms] [k] do_csum\n>\n>\n> * Network:\n>\n> # Samples: 6M of event 'skb:consume_skb'\n> # Event count (approx.): 6449013\n> #\n> # Overhead Command Shared Object Symbol\n> # ........ ............... ................. ...........................\n> #\n> 90.28% pg_basebackup [kernel.kallsyms] [k] consume_skb\n> 9.09% swapper [kernel.kallsyms] [k] consume_skb\n> 0.29% ksoftirqd/1 [kernel.kallsyms] [k] consume_skb\n> 0.21% sshd [kernel.kallsyms] [k] consume_skb\n>\n>\n> The detailed perf report is attached, with different scenarios, i.e.\n> without patch (with and without load for server and client) , with patch\n> (with and without load for 1, 2, 4, 8 workers for both server and client).\n> The file name should self explain the cases.\n>\n> Let me know if more information required.\n>\n> Best regards,\n>\n> David\n> On 2020-04-29 5:41 a.m., Suraj Kharage wrote:\n>\n> Hi,\n>\n> We at EnterpriseDB did some performance testing around this\n> parallel backup to check how this is beneficial and below are the results.\n> In this testing, we run the backup -\n> 1) Without Asif’s patch\n> 2) With Asif’s patch and combination of workers 1,2,4,8.\n>\n> We run those test on two setup\n>\n> 1) Client and Server both on the same machine (Local backups)\n>\n> 2) Client and server on a different machine (remote backups)\n>\n>\n> *Machine details: *\n>\n> 1: Server (on which local backups performed and used as server for remote\n> backups)\n>\n> 2: Client (Used as a client for remote backups)\n>\n>\n> *Server:*\n> RAM: 500 GB\n> CPU details:\n> Architecture: x86_64\n> CPU op-mode(s): 32-bit, 64-bit\n> Byte Order: Little Endian\n> CPU(s): 128\n> On-line CPU(s) list: 0-127\n> Thread(s) per core: 2\n> Core(s) per socket: 8\n> Socket(s): 8\n> NUMA node(s): 8\n> Filesystem: ext4\n>\n>\n> *Client:*\n> RAM: 490 GB\n> CPU details:\n> Architecture: ppc64le\n> Byte Order: Little Endian\n> CPU(s): 192\n> On-line CPU(s) list: 0-191\n> Thread(s) per core: 8\n> Core(s) per socket: 1\n> Socket(s): 24\n> Filesystem: ext4\n>\n> Below are the results for the local test:\n>\n> Data size without paralle backup\n> patch parallel backup with\n> 1 worker % performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch) parallel backup with\n> 2 worker % performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch) parallel backup with\n> 4 worker % performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch) parallel backup with\n> 8 worker % performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch)\n> 10 GB\n> (10 tables - each table around 1.05 GB) real 0m27.016s\n> user 0m3.378s\n> sys 0m23.059s real 0m30.314s\n> user 0m3.575s\n> sys 0m22.946s 12% performance\n> decreased real 0m20.400s\n> user 0m3.622s\n> sys 0m29.670s 27% performace\n> increased real 0m15.331s\n> user 0m3.706s\n> sys 0m39.189s 43% performance\n> increased real 0m15.094s\n> user 0m3.915s\n> sys 1m23.350s 44% performace\n> increased.\n> 50GB\n> (50 tables - each table around 1.05 GB) real 2m11.049s\n> user 0m16.464s\n> sys 2m1.757s real 2m26.621s\n> user 0m18.497s\n> sys 2m4.792s 21% performance\n> decreased real 1m9.581s\n> user 0m18.298s\n> sys 2m12.030s 46% performance\n> increased real 0m53.894s\n> user 0m18.588s\n> sys 2m47.390s 58% performance\n> increased. real 0m55.373s\n> user 0m18.423s\n> sys 5m57.470s 57% performance\n> increased.\n> 100GB\n> (100 tables - each table around 1.05 GB) real 4m4.776s\n> user 0m33.699s\n> sys 3m27.777s real 4m20.862s\n> user 0m35.753s\n> sys 3m28.262s 6% performance\n> decreased real 2m37.411s\n> user 0m36.440s\n> sys 4m16.424s\" 35% performance\n> increased real 1m49.503s\n> user 0m37.200s\n> sys 5m58.077s 55% performace\n> increased real 1m36.762s\n> user 0m36.987s\n> sys 9m36.906s 60% performace\n> increased.\n> 200GB\n> (200 tables - each table around 1.05 GB) real 10m34.998s\n> user 1m8.471s\n> sys 7m21.520s real 11m30.899s\n> user 1m12.933s\n> sys 8m14.496s 8% performance\n> decreased real 6m8.481s\n> user 1m13.771s\n> sys 9m31.216s 41% performance\n> increased real 4m2.403s\n> user 1m18.331s\n> sys 12m29.661s 61% performance\n> increased real 4m3.768s\n> user 1m24.547s\n> sys 15m21.421s 61% performance\n> increased\n>\n> Results for the remote test:\n>\n> Data size without paralle backup\n> patch parallel backup with\n> 1 worker % performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch) parallel backup with\n> 2 worker % performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch) parallel backup with\n> 4 worker % performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch) parallel backup with\n> 8 worker % performance\n> increased/decreased\n> compare to normal\n> backup\n> (without patch)\n> 10 GB\n> (10 tables - each table around 1.05 GB) real 1m36.829s\n> user 0m2.124s\n> sys 0m14.004s real 1m37.598s\n> user 0m3.272s\n> sys 0m11.110s 0.8% performance\n> decreased real 1m36.753s\n> user 0m2.627s\n> sys 0m15.312s 0.08% performance\n> increased. real 1m37.212s\n> user 0m3.835s\n> sys 0m13.221s 0.3% performance\n> decreased. real 1m36.977s\n> user 0m4.475s\n> sys 0m17.937s 0.1% perfomance\n> decreased.\n> 50GB\n> (50 tables - each table around 1.05 GB) real 7m54.211s\n> user 0m10.826s\n> sys 1m10.435s real 7m55.603s\n> user 0m16.535s\n> sys 1m8.147s 0.2% performance\n> decreased real 7m53.499s\n> user 0m18.131s\n> sys 1m8.822s 0.1% performance\n> increased. real 7m54.687s\n> user 0m15.818s\n> sys 1m30.991s 0.1% performance\n> decreased real 7m54.658s\n> user 0m20.783s\n> sys 1m34.460s 0.1% performance\n> decreased\n> 100GB\n> (100 tables - each table around 1.05 GB) real 15m45.776s\n> user 0m21.802s\n> sys 2m59.006s real 15m46.315s\n> user 0m32.499s\n> sys 2m47.245s 0.05% performance\n> decreased real 15m46.065s\n> user 0m28.877s\n> sys 2m21.181s 0.03% performacne\n> drcreased real 15m47.793s\n> user 0m30.932s\n> sys 2m36.708s 0.2% performance\n> decresed real 15m47.129s\n> user 0m35.151s\n> sys 3m23.572s 0.14% performance\n> decreased.\n> 200GB\n> (200 tables - each table around 1.05 GB) real 32m55.720s\n> user 0m50.602s\n> sys 5m38.875s real 31m30.602s\n> user 0m45.377s\n> sys 4m57.405s 4% performance\n> increased real 31m30.214s\n> user 0m55.023s\n> sys 5m8.689s 4% performance\n> increased real 31m31.187s\n> user 1m13.390s\n> sys 5m40.861s 4% performance\n> increased real 31m31.729s\n> user 1m4.955s\n> sys 6m35.774s 4% performance\n> decreased\n>\n>\n> Client & Server on the same machine, the result shows around 50%\n> improvement in parallel run with worker 4 and 8. We don’t see the huge\n> performance improvement with more workers been added.\n>\n>\n> Whereas, when the client and server on a different machine, we don’t see\n> any major benefit in performance. This testing result matches the testing\n> results posted by David Zhang up thread.\n>\n>\n>\n> We ran the test for 100GB backup with parallel worker 4 to see the CPU\n> usage and other information. What we noticed is that server is consuming\n> the CPU almost 100% whole the time and pg_stat_activity shows that server\n> is busy with ClientWrite most of the time.\n>\n>\n> Attaching captured output for\n>\n> 1) Top command output on the server after every 5 second\n>\n> 2) pg_stat_activity output after every 5 second\n>\n> 3) Top command output on the client after every 5 second\n>\n>\n> Do let me know if anyone has further questions/inputs for the\n> benchmarking.\n>\n> Thanks to Rushabh Lathia for helping me with this testing.\n>\n> On Tue, Apr 28, 2020 at 8:46 AM Amit Kapila <amit.kapila16@gmail.com>\n> wrote:\n>\n>> On Mon, Apr 27, 2020 at 10:23 PM David Zhang <david.zhang@highgo.ca>\n>> wrote:\n>> >\n>> > Hi,\n>> >\n>> > Here is the parallel backup performance test results with and without\n>> > the patch \"parallel_backup_v15\" on AWS cloud environment. Two\n>> > \"t2.xlarge\" machines were used: one for Postgres server and the other\n>> > one for pg_basebackup with the same machine configuration showing below.\n>> >\n>> > Machine configuration:\n>> > Instance Type :t2.xlarge\n>> > Volume type :io1\n>> > Memory (MiB) :16GB\n>> > vCPU # :4\n>> > Architecture :x86_64\n>> > IOP :6000\n>> > Database Size (GB) :108\n>> >\n>> > Performance test results:\n>> > without patch:\n>> > real 18m49.346s\n>> > user 1m24.178s\n>> > sys 7m2.966s\n>> >\n>> > 1 worker with patch:\n>> > real 18m43.201s\n>> > user 1m55.787s\n>> > sys 7m24.724s\n>> >\n>> > 2 worker with patch:\n>> > real 18m47.373s\n>> > user 2m22.970s\n>> > sys 11m23.891s\n>> >\n>> > 4 worker with patch:\n>> > real 18m46.878s\n>> > user 2m26.791s\n>> > sys 13m14.716s\n>> >\n>> > As required, I didn't have the pgbench running in parallel like we did\n>> > in the previous benchmark.\n>> >\n>>\n>> So, there doesn't seem to be any significant improvement in this\n>> scenario. Now, it is not clear why there was a significant\n>> improvement in the previous run where pgbench was also running\n>> simultaneously. I am not sure but maybe it is because when a lot of\n>> other backends were running (performing read-only workload) the\n>> backend that was responsible for doing backup was getting frequently\n>> scheduled out and it slowed down the overall backup process. And when\n>> we start using multiple backends for backup one or other backup\n>> process is always running making the overall backup faster. One idea\n>> to find this out is to check how much time backup takes when we run it\n>> with and without pgbench workload on HEAD (aka unpatched code). Even\n>> if what I am saying is true or there is some other reason due to which\n>> we are seeing speedup in some cases (where there is a concurrent\n>> workload), it might not make the case for using multiple backends for\n>> backup but still, it is good to find that information as it might help\n>> in designing this feature better.\n>>\n>> > The perf report files for both Postgres server and pg_basebackup sides\n>> > are attached.\n>> >\n>>\n>> It is not clear which functions are taking more time or for which\n>> functions time is reduced as function symbols are not present in the\n>> reports. I think you can refer\n>> \"https://wiki.postgresql.org/wiki/Profiling_with_perf\" to see how to\n>> take profiles and additionally use -fno-omit-frame-pointer during\n>> configure (you can use CFLAGS=\"-fno-omit-frame-pointer during\n>> configure).\n>>\n>>\n>> --\n>> With Regards,\n>> Amit Kapila.\n>> EnterpriseDB: http://www.enterprisedb.com\n>>\n>>\n>>\n>\n> --\n> --\n>\n> Thanks & Regards,\n> Suraj kharage,\n> EnterpriseDB Corporation,\n> The Postgres Database Company.\n>\n> --\n> David\n>\n> Software Engineer\n> Highgo Software Inc. (Canada)\n> www.highgo.ca\n>\n\nHi,Would it be possible to put in the absolute numbers of the perf so that it is easier to understand the amount of improvement with and without the patch and different loads and workers.I am also unsure why the swapper is taking such a huge percentage of the absolute time in the base run of just the postgres server and pg_basebackup client. With Regards,Sumanta Mukherjee.EnterpriseDB: http://www.enterprisedb.comOn Thu, Apr 30, 2020 at 1:18 PM David Zhang <david.zhang@highgo.ca> wrote:\n\nHi,\nThanks a lot for sharing the test results. Here is the our test\n results using perf on three ASW t2.xlarge with below\n configuration. \n\nMachine configuration:\n       Instance Type        :t2.xlarge\n       Volume type          :io1\n       Memory (MiB)         :16GB\n       vCPU #                   :4\n       Architecture           :x86_64\n       IOP                         :6000\n       Database Size (GB)  :45 (Server)\n\ncase 1: postgres server: without patch and without load\n* Disk I/O:\n\n# Samples: 342K of event 'block:block_rq_insert'\n # Event count (approx.): 342834\n #\n # Overhead  Command          Shared Object     \n Symbol               \n # ........  ...............  ................. \n .....................\n #\n     97.65%  postgres         [kernel.kallsyms]  [k]\n __elv_add_request\n      2.27%  kworker/u30:0    [kernel.kallsyms]  [k]\n __elv_add_request\n\n\n* CPU:\n\n# Samples: 6M of event 'cpu-clock'\n # Event count (approx.): 1559444750000\n #\n # Overhead  Command          Shared Object        \n Symbol                                       \n # ........  ...............  .................... \n .............................................\n #\n     64.73%  swapper          [kernel.kallsyms]     [k]\n native_safe_halt\n     10.89%  postgres         [vdso]                [.]\n __vdso_gettimeofday\n      5.64%  postgres         [kernel.kallsyms]     [k]\n do_syscall_64\n      5.43%  postgres         libpthread-2.26.so    [.] __libc_recv\n      1.72%  postgres         [kernel.kallsyms]     [k]\n pvclock_clocksource_read\n* Network:\n\n# Samples: 2M of event 'skb:consume_skb'\n # Event count (approx.): 2739785\n #\n # Overhead  Command          Shared Object     \n Symbol                     \n # ........  ...............  ................. \n ...........................\n #\n     91.58%  swapper          [kernel.kallsyms]  [k] consume_skb\n      7.09%  postgres         [kernel.kallsyms]  [k] consume_skb\n      0.61%  kswapd0          [kernel.kallsyms]  [k] consume_skb\n      0.44%  ksoftirqd/3      [kernel.kallsyms]  [k] consume_skb\n\n\ncase 1: pg_basebackup client: without patch and without load\n* Disk I/O:\n# Samples: 371K of event 'block:block_rq_insert'\n # Event count (approx.): 371362\n #\n # Overhead  Command          Shared Object     \n Symbol               \n # ........  ...............  ................. \n .....................\n #\n     96.78%  kworker/u30:0    [kernel.kallsyms]  [k]\n __elv_add_request\n      2.82%  pg_basebackup    [kernel.kallsyms]  [k]\n __elv_add_request\n      0.29%  kworker/u30:1    [kernel.kallsyms]  [k]\n __elv_add_request\n      0.09%  xfsaild/xvda1    [kernel.kallsyms]  [k]\n __elv_add_request\n\n\n* CPU:\n# Samples: 3M of event 'cpu-clock'\n # Event count (approx.): 903527000000\n #\n # Overhead  Command          Shared Object      \n Symbol                                       \n # ........  ...............  .................. \n .............................................\n #\n     87.99%  swapper          [kernel.kallsyms]   [k]\n native_safe_halt\n      3.14%  swapper          [kernel.kallsyms]   [k]\n __lock_text_start\n      0.48%  swapper          [kernel.kallsyms]   [k]\n __softirqentry_text_start\n      0.37%  pg_basebackup    [kernel.kallsyms]   [k]\n copy_user_enhanced_fast_string\n      0.35%  swapper          [kernel.kallsyms]   [k] do_csum\n\n* Network:\n# Samples: 12M of event 'skb:consume_skb'\n # Event count (approx.): 12260713\n #\n # Overhead  Command          Shared Object     \n Symbol                     \n # ........  ...............  ................. \n ...........................\n #\n     95.12%  swapper          [kernel.kallsyms]  [k] consume_skb\n      3.23%  pg_basebackup    [kernel.kallsyms]  [k] consume_skb\n      0.83%  ksoftirqd/1      [kernel.kallsyms]  [k] consume_skb\n      0.45%  kswapd0          [kernel.kallsyms]  [k] consume_skb\n\n\ncase 2: postgres server: with patch and with load, 4 backup\n workers on client side\n\n* Disk I/O:\n# Samples: 3M of event 'block:block_rq_insert'\n # Event count (approx.): 3634542\n #\n # Overhead  Command          Shared Object     \n Symbol               \n # ........  ...............  ................. \n .....................\n #\n     98.88%  postgres         [kernel.kallsyms]  [k]\n __elv_add_request\n      0.66%  perf             [kernel.kallsyms]  [k]\n __elv_add_request\n      0.42%  kworker/u30:1    [kernel.kallsyms]  [k]\n __elv_add_request\n      0.01%  sshd             [kernel.kallsyms]  [k]\n __elv_add_request\n\n* CPU:\n# Samples: 9M of event 'cpu-clock'\n # Event count (approx.): 2299129250000\n #\n # Overhead  Command          Shared Object         \n Symbol                                       \n # ........  ...............  ..................... \n .............................................\n #\n     52.73%  swapper          [kernel.kallsyms]      [k]\n native_safe_halt\n      8.31%  postgres         [vdso]                 [.]\n __vdso_gettimeofday\n      4.46%  postgres         [kernel.kallsyms]      [k]\n do_syscall_64\n      4.16%  postgres         libpthread-2.26.so     [.]\n __libc_recv\n      1.58%  postgres         [kernel.kallsyms]      [k]\n __lock_text_start\n      1.52%  postgres         [kernel.kallsyms]      [k]\n pvclock_clocksource_read\n      0.81%  postgres         [kernel.kallsyms]      [k]\n copy_user_enhanced_fast_string\n\n\n* Network:\n# Samples: 6M of event 'skb:consume_skb'\n # Event count (approx.): 6048795\n #\n # Overhead  Command          Shared Object     \n Symbol                     \n # ........  ...............  ................. \n ...........................\n #\n     85.81%  postgres         [kernel.kallsyms]  [k] consume_skb\n     12.03%  swapper          [kernel.kallsyms]  [k] consume_skb\n      0.97%  postgres         [kernel.kallsyms]  [k]\n __consume_stateless_skb\n      0.85%  ksoftirqd/3      [kernel.kallsyms]  [k] consume_skb\n      0.24%  perf             [kernel.kallsyms]  [k] consume_skb\n\n\ncase 2: pg_basebackup 4 workers: with patch and with load\n* Disk I/O:\n# Samples: 372K of event 'block:block_rq_insert'\n # Event count (approx.): 372360\n #\n # Overhead  Command          Shared Object     \n Symbol               \n # ........  ...............  ................. \n .....................\n #\n     97.26%  kworker/u30:0    [kernel.kallsyms]  [k]\n __elv_add_request\n      1.45%  pg_basebackup    [kernel.kallsyms]  [k]\n __elv_add_request\n      0.95%  kworker/u30:1    [kernel.kallsyms]  [k]\n __elv_add_request\n      0.14%  xfsaild/xvda1    [kernel.kallsyms]  [k]\n __elv_add_request\n\n\n* CPU:\n# Samples: 4M of event 'cpu-clock'\n # Event count (approx.): 1234071000000\n #\n # Overhead  Command          Shared Object            \n Symbol                                           \n # ........  ...............  ........................ \n .................................................\n #\n     89.25%  swapper          [kernel.kallsyms]         [k]\n native_safe_halt\n      0.93%  pg_basebackup    [kernel.kallsyms]         [k]\n __lock_text_start\n      0.91%  swapper          [kernel.kallsyms]         [k]\n __lock_text_start\n      0.69%  pg_basebackup    [kernel.kallsyms]         [k]\n copy_user_enhanced_fast_string\n      0.45%  swapper          [kernel.kallsyms]         [k] do_csum\n\n\n* Network:\n# Samples: 6M of event 'skb:consume_skb'\n # Event count (approx.): 6449013\n #\n # Overhead  Command          Shared Object     \n Symbol                     \n # ........  ...............  ................. \n ...........................\n #\n     90.28%  pg_basebackup    [kernel.kallsyms]  [k] consume_skb\n      9.09%  swapper          [kernel.kallsyms]  [k] consume_skb\n      0.29%  ksoftirqd/1      [kernel.kallsyms]  [k] consume_skb\n      0.21%  sshd             [kernel.kallsyms]  [k] consume_skb\n\n\nThe detailed perf report is attached, with different scenarios,\n i.e. without patch (with and without load for server and client) ,\n with patch (with and without load for 1, 2, 4, 8 workers for both\n server and client). The file name should self explain the cases. \n\nLet me know if more information required.\nBest regards,\nDavid\n\nOn 2020-04-29 5:41 a.m., Suraj Kharage\n wrote:\n\n\nHi,\n \n\nWe at EnterpriseDB did some performance testing around this\n parallel backup to check how this is beneficial and below are\n the results. In this testing, we run the backup - \n1)\n Without Asif’s patch \n2)\n With Asif’s patch and combination of workers 1,2,4,8. \n\n\nWe run those test on two setup\n1) Client and Server both on the\n same machine (Local backups)\n2) Client and server on a\n different machine (remote backups)\n\n\nMachine\n details: \n1:\n Server (on which local backups performed and used as server\n for remote backups)\n2:\n Client (Used as a client for remote backups)\n\n\nServer:\n\n\n\nRAM: 500 GB\n\n\nCPU\n details:\n Architecture: x86_64\n CPU op-mode(s): 32-bit, 64-bit\n Byte Order: Little Endian\n CPU(s): 128\n On-line CPU(s) list: 0-127\n Thread(s) per core: 2\n Core(s) per socket: 8\n Socket(s): 8\n NUMA node(s): 8\n\n\n\nFilesystem: ext4\n\n\n\n\n\nClient:\n\n\n\n\nRAM: 490 GB\n\n\nCPU\n details:\n Architecture: ppc64le\n Byte Order: Little Endian\n CPU(s): 192\n On-line CPU(s) list: 0-191\n Thread(s) per core: 8\n Core(s) per socket: 1\n Socket(s): 24\n\n\n\nFilesystem: ext4\n\n\n\n  \nBelow are the results for the\n local test: \n\n\n\n\n\n\nData\n size\nwithout\n paralle backup \n patch\nparallel\n backup with \n 1 worker\n%\n performance \n increased/decreased\n compare to normal \n backup\n (without patch)\nparallel\n backup with \n 2 worker\n%\n performance \n increased/decreased\n compare to normal \n backup\n (without patch)\nparallel\n backup with \n 4 worker\n%\n performance \n increased/decreased\n compare to normal \n backup\n (without patch)\nparallel\n backup with \n 8 worker\n%\n performance \n increased/decreased\n compare to normal \n backup\n (without patch)\n\n\n10 GB \n (10 tables - each table around 1.05 GB)\nreal\n 0m27.016s\n user 0m3.378s\n sys 0m23.059s\nreal\n 0m30.314s\n user 0m3.575s\n sys 0m22.946s\n12%\n performance \n decreased\nreal\n 0m20.400s\n user 0m3.622s\n sys 0m29.670s\n27%\n performace\n increased\nreal\n 0m15.331s\n user 0m3.706s\n sys 0m39.189s\n43%\n performance\n increased\nreal\n 0m15.094s\n user 0m3.915s\n sys 1m23.350s\n44%\n performace\n increased.\n\n\n50GB\n (50 tables - each table around 1.05 GB)\nreal\n 2m11.049s\n user 0m16.464s\n sys 2m1.757s\nreal\n 2m26.621s\n user 0m18.497s\n sys 2m4.792s\n21%\n performance\n decreased\nreal\n 1m9.581s\n user 0m18.298s\n sys 2m12.030s\n46%\n performance\n increased\nreal\n 0m53.894s\n user 0m18.588s\n sys 2m47.390s\n58%\n performance\n increased.\nreal\n 0m55.373s\n user 0m18.423s\n sys 5m57.470s\n57%\n performance\n increased.\n\n\n100GB\n (100 tables - each table around 1.05 GB)\nreal\n 4m4.776s\n user 0m33.699s\n sys 3m27.777s\nreal\n 4m20.862s\n user 0m35.753s\n sys 3m28.262s\n6%\n performance\n decreased\nreal\n 2m37.411s\n user 0m36.440s\n sys 4m16.424s\"\n35%\n performance\n increased\nreal\n 1m49.503s\n user 0m37.200s\n sys 5m58.077s\n55%\n performace\n increased\nreal\n 1m36.762s\n user 0m36.987s\n sys 9m36.906s\n60%\n performace\n increased.\n\n\n200GB\n (200 tables - each table around 1.05 GB)\nreal\n 10m34.998s\n user 1m8.471s\n sys 7m21.520s\nreal\n 11m30.899s\n user 1m12.933s\n sys 8m14.496s\n8%\n performance\n decreased\nreal\n 6m8.481s\n user 1m13.771s\n sys 9m31.216s\n41%\n performance\n increased\nreal\n 4m2.403s\n user 1m18.331s\n sys 12m29.661s\n61%\n performance\n increased\nreal\n 4m3.768s\n user 1m24.547s\n sys 15m21.421s\n61%\n performance\n increased\n\n\n\n\n\nResults for the remote test: \n\n\n\n\n\n\nData\n size\nwithout\n paralle backup \n patch\nparallel\n backup with \n 1 worker\n%\n performance \n increased/decreased\n compare to normal \n backup\n (without patch)\nparallel\n backup with \n 2 worker\n%\n performance \n increased/decreased\n compare to normal \n backup\n (without patch)\nparallel\n backup with \n 4 worker\n%\n performance \n increased/decreased\n compare to normal \n backup\n (without patch)\nparallel\n backup with \n 8 worker\n%\n performance \n increased/decreased\n compare to normal \n backup\n (without patch)\n\n\n10 GB\n \n (10 tables - each table around 1.05 GB)\nreal\n 1m36.829s\n user 0m2.124s\n sys 0m14.004s\nreal\n 1m37.598s\n user 0m3.272s\n sys 0m11.110s\n0.8%\n performance\n decreased\nreal\n 1m36.753s\n user 0m2.627s\n sys 0m15.312s\n0.08%\n performance\n increased.\nreal\n 1m37.212s\n user 0m3.835s\n sys 0m13.221s\n0.3%\n performance\n decreased.\nreal\n 1m36.977s\n user 0m4.475s\n sys 0m17.937s\n0.1%\n perfomance\n decreased.\n\n\n50GB\n (50 tables - each table around 1.05 GB)\nreal\n 7m54.211s\n user 0m10.826s\n sys 1m10.435s\nreal\n 7m55.603s\n user 0m16.535s\n sys 1m8.147s\n0.2%\n performance\n decreased\nreal\n 7m53.499s\n user 0m18.131s\n sys 1m8.822s\n0.1%\n performance\n increased.\nreal\n 7m54.687s\n user 0m15.818s\n sys 1m30.991s\n0.1%\n performance\n decreased\nreal\n 7m54.658s\n user 0m20.783s\n sys 1m34.460s\n0.1%\n performance\n decreased\n\n\n100GB\n (100 tables - each table around 1.05 GB)\nreal\n 15m45.776s\n user 0m21.802s\n sys 2m59.006s\nreal\n 15m46.315s\n user 0m32.499s\n sys 2m47.245s\n0.05%\n performance\n decreased\nreal\n 15m46.065s\n user 0m28.877s\n sys 2m21.181s\n0.03%\n performacne\n drcreased\nreal\n 15m47.793s\n user 0m30.932s\n sys 2m36.708s\n0.2%\n performance\n decresed\nreal\n 15m47.129s\n user 0m35.151s\n sys 3m23.572s\n0.14%\n performance\n decreased.\n\n\n200GB\n (200 tables - each table around 1.05 GB)\nreal\n 32m55.720s\n user 0m50.602s\n sys 5m38.875s\nreal\n 31m30.602s\n user 0m45.377s\n sys 4m57.405s\n4%\n performance\n increased\nreal\n 31m30.214s\n user 0m55.023s\n sys 5m8.689s\n4%\n performance\n increased\nreal\n 31m31.187s\n user 1m13.390s\n sys 5m40.861s\n4%\n performance\n increased\nreal\n 31m31.729s\n user 1m4.955s\n sys 6m35.774s\n4%\n performance\n decreased\n\n\n\n\n\n\n\n\n\nClient & Server on the\n same machine, the result shows around 50% improvement\n in parallel run with worker 4 and 8.  We don’t see the\n huge performance improvement with more workers been\n added.\n\n\nWhereas, when the client\n and server on a different machine, we don’t see any\n major benefit in performance.  This testing result\n matches the testing results posted by David Zhang up\n thread.\n\n\n\n\nWe ran the test for 100GB\n backup with parallel worker 4 to see the CPU usage and\n other information. What we noticed is that server is\n consuming the CPU almost 100% whole the time and\n pg_stat_activity shows that server is busy with\n ClientWrite most of the time.\n\n\nAttaching captured output\n for\n1) Top command output on\n the server after every 5 second\n2) pg_stat_activity output\n after every 5 second\n3) Top command output on\n the client after every 5 second\n\n\nDo let me know\n if anyone has further questions/inputs for the\n benchmarking. \n\n\n\n\nThanks to Rushabh Lathia for helping me with this\n testing.\n\n\n\n\n\nOn Tue, Apr 28, 2020 at 8:46\n AM Amit Kapila <amit.kapila16@gmail.com>\n wrote:\n\nOn\n Mon, Apr 27, 2020 at 10:23 PM David Zhang <david.zhang@highgo.ca> wrote:\n >\n > Hi,\n >\n > Here is the parallel backup performance test results with\n and without\n > the patch \"parallel_backup_v15\" on AWS cloud environment.\n Two\n > \"t2.xlarge\" machines were used: one for Postgres server\n and the other\n > one for pg_basebackup with the same machine configuration\n showing below.\n >\n > Machine configuration:\n >      Instance Type        :t2.xlarge\n >      Volume type          :io1\n >      Memory (MiB)         :16GB\n >      vCPU #               :4\n >      Architecture         :x86_64\n >      IOP                  :6000\n >      Database Size (GB)   :108\n >\n > Performance test results:\n > without patch:\n >      real 18m49.346s\n >      user 1m24.178s\n >      sys 7m2.966s\n >\n > 1 worker with patch:\n >      real 18m43.201s\n >      user 1m55.787s\n >      sys 7m24.724s\n >\n > 2 worker with patch:\n >      real 18m47.373s\n >      user 2m22.970s\n >      sys 11m23.891s\n >\n > 4 worker with patch:\n >      real 18m46.878s\n >      user 2m26.791s\n >      sys 13m14.716s\n >\n > As required, I didn't have the pgbench running in\n parallel like we did\n > in the previous benchmark.\n >\n\n So, there doesn't seem to be any significant improvement in\n this\n scenario.  Now, it is not clear why there was a significant\n improvement in the previous run where pgbench was also running\n simultaneously.  I am not sure but maybe it is because when a\n lot of\n other backends were running (performing read-only workload)\n the\n backend that was responsible for doing backup was getting\n frequently\n scheduled out and it slowed down the overall backup process. \n And when\n we start using multiple backends for backup one or other\n backup\n process is always running making the overall backup faster. \n One idea\n to find this out is to check how much time backup takes when\n we run it\n with and without pgbench workload on HEAD (aka unpatched\n code).  Even\n if what I am saying is true or there is some other reason due\n to which\n we are seeing speedup in some cases (where there is a\n concurrent\n workload), it might not make the case for using multiple\n backends for\n backup but still, it is good to find that information as it\n might help\n in designing this feature better.\n\n > The perf report files for both Postgres server and\n pg_basebackup sides\n > are attached.\n >\n\n It is not clear which functions are taking more time or for\n which\n functions time is reduced as function symbols are not present\n in the\n reports.  I think you can refer\n \"https://wiki.postgresql.org/wiki/Profiling_with_perf\"\n to see how to\n take profiles and additionally use -fno-omit-frame-pointer\n during\n configure (you can use CFLAGS=\"-fno-omit-frame-pointer during\n configure).\n\n\n -- \n With Regards,\n Amit Kapila.\n EnterpriseDB: http://www.enterprisedb.com\n\n\n\n\n\n\n\n -- \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n--\n \n\n\nThanks\n &\n Regards, \nSuraj\n kharage, \nEnterpriseDB\n Corporation, \nThe\n Postgres\n Database\n Company.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n-- \n David\n\n Software Engineer\n Highgo Software Inc. (Canada)\nwww.highgo.ca", "msg_date": "Thu, 30 Apr 2020 14:48:23 +0530", "msg_from": "Sumanta Mukherjee <sumanta.mukherjee@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Wed, Apr 29, 2020 at 6:11 PM Suraj Kharage\n<suraj.kharage@enterprisedb.com> wrote:\n>\n> Hi,\n>\n> We at EnterpriseDB did some performance testing around this parallel backup to check how this is beneficial and below are the results. In this testing, we run the backup -\n> 1) Without Asif’s patch\n> 2) With Asif’s patch and combination of workers 1,2,4,8.\n>\n> We run those test on two setup\n>\n> 1) Client and Server both on the same machine (Local backups)\n>\n> 2) Client and server on a different machine (remote backups)\n>\n>\n> Machine details:\n>\n> 1: Server (on which local backups performed and used as server for remote backups)\n>\n> 2: Client (Used as a client for remote backups)\n>\n>\n...\n>\n>\n> Client & Server on the same machine, the result shows around 50% improvement in parallel run with worker 4 and 8. We don’t see the huge performance improvement with more workers been added.\n>\n>\n> Whereas, when the client and server on a different machine, we don’t see any major benefit in performance. This testing result matches the testing results posted by David Zhang up thread.\n>\n>\n>\n> We ran the test for 100GB backup with parallel worker 4 to see the CPU usage and other information. What we noticed is that server is consuming the CPU almost 100% whole the time and pg_stat_activity shows that server is busy with ClientWrite most of the time.\n>\n>\n\nWas this for a setup where the client and server were on the same\nmachine or where the client was on a different machine? If it was for\nthe case where both are on the same machine, then ideally, we should\nsee ClientRead events in a similar proportion?\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 30 Apr 2020 16:15:13 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Apr 30, 2020 at 4:15 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> On Wed, Apr 29, 2020 at 6:11 PM Suraj Kharage\n> <suraj.kharage@enterprisedb.com> wrote:\n> >\n> > Hi,\n> >\n> > We at EnterpriseDB did some performance testing around this parallel backup to check how this is beneficial and below are the results. In this testing, we run the backup -\n> > 1) Without Asif’s patch\n> > 2) With Asif’s patch and combination of workers 1,2,4,8.\n> >\n> > We run those test on two setup\n> >\n> > 1) Client and Server both on the same machine (Local backups)\n> >\n> > 2) Client and server on a different machine (remote backups)\n> >\n> >\n> > Machine details:\n> >\n> > 1: Server (on which local backups performed and used as server for remote backups)\n> >\n> > 2: Client (Used as a client for remote backups)\n> >\n> >\n> ...\n> >\n> >\n> > Client & Server on the same machine, the result shows around 50% improvement in parallel run with worker 4 and 8. We don’t see the huge performance improvement with more workers been added.\n> >\n> >\n> > Whereas, when the client and server on a different machine, we don’t see any major benefit in performance. This testing result matches the testing results posted by David Zhang up thread.\n> >\n> >\n> >\n> > We ran the test for 100GB backup with parallel worker 4 to see the CPU usage and other information. What we noticed is that server is consuming the CPU almost 100% whole the time and pg_stat_activity shows that server is busy with ClientWrite most of the time.\n> >\n> >\n>\n> Was this for a setup where the client and server were on the same\n> machine or where the client was on a different machine? If it was for\n> the case where both are on the same machine, then ideally, we should\n> see ClientRead events in a similar proportion?\n>\n\nDuring an offlist discussion with Robert, he pointed out that current\nbasebackup's code doesn't account for the wait event for the reading\nof files which can change what pg_stat_activity shows? Can you please\napply his latest patch to improve basebackup.c's code [1] which will\ntake care of that waitevent before getting the data again?\n\n[1] - https://www.postgresql.org/message-id/CA%2BTgmobBw-3573vMosGj06r72ajHsYeKtksT_oTxH8XvTL7DxA%40mail.gmail.com\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 30 Apr 2020 18:39:36 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On 2020-04-30 2:18 a.m., Sumanta Mukherjee wrote:\n\n> Hi,\n>\n> Would it be possible to put in the absolute numbers of the perf\n> so that it is easier to understand the amount of improvement with\n> and without the patch and different loads and workers.\n\nHere is the parameters used to record the perf data on both server and \nclient side, for example, after applied the patch15 using 4 workers with \nload,\n\nperf record -o postgres_patch_j4_load -e block:block_rq_insert -e \ncpu-clock -e cycles:k -e skb:consume_skb -aR -s -- \n/home/ec2-user/after/bin/postgres -D /mnt/test/data\n\nperf record -o backup_patch_j4_load -e block:block_rq_insert -e \ncpu-clock -e cycles:k -e skb:consume_skb -aR -s -- \n/home/ec2-user/after/bin/pg_basebackup -h ${PG_SERVER} -p 5432 -D \n/mnt/backup/data -v\n\nAnd this is how the report is generated.\nperf report  -i postgres_patch_j4_load --stdio > postgres_patch_j4_load.txt\n\nThe original perf data files are still available, can you please clarify \nwhich parameter you would like to be added for regenerating the report, \nor any other parameters need to be added to recreate the perf.data and \nthen generate the report?\n\n>\n> I am also unsure why the swapper is taking such a huge percentage of \n> the absolute time\n> in the base run of just the postgres server and pg_basebackup client.\n>\n> With Regards,\n> Sumanta Mukherjee.\n> EnterpriseDB: http://www.enterprisedb.com\n>\n>\n> On Thu, Apr 30, 2020 at 1:18 PM David Zhang <david.zhang@highgo.ca \n> <mailto:david.zhang@highgo.ca>> wrote:\n>\n> Hi,\n>\n> Thanks a lot for sharing the test results. Here is the our test\n> results using perf on three ASW t2.xlarge with below configuration.\n>\n> Machine configuration:\n>       Instance Type        :t2.xlarge\n>       Volume type          :io1\n>       Memory (MiB)         :16GB\n>       vCPU #                   :4\n>       Architecture           :x86_64\n>       IOP                         :6000\n>       Database Size (GB)  :45 (Server)\n>\n> case 1: postgres server: without patch and without load\n>\n> * Disk I/O:\n>\n> # Samples: 342K of event 'block:block_rq_insert'\n> # Event count (approx.): 342834\n> #\n> # Overhead  Command          Shared Object Symbol\n> # ........  ...............  ................. .....................\n> #\n>     97.65%  postgres         [kernel.kallsyms]  [k] __elv_add_request\n>      2.27%  kworker/u30:0    [kernel.kallsyms]  [k] __elv_add_request\n>\n>\n> * CPU:\n>\n> # Samples: 6M of event 'cpu-clock'\n> # Event count (approx.): 1559444750000\n> #\n> # Overhead  Command          Shared Object Symbol\n> # ........  ...............  ....................\n> .............................................\n> #\n>     64.73%  swapper          [kernel.kallsyms]     [k]\n> native_safe_halt\n>     10.89%  postgres         [vdso]                [.]\n> __vdso_gettimeofday\n>      5.64%  postgres         [kernel.kallsyms]     [k] do_syscall_64\n>      5.43%  postgres libpthread-2.26.so\n> <http://libpthread-2.26.so>    [.] __libc_recv\n>      1.72%  postgres         [kernel.kallsyms]     [k]\n> pvclock_clocksource_read\n>\n> * Network:\n>\n> # Samples: 2M of event 'skb:consume_skb'\n> # Event count (approx.): 2739785\n> #\n> # Overhead  Command          Shared Object Symbol\n> # ........  ...............  .................\n> ...........................\n> #\n>     91.58%  swapper          [kernel.kallsyms]  [k] consume_skb\n>      7.09%  postgres         [kernel.kallsyms]  [k] consume_skb\n>      0.61%  kswapd0          [kernel.kallsyms]  [k] consume_skb\n>      0.44%  ksoftirqd/3      [kernel.kallsyms]  [k] consume_skb\n>\n>\n> case 1: pg_basebackup client: without patch and without load\n>\n> * Disk I/O:\n>\n> # Samples: 371K of event 'block:block_rq_insert'\n> # Event count (approx.): 371362\n> #\n> # Overhead  Command          Shared Object Symbol\n> # ........  ...............  ................. .....................\n> #\n>     96.78%  kworker/u30:0    [kernel.kallsyms]  [k] __elv_add_request\n>      2.82%  pg_basebackup    [kernel.kallsyms]  [k] __elv_add_request\n>      0.29%  kworker/u30:1    [kernel.kallsyms]  [k] __elv_add_request\n>      0.09%  xfsaild/xvda1    [kernel.kallsyms]  [k] __elv_add_request\n>\n>\n> * CPU:\n>\n> # Samples: 3M of event 'cpu-clock'\n> # Event count (approx.): 903527000000\n> #\n> # Overhead  Command          Shared Object Symbol\n> # ........  ...............  ..................\n> .............................................\n> #\n>     87.99%  swapper          [kernel.kallsyms]   [k] native_safe_halt\n>      3.14%  swapper          [kernel.kallsyms]   [k] __lock_text_start\n>      0.48%  swapper          [kernel.kallsyms]   [k]\n> __softirqentry_text_start\n>      0.37%  pg_basebackup    [kernel.kallsyms]   [k]\n> copy_user_enhanced_fast_string\n>      0.35%  swapper          [kernel.kallsyms]   [k] do_csum\n>\n> * Network:\n>\n> # Samples: 12M of event 'skb:consume_skb'\n> # Event count (approx.): 12260713\n> #\n> # Overhead  Command          Shared Object Symbol\n> # ........  ...............  .................\n> ...........................\n> #\n>     95.12%  swapper          [kernel.kallsyms]  [k] consume_skb\n>      3.23%  pg_basebackup    [kernel.kallsyms]  [k] consume_skb\n>      0.83%  ksoftirqd/1      [kernel.kallsyms]  [k] consume_skb\n>      0.45%  kswapd0          [kernel.kallsyms]  [k] consume_skb\n>\n>\n> case 2: postgres server: with patch and with load, 4 backup\n> workers on client side\n>\n> * Disk I/O:\n>\n> # Samples: 3M of event 'block:block_rq_insert'\n> # Event count (approx.): 3634542\n> #\n> # Overhead  Command          Shared Object Symbol\n> # ........  ...............  ................. .....................\n> #\n>     98.88%  postgres         [kernel.kallsyms]  [k] __elv_add_request\n>      0.66%  perf             [kernel.kallsyms]  [k] __elv_add_request\n>      0.42%  kworker/u30:1    [kernel.kallsyms]  [k] __elv_add_request\n>      0.01%  sshd             [kernel.kallsyms]  [k] __elv_add_request\n>\n> * CPU:\n>\n> # Samples: 9M of event 'cpu-clock'\n> # Event count (approx.): 2299129250000\n> #\n> # Overhead  Command          Shared Object Symbol\n> # ........  ...............  .....................\n> .............................................\n> #\n>     52.73%  swapper          [kernel.kallsyms]      [k]\n> native_safe_halt\n>      8.31%  postgres         [vdso]                 [.]\n> __vdso_gettimeofday\n>      4.46%  postgres         [kernel.kallsyms]      [k] do_syscall_64\n>      4.16%  postgres libpthread-2.26.so\n> <http://libpthread-2.26.so>     [.] __libc_recv\n>      1.58%  postgres         [kernel.kallsyms]      [k]\n> __lock_text_start\n>      1.52%  postgres         [kernel.kallsyms]      [k]\n> pvclock_clocksource_read\n>      0.81%  postgres         [kernel.kallsyms]      [k]\n> copy_user_enhanced_fast_string\n>\n>\n> * Network:\n>\n> # Samples: 6M of event 'skb:consume_skb'\n> # Event count (approx.): 6048795\n> #\n> # Overhead  Command          Shared Object Symbol\n> # ........  ...............  .................\n> ...........................\n> #\n>     85.81%  postgres         [kernel.kallsyms]  [k] consume_skb\n>     12.03%  swapper          [kernel.kallsyms]  [k] consume_skb\n>      0.97%  postgres         [kernel.kallsyms]  [k]\n> __consume_stateless_skb\n>      0.85%  ksoftirqd/3      [kernel.kallsyms]  [k] consume_skb\n>      0.24%  perf             [kernel.kallsyms]  [k] consume_skb\n>\n>\n> case 2: pg_basebackup 4 workers: with patch and with load\n>\n> * Disk I/O:\n>\n> # Samples: 372K of event 'block:block_rq_insert'\n> # Event count (approx.): 372360\n> #\n> # Overhead  Command          Shared Object Symbol\n> # ........  ...............  ................. .....................\n> #\n>     97.26%  kworker/u30:0    [kernel.kallsyms]  [k] __elv_add_request\n>      1.45%  pg_basebackup    [kernel.kallsyms]  [k] __elv_add_request\n>      0.95%  kworker/u30:1    [kernel.kallsyms]  [k] __elv_add_request\n>      0.14%  xfsaild/xvda1    [kernel.kallsyms]  [k] __elv_add_request\n>\n>\n> * CPU:\n>\n> # Samples: 4M of event 'cpu-clock'\n> # Event count (approx.): 1234071000000\n> #\n> # Overhead  Command          Shared Object Symbol\n> # ........  ...............  ........................\n> .................................................\n> #\n>     89.25%  swapper          [kernel.kallsyms] [k] native_safe_halt\n>      0.93%  pg_basebackup    [kernel.kallsyms] [k] __lock_text_start\n>      0.91%  swapper          [kernel.kallsyms] [k] __lock_text_start\n>      0.69%  pg_basebackup    [kernel.kallsyms] [k]\n> copy_user_enhanced_fast_string\n>      0.45%  swapper          [kernel.kallsyms] [k] do_csum\n>\n>\n> * Network:\n>\n> # Samples: 6M of event 'skb:consume_skb'\n> # Event count (approx.): 6449013\n> #\n> # Overhead  Command          Shared Object Symbol\n> # ........  ...............  .................\n> ...........................\n> #\n>     90.28%  pg_basebackup    [kernel.kallsyms]  [k] consume_skb\n>      9.09%  swapper          [kernel.kallsyms]  [k] consume_skb\n>      0.29%  ksoftirqd/1      [kernel.kallsyms]  [k] consume_skb\n>      0.21%  sshd             [kernel.kallsyms]  [k] consume_skb\n>\n>\n> The detailed perf report is attached, with different scenarios,\n> i.e. without patch (with and without load for server and client) ,\n> with patch (with and without load for 1, 2, 4, 8 workers for both\n> server and client). The file name should self explain the cases.\n>\n> Let me know if more information required.\n>\n> Best regards,\n>\n> David\n>\n> On 2020-04-29 5:41 a.m., Suraj Kharage wrote:\n>> Hi,\n>>\n>> We at EnterpriseDB did some performance testing around this\n>> parallel backup to check how this is beneficial and below are the\n>> results. In this testing, we run the backup -\n>> 1) Without Asif’s patch\n>> 2) With Asif’s patch and combination of workers 1,2,4,8.\n>>\n>> We run those test on two setup\n>>\n>> 1) Client and Server both on the same machine (Local backups)\n>>\n>> 2) Client and server on a different machine (remote backups)\n>>\n>>\n>> *Machine details: *\n>>\n>> 1: Server (on which local backups performed and used as server\n>> for remote backups)\n>>\n>> 2: Client (Used as a client for remote backups)\n>>\n>>\n>> *Server:*\n>>\n>> RAM:500 GB\n>> CPU details:\n>> Architecture: x86_64\n>> CPU op-mode(s): 32-bit, 64-bit\n>> Byte Order: Little Endian\n>> CPU(s): 128\n>> On-line CPU(s) list: 0-127\n>> Thread(s) per core: 2\n>> Core(s) per socket: 8\n>> Socket(s): 8\n>> NUMA node(s): 8\n>> Filesystem:ext4\n>>\n>>\n>> *Client:*\n>> RAM:490 GB\n>> CPU details:\n>> Architecture: ppc64le\n>> Byte Order: Little Endian\n>> CPU(s): 192\n>> On-line CPU(s) list: 0-191\n>> Thread(s) per core: 8\n>> Core(s) per socket: 1\n>> Socket(s): 24\n>> Filesystem:ext4\n>>\n>> Below are the results for the local test:\n>>\n>> Data size \twithout paralle backup\n>> patch \tparallel backup with\n>> 1 worker \t% performance\n>> increased/decreased\n>> compare to normal\n>> backup\n>> (without patch) \tparallel backup with\n>> 2 worker \t% performance\n>> increased/decreased\n>> compare to normal\n>> backup\n>> (without patch) \tparallel backup with\n>> 4 worker \t% performance\n>> increased/decreased\n>> compare to normal\n>> backup\n>> (without patch) \tparallel backup with\n>> 8 worker \t% performance\n>> increased/decreased\n>> compare to normal\n>> backup\n>> (without patch)\n>> 10 GB\n>> (10 tables - each table around 1.05 GB) \treal 0m27.016s\n>> user 0m3.378s\n>> sys 0m23.059s \treal 0m30.314s\n>> user 0m3.575s\n>> sys 0m22.946s \t12% performance\n>> decreased \treal 0m20.400s\n>> user 0m3.622s\n>> sys 0m29.670s \t27% performace\n>> increased \treal 0m15.331s\n>> user 0m3.706s\n>> sys 0m39.189s \t43% performance\n>> increased \treal 0m15.094s\n>> user 0m3.915s\n>> sys 1m23.350s \t44% performace\n>> increased.\n>> 50GB\n>> (50 tables - each table around 1.05 GB) \treal 2m11.049s\n>> user 0m16.464s\n>> sys 2m1.757s \treal 2m26.621s\n>> user 0m18.497s\n>> sys 2m4.792s \t21% performance\n>> decreased \treal 1m9.581s\n>> user 0m18.298s\n>> sys 2m12.030s \t46% performance\n>> increased \treal 0m53.894s\n>> user 0m18.588s\n>> sys 2m47.390s \t58% performance\n>> increased. \treal 0m55.373s\n>> user 0m18.423s\n>> sys 5m57.470s \t57% performance\n>> increased.\n>> 100GB\n>> (100 tables - each table around 1.05 GB) \treal 4m4.776s\n>> user 0m33.699s\n>> sys 3m27.777s \treal 4m20.862s\n>> user 0m35.753s\n>> sys 3m28.262s \t6% performance\n>> decreased \treal 2m37.411s\n>> user 0m36.440s\n>> sys 4m16.424s\" \t35% performance\n>> increased \treal 1m49.503s\n>> user 0m37.200s\n>> sys 5m58.077s \t55% performace\n>> increased \treal 1m36.762s\n>> user 0m36.987s\n>> sys 9m36.906s \t60% performace\n>> increased.\n>> 200GB\n>> (200 tables - each table around 1.05 GB) \treal 10m34.998s\n>> user 1m8.471s\n>> sys 7m21.520s \treal 11m30.899s\n>> user 1m12.933s\n>> sys 8m14.496s \t8% performance\n>> decreased \treal 6m8.481s\n>> user 1m13.771s\n>> sys 9m31.216s \t41% performance\n>> increased \treal 4m2.403s\n>> user 1m18.331s\n>> sys 12m29.661s \t61% performance\n>> increased \treal 4m3.768s\n>> user 1m24.547s\n>> sys 15m21.421s \t61% performance\n>> increased\n>>\n>>\n>> Results for the remote test:\n>>\n>> Data size \twithout paralle backup\n>> patch \tparallel backup with\n>> 1 worker \t% performance\n>> increased/decreased\n>> compare to normal\n>> backup\n>> (without patch) \tparallel backup with\n>> 2 worker \t% performance\n>> increased/decreased\n>> compare to normal\n>> backup\n>> (without patch) \tparallel backup with\n>> 4 worker \t% performance\n>> increased/decreased\n>> compare to normal\n>> backup\n>> (without patch) \tparallel backup with\n>> 8 worker \t% performance\n>> increased/decreased\n>> compare to normal\n>> backup\n>> (without patch)\n>> 10 GB\n>> (10 tables - each table around 1.05 GB) \treal 1m36.829s\n>> user 0m2.124s\n>> sys 0m14.004s \treal 1m37.598s\n>> user 0m3.272s\n>> sys 0m11.110s \t0.8% performance\n>> decreased \treal 1m36.753s\n>> user 0m2.627s\n>> sys 0m15.312s \t0.08% performance\n>> increased. \treal 1m37.212s\n>> user 0m3.835s\n>> sys 0m13.221s \t0.3% performance\n>> decreased. \treal 1m36.977s\n>> user 0m4.475s\n>> sys 0m17.937s \t0.1% perfomance\n>> decreased.\n>> 50GB\n>> (50 tables - each table around 1.05 GB) \treal 7m54.211s\n>> user 0m10.826s\n>> sys 1m10.435s \treal 7m55.603s\n>> user 0m16.535s\n>> sys 1m8.147s \t0.2% performance\n>> decreased \treal 7m53.499s\n>> user 0m18.131s\n>> sys 1m8.822s \t0.1% performance\n>> increased. \treal 7m54.687s\n>> user 0m15.818s\n>> sys 1m30.991s \t0.1% performance\n>> decreased \treal 7m54.658s\n>> user 0m20.783s\n>> sys 1m34.460s \t0.1% performance\n>> decreased\n>> 100GB\n>> (100 tables - each table around 1.05 GB) \treal 15m45.776s\n>> user 0m21.802s\n>> sys 2m59.006s \treal 15m46.315s\n>> user 0m32.499s\n>> sys 2m47.245s \t0.05% performance\n>> decreased \treal 15m46.065s\n>> user 0m28.877s\n>> sys 2m21.181s \t0.03% performacne\n>> drcreased \treal 15m47.793s\n>> user 0m30.932s\n>> sys 2m36.708s \t0.2% performance\n>> decresed \treal 15m47.129s\n>> user 0m35.151s\n>> sys 3m23.572s \t0.14% performance\n>> decreased.\n>> 200GB\n>> (200 tables - each table around 1.05 GB) \treal 32m55.720s\n>> user 0m50.602s\n>> sys 5m38.875s \treal 31m30.602s\n>> user 0m45.377s\n>> sys 4m57.405s \t4% performance\n>> increased \treal 31m30.214s\n>> user 0m55.023s\n>> sys 5m8.689s \t4% performance\n>> increased \treal 31m31.187s\n>> user 1m13.390s\n>> sys 5m40.861s \t4% performance\n>> increased \treal 31m31.729s\n>> user 1m4.955s\n>> sys 6m35.774s \t4% performance\n>> decreased\n>>\n>>\n>>\n>> Client & Server on the same machine, the result shows around 50%\n>> improvement in parallel run with worker 4 and 8.  We don’t see\n>> the huge performance improvement with more workers been added.\n>>\n>>\n>> Whereas, when the client and server on a different machine, we\n>> don’t see any major benefit in performance.  This testing result\n>> matches the testing results posted by David Zhang up thread.\n>>\n>>\n>>\n>> We ran the test for 100GB backup with parallel worker 4 to see\n>> the CPU usage and other information. What we noticed is that\n>> server is consuming the CPU almost 100% whole the time and\n>> pg_stat_activity shows that server is busy with ClientWrite most\n>> of the time.\n>>\n>>\n>> Attaching captured output for\n>>\n>> 1) Top command output on the server after every 5 second\n>>\n>> 2) pg_stat_activity output after every 5 second\n>>\n>> 3) Top command output on the client after every 5 second\n>>\n>>\n>> Do let me know if anyone has further questions/inputs for the\n>> benchmarking.\n>>\n>>\n>> Thanks to Rushabh Lathia for helping me with this testing.\n>>\n>> On Tue, Apr 28, 2020 at 8:46 AM Amit Kapila\n>> <amit.kapila16@gmail.com <mailto:amit.kapila16@gmail.com>> wrote:\n>>\n>> On Mon, Apr 27, 2020 at 10:23 PM David Zhang\n>> <david.zhang@highgo.ca <mailto:david.zhang@highgo.ca>> wrote:\n>> >\n>> > Hi,\n>> >\n>> > Here is the parallel backup performance test results with\n>> and without\n>> > the patch \"parallel_backup_v15\" on AWS cloud environment. Two\n>> > \"t2.xlarge\" machines were used: one for Postgres server and\n>> the other\n>> > one for pg_basebackup with the same machine configuration\n>> showing below.\n>> >\n>> > Machine configuration:\n>> >      Instance Type        :t2.xlarge\n>> >      Volume type          :io1\n>> >      Memory (MiB)         :16GB\n>> >      vCPU #               :4\n>> >      Architecture         :x86_64\n>> >      IOP                  :6000\n>> >      Database Size (GB)   :108\n>> >\n>> > Performance test results:\n>> > without patch:\n>> >      real 18m49.346s\n>> >      user 1m24.178s\n>> >      sys 7m2.966s\n>> >\n>> > 1 worker with patch:\n>> >      real 18m43.201s\n>> >      user 1m55.787s\n>> >      sys 7m24.724s\n>> >\n>> > 2 worker with patch:\n>> >      real 18m47.373s\n>> >      user 2m22.970s\n>> >      sys 11m23.891s\n>> >\n>> > 4 worker with patch:\n>> >      real 18m46.878s\n>> >      user 2m26.791s\n>> >      sys 13m14.716s\n>> >\n>> > As required, I didn't have the pgbench running in parallel\n>> like we did\n>> > in the previous benchmark.\n>> >\n>>\n>> So, there doesn't seem to be any significant improvement in this\n>> scenario.  Now, it is not clear why there was a significant\n>> improvement in the previous run where pgbench was also running\n>> simultaneously.  I am not sure but maybe it is because when a\n>> lot of\n>> other backends were running (performing read-only workload) the\n>> backend that was responsible for doing backup was getting\n>> frequently\n>> scheduled out and it slowed down the overall backup process. \n>> And when\n>> we start using multiple backends for backup one or other backup\n>> process is always running making the overall backup faster. \n>> One idea\n>> to find this out is to check how much time backup takes when\n>> we run it\n>> with and without pgbench workload on HEAD (aka unpatched\n>> code).  Even\n>> if what I am saying is true or there is some other reason due\n>> to which\n>> we are seeing speedup in some cases (where there is a concurrent\n>> workload), it might not make the case for using multiple\n>> backends for\n>> backup but still, it is good to find that information as it\n>> might help\n>> in designing this feature better.\n>>\n>> > The perf report files for both Postgres server and\n>> pg_basebackup sides\n>> > are attached.\n>> >\n>>\n>> It is not clear which functions are taking more time or for which\n>> functions time is reduced as function symbols are not present\n>> in the\n>> reports.  I think you can refer\n>> \"https://wiki.postgresql.org/wiki/Profiling_with_perf\" to see\n>> how to\n>> take profiles and additionally use -fno-omit-frame-pointer during\n>> configure (you can use CFLAGS=\"-fno-omit-frame-pointer during\n>> configure).\n>>\n>>\n>> -- \n>> With Regards,\n>> Amit Kapila.\n>> EnterpriseDB: http://www.enterprisedb.com\n>>\n>>\n>>\n>>\n>> -- \n>> -- \n>>\n>> Thanks & Regards,\n>> Suraj kharage,\n>> EnterpriseDB Corporation,\n>> The Postgres Database Company.\n> -- \n> David\n>\n> Software Engineer\n> Highgo Software Inc. (Canada)\n> www.highgo.ca <http://www.highgo.ca>\n>\n-- \nDavid\n\nSoftware Engineer\nHighgo Software Inc. (Canada)\nwww.highgo.ca\n\n\n\n\n\n\nOn 2020-04-30 2:18 a.m., Sumanta Mukherjee wrote:\n\n\n\n\nHi,\n \n\nWould it be possible to put in the absolute numbers of\n the perf \nso that it is easier to understand the amount of\n improvement with \nand without the patch and different loads and workers.\n\n\n\nHere is the parameters used to record the perf data on both\n server and client side, for example, after applied the patch15\n using 4 workers with load,\n\nperf record -o postgres_patch_j4_load -e block:block_rq_insert -e\n cpu-clock -e cycles:k -e skb:consume_skb -aR -s --\n /home/ec2-user/after/bin/postgres -D /mnt/test/data\n\nperf record -o backup_patch_j4_load -e block:block_rq_insert -e\n cpu-clock -e cycles:k -e skb:consume_skb -aR -s --\n /home/ec2-user/after/bin/pg_basebackup -h ${PG_SERVER} -p 5432 -D\n /mnt/backup/data -v\n\nAnd this is how the report is generated.\n perf report  -i postgres_patch_j4_load --stdio >\n postgres_patch_j4_load.txt\nThe original perf data files are still available, can you please\n clarify which parameter you would like to be added for\n regenerating the report, or any other parameters need to be added\n to recreate the perf.data and then generate the report?\n\n\n\n\n\n\nI am also unsure why the swapper is taking such a huge\n percentage of the absolute time \nin the base run of just the postgres server and\n pg_basebackup client. \n\n\n\n\n\n\n\n\n\n\n\n\nWith Regards,\nSumanta Mukherjee.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n\n\n\n\n\n\n\nOn Thu, Apr 30, 2020 at 1:18\n PM David Zhang <david.zhang@highgo.ca>\n wrote:\n\n\n\nHi,\nThanks a lot for sharing the test results. Here is the\n our test results using perf on three ASW t2.xlarge with\n below configuration. \n\nMachine configuration:\n       Instance Type        :t2.xlarge\n       Volume type          :io1\n       Memory (MiB)         :16GB\n       vCPU #                   :4\n       Architecture           :x86_64\n       IOP                         :6000\n       Database Size (GB)  :45 (Server)\n\ncase 1: postgres server: without patch and without load\n* Disk I/O:\n\n# Samples: 342K of event 'block:block_rq_insert'\n # Event count (approx.): 342834\n #\n # Overhead  Command          Shared Object     \n Symbol               \n # ........  ...............  ................. \n .....................\n #\n     97.65%  postgres         [kernel.kallsyms]  [k]\n __elv_add_request\n      2.27%  kworker/u30:0    [kernel.kallsyms]  [k]\n __elv_add_request\n\n\n* CPU:\n\n# Samples: 6M of event 'cpu-clock'\n # Event count (approx.): 1559444750000\n #\n # Overhead  Command          Shared Object        \n Symbol                                       \n # ........  ...............  .................... \n .............................................\n #\n     64.73%  swapper          [kernel.kallsyms]     [k]\n native_safe_halt\n     10.89%  postgres         [vdso]                [.]\n __vdso_gettimeofday\n      5.64%  postgres         [kernel.kallsyms]     [k]\n do_syscall_64\n      5.43%  postgres         libpthread-2.26.so    [.]\n __libc_recv\n      1.72%  postgres         [kernel.kallsyms]     [k]\n pvclock_clocksource_read\n* Network:\n\n# Samples: 2M of event 'skb:consume_skb'\n # Event count (approx.): 2739785\n #\n # Overhead  Command          Shared Object     \n Symbol                     \n # ........  ...............  ................. \n ...........................\n #\n     91.58%  swapper          [kernel.kallsyms]  [k]\n consume_skb\n      7.09%  postgres         [kernel.kallsyms]  [k]\n consume_skb\n      0.61%  kswapd0          [kernel.kallsyms]  [k]\n consume_skb\n      0.44%  ksoftirqd/3      [kernel.kallsyms]  [k]\n consume_skb\n\n\ncase 1: pg_basebackup client: without patch and without\n load\n* Disk I/O:\n# Samples: 371K of event 'block:block_rq_insert'\n # Event count (approx.): 371362\n #\n # Overhead  Command          Shared Object     \n Symbol               \n # ........  ...............  ................. \n .....................\n #\n     96.78%  kworker/u30:0    [kernel.kallsyms]  [k]\n __elv_add_request\n      2.82%  pg_basebackup    [kernel.kallsyms]  [k]\n __elv_add_request\n      0.29%  kworker/u30:1    [kernel.kallsyms]  [k]\n __elv_add_request\n      0.09%  xfsaild/xvda1    [kernel.kallsyms]  [k]\n __elv_add_request\n\n\n* CPU:\n# Samples: 3M of event 'cpu-clock'\n # Event count (approx.): 903527000000\n #\n # Overhead  Command          Shared Object      \n Symbol                                       \n # ........  ...............  .................. \n .............................................\n #\n     87.99%  swapper          [kernel.kallsyms]   [k]\n native_safe_halt\n      3.14%  swapper          [kernel.kallsyms]   [k]\n __lock_text_start\n      0.48%  swapper          [kernel.kallsyms]   [k]\n __softirqentry_text_start\n      0.37%  pg_basebackup    [kernel.kallsyms]   [k]\n copy_user_enhanced_fast_string\n      0.35%  swapper          [kernel.kallsyms]   [k]\n do_csum\n\n* Network:\n# Samples: 12M of event 'skb:consume_skb'\n # Event count (approx.): 12260713\n #\n # Overhead  Command          Shared Object     \n Symbol                     \n # ........  ...............  ................. \n ...........................\n #\n     95.12%  swapper          [kernel.kallsyms]  [k]\n consume_skb\n      3.23%  pg_basebackup    [kernel.kallsyms]  [k]\n consume_skb\n      0.83%  ksoftirqd/1      [kernel.kallsyms]  [k]\n consume_skb\n      0.45%  kswapd0          [kernel.kallsyms]  [k]\n consume_skb\n\n\ncase 2: postgres server: with patch and with load, 4\n backup workers on client side\n\n* Disk I/O:\n# Samples: 3M of event 'block:block_rq_insert'\n # Event count (approx.): 3634542\n #\n # Overhead  Command          Shared Object     \n Symbol               \n # ........  ...............  ................. \n .....................\n #\n     98.88%  postgres         [kernel.kallsyms]  [k]\n __elv_add_request\n      0.66%  perf             [kernel.kallsyms]  [k]\n __elv_add_request\n      0.42%  kworker/u30:1    [kernel.kallsyms]  [k]\n __elv_add_request\n      0.01%  sshd             [kernel.kallsyms]  [k]\n __elv_add_request\n\n* CPU:\n# Samples: 9M of event 'cpu-clock'\n # Event count (approx.): 2299129250000\n #\n # Overhead  Command          Shared Object         \n Symbol                                       \n # ........  ...............  ..................... \n .............................................\n #\n     52.73%  swapper          [kernel.kallsyms]      [k]\n native_safe_halt\n      8.31%  postgres         [vdso]                 [.]\n __vdso_gettimeofday\n      4.46%  postgres         [kernel.kallsyms]      [k]\n do_syscall_64\n      4.16%  postgres         libpthread-2.26.so     [.]\n __libc_recv\n      1.58%  postgres         [kernel.kallsyms]      [k]\n __lock_text_start\n      1.52%  postgres         [kernel.kallsyms]      [k]\n pvclock_clocksource_read\n      0.81%  postgres         [kernel.kallsyms]      [k]\n copy_user_enhanced_fast_string\n\n\n* Network:\n# Samples: 6M of event 'skb:consume_skb'\n # Event count (approx.): 6048795\n #\n # Overhead  Command          Shared Object     \n Symbol                     \n # ........  ...............  ................. \n ...........................\n #\n     85.81%  postgres         [kernel.kallsyms]  [k]\n consume_skb\n     12.03%  swapper          [kernel.kallsyms]  [k]\n consume_skb\n      0.97%  postgres         [kernel.kallsyms]  [k]\n __consume_stateless_skb\n      0.85%  ksoftirqd/3      [kernel.kallsyms]  [k]\n consume_skb\n      0.24%  perf             [kernel.kallsyms]  [k]\n consume_skb\n\n\ncase 2: pg_basebackup 4 workers: with patch and with\n load\n* Disk I/O:\n# Samples: 372K of event 'block:block_rq_insert'\n # Event count (approx.): 372360\n #\n # Overhead  Command          Shared Object     \n Symbol               \n # ........  ...............  ................. \n .....................\n #\n     97.26%  kworker/u30:0    [kernel.kallsyms]  [k]\n __elv_add_request\n      1.45%  pg_basebackup    [kernel.kallsyms]  [k]\n __elv_add_request\n      0.95%  kworker/u30:1    [kernel.kallsyms]  [k]\n __elv_add_request\n      0.14%  xfsaild/xvda1    [kernel.kallsyms]  [k]\n __elv_add_request\n\n\n* CPU:\n# Samples: 4M of event 'cpu-clock'\n # Event count (approx.): 1234071000000\n #\n # Overhead  Command          Shared Object            \n Symbol                                           \n # ........  ...............  ........................ \n .................................................\n #\n     89.25%  swapper          [kernel.kallsyms]        \n [k] native_safe_halt\n      0.93%  pg_basebackup    [kernel.kallsyms]        \n [k] __lock_text_start\n      0.91%  swapper          [kernel.kallsyms]        \n [k] __lock_text_start\n      0.69%  pg_basebackup    [kernel.kallsyms]        \n [k] copy_user_enhanced_fast_string\n      0.45%  swapper          [kernel.kallsyms]        \n [k] do_csum\n\n\n* Network:\n# Samples: 6M of event 'skb:consume_skb'\n # Event count (approx.): 6449013\n #\n # Overhead  Command          Shared Object     \n Symbol                     \n # ........  ...............  ................. \n ...........................\n #\n     90.28%  pg_basebackup    [kernel.kallsyms]  [k]\n consume_skb\n      9.09%  swapper          [kernel.kallsyms]  [k]\n consume_skb\n      0.29%  ksoftirqd/1      [kernel.kallsyms]  [k]\n consume_skb\n      0.21%  sshd             [kernel.kallsyms]  [k]\n consume_skb\n\n\nThe detailed perf report is attached, with different\n scenarios, i.e. without patch (with and without load for\n server and client) , with patch (with and without load\n for 1, 2, 4, 8 workers for both server and client). The\n file name should self explain the cases. \n\nLet me know if more information required.\nBest regards,\nDavid\n\nOn 2020-04-29 5:41 a.m., Suraj Kharage wrote:\n\n\nHi,\n \n\nWe at EnterpriseDB did some performance testing\n around this parallel backup to check how this is\n beneficial and below are the results. In this\n testing, we run the backup - \n1)\n Without Asif’s patch \n2)\n With Asif’s patch and combination of workers\n 1,2,4,8. \n\n\nWe run those test on\n two setup\n1) Client and Server\n both on the same machine (Local backups)\n2) Client and server on\n a different machine (remote backups)\n\n\nMachine\n details: \n1:\n Server (on which local backups performed and used as\n server for remote backups)\n2:\n Client (Used as a client for remote backups)\n\n\nServer:\n\n\n\nRAM:\n 500 GB\n\n\nCPU\n details:\n Architecture: x86_64\n CPU op-mode(s): 32-bit, 64-bit\n Byte Order: Little Endian\n CPU(s): 128\n On-line CPU(s) list: 0-127\n Thread(s) per core: 2\n Core(s) per socket: 8\n Socket(s): 8\n NUMA node(s): 8\n\n\n\nFilesystem:\n ext4\n\n\n\n\n\nClient:\n\n\n\n\nRAM:\n 490 GB\n\n\nCPU\n details:\n Architecture: ppc64le\n Byte Order: Little Endian\n CPU(s): 192\n On-line CPU(s) list: 0-191\n Thread(s) per core: 8\n Core(s) per socket: 1\n Socket(s): 24\n\n\n\nFilesystem:\n ext4\n\n\n\n  \nBelow are the results\n for the local test: \n\n\n\n\n\n\nData\n size\nwithout paralle backup \n patch\nparallel backup with \n 1 worker\n% performance \n increased/decreased\n compare to normal \n backup\n (without patch)\nparallel backup with \n 2 worker\n% performance \n increased/decreased\n compare to normal \n backup\n (without patch)\nparallel backup with \n 4 worker\n% performance \n increased/decreased\n compare to normal \n backup\n (without patch)\nparallel backup with \n 8 worker\n% performance \n increased/decreased\n compare to normal \n backup\n (without patch)\n\n\n10\n GB \n (10 tables - each table around 1.05 GB)\nreal 0m27.016s\n user 0m3.378s\n sys 0m23.059s\nreal 0m30.314s\n user 0m3.575s\n sys 0m22.946s\n12% performance \n decreased\nreal 0m20.400s\n user 0m3.622s\n sys 0m29.670s\n27% performace\n increased\nreal 0m15.331s\n user 0m3.706s\n sys 0m39.189s\n43% performance\n increased\nreal 0m15.094s\n user 0m3.915s\n sys 1m23.350s\n44% performace\n increased.\n\n\n50GB\n (50 tables - each table around 1.05 GB)\nreal 2m11.049s\n user 0m16.464s\n sys 2m1.757s\nreal 2m26.621s\n user 0m18.497s\n sys 2m4.792s\n21% performance\n decreased\nreal 1m9.581s\n user 0m18.298s\n sys 2m12.030s\n46% performance\n increased\nreal 0m53.894s\n user 0m18.588s\n sys 2m47.390s\n58% performance\n increased.\nreal 0m55.373s\n user 0m18.423s\n sys 5m57.470s\n57% performance\n increased.\n\n\n100GB\n (100 tables - each table around 1.05 GB)\nreal 4m4.776s\n user 0m33.699s\n sys 3m27.777s\nreal 4m20.862s\n user 0m35.753s\n sys 3m28.262s\n6% performance\n decreased\nreal 2m37.411s\n user 0m36.440s\n sys 4m16.424s\"\n35% performance\n increased\nreal 1m49.503s\n user 0m37.200s\n sys 5m58.077s\n55% performace\n increased\nreal 1m36.762s\n user 0m36.987s\n sys 9m36.906s\n60% performace\n increased.\n\n\n200GB\n (200 tables - each table around 1.05 GB)\nreal 10m34.998s\n user 1m8.471s\n sys 7m21.520s\nreal 11m30.899s\n user 1m12.933s\n sys 8m14.496s\n8% performance\n decreased\nreal 6m8.481s\n user 1m13.771s\n sys 9m31.216s\n41% performance\n increased\nreal 4m2.403s\n user 1m18.331s\n sys 12m29.661s\n61% performance\n increased\nreal 4m3.768s\n user 1m24.547s\n sys 15m21.421s\n61% performance\n increased\n\n\n\n\n\nResults for the remote test: \n\n\n\n\n\n\nData\n size\nwithout paralle backup \n patch\nparallel backup with \n 1 worker\n% performance \n increased/decreased\n compare to normal \n backup\n (without patch)\nparallel backup with \n 2 worker\n% performance \n increased/decreased\n compare to normal \n backup\n (without patch)\nparallel backup with \n 4 worker\n% performance \n increased/decreased\n compare to normal \n backup\n (without patch)\nparallel backup with \n 8 worker\n% performance \n increased/decreased\n compare to normal \n backup\n (without patch)\n\n\n10\n GB \n (10 tables - each table around 1.05 GB)\nreal 1m36.829s\n user 0m2.124s\n sys 0m14.004s\nreal 1m37.598s\n user 0m3.272s\n sys 0m11.110s\n0.8% performance\n decreased\nreal 1m36.753s\n user 0m2.627s\n sys 0m15.312s\n0.08% performance\n increased.\nreal 1m37.212s\n user 0m3.835s\n sys 0m13.221s\n0.3% performance\n decreased.\nreal 1m36.977s\n user 0m4.475s\n sys 0m17.937s\n0.1% perfomance\n decreased.\n\n\n50GB\n (50 tables - each table around 1.05 GB)\nreal 7m54.211s\n user 0m10.826s\n sys 1m10.435s\nreal 7m55.603s\n user 0m16.535s\n sys 1m8.147s\n0.2% performance\n decreased\nreal 7m53.499s\n user 0m18.131s\n sys 1m8.822s\n0.1% performance\n increased.\nreal 7m54.687s\n user 0m15.818s\n sys 1m30.991s\n0.1% performance\n decreased\nreal 7m54.658s\n user 0m20.783s\n sys 1m34.460s\n0.1% performance\n decreased\n\n\n100GB\n (100 tables - each table around 1.05 GB)\nreal 15m45.776s\n user 0m21.802s\n sys 2m59.006s\nreal 15m46.315s\n user 0m32.499s\n sys 2m47.245s\n0.05% performance\n decreased\nreal 15m46.065s\n user 0m28.877s\n sys 2m21.181s\n0.03% performacne\n drcreased\nreal 15m47.793s\n user 0m30.932s\n sys 2m36.708s\n0.2% performance\n decresed\nreal 15m47.129s\n user 0m35.151s\n sys 3m23.572s\n0.14% performance\n decreased.\n\n\n200GB\n (200 tables - each table around 1.05 GB)\nreal 32m55.720s\n user 0m50.602s\n sys 5m38.875s\nreal 31m30.602s\n user 0m45.377s\n sys 4m57.405s\n4% performance\n increased\nreal 31m30.214s\n user 0m55.023s\n sys 5m8.689s\n4% performance\n increased\nreal 31m31.187s\n user 1m13.390s\n sys 5m40.861s\n4% performance\n increased\nreal 31m31.729s\n user 1m4.955s\n sys 6m35.774s\n4% performance\n decreased\n\n\n\n\n\n\n\n\n\nClient &\n Server on the same machine, the result shows\n around 50% improvement in parallel run with\n worker 4 and 8.  We don’t see the huge\n performance improvement with more workers\n been added.\n\n\nWhereas, when the\n client and server on a different machine, we\n don’t see any major benefit in\n performance.  This testing result\n matches the testing results posted by David\n Zhang up thread.\n\n\n\n\nWe ran the test\n for 100GB backup with parallel worker 4 to\n see the CPU usage and other information.\n What we noticed is that server is consuming\n the CPU almost 100% whole the time and\n pg_stat_activity shows that server is busy\n with ClientWrite most of the time.\n\n\nAttaching\n captured output for\n1) Top command\n output on the server after every 5 second\n2)\n pg_stat_activity output after every 5 second\n3) Top command\n output on the client after every 5 second\n\n\nDo\n let me know if anyone has further\n questions/inputs for the benchmarking. \n\n\n\n\nThanks to Rushabh Lathia for helping me with\n this testing.\n\n\n\n\n\nOn Tue, Apr 28, 2020\n at 8:46 AM Amit Kapila <amit.kapila16@gmail.com>\n wrote:\n\nOn\n Mon, Apr 27, 2020 at 10:23 PM David Zhang <david.zhang@highgo.ca>\n wrote:\n >\n > Hi,\n >\n > Here is the parallel backup performance test\n results with and without\n > the patch \"parallel_backup_v15\" on AWS cloud\n environment. Two\n > \"t2.xlarge\" machines were used: one for\n Postgres server and the other\n > one for pg_basebackup with the same machine\n configuration showing below.\n >\n > Machine configuration:\n >      Instance Type        :t2.xlarge\n >      Volume type          :io1\n >      Memory (MiB)         :16GB\n >      vCPU #               :4\n >      Architecture         :x86_64\n >      IOP                  :6000\n >      Database Size (GB)   :108\n >\n > Performance test results:\n > without patch:\n >      real 18m49.346s\n >      user 1m24.178s\n >      sys 7m2.966s\n >\n > 1 worker with patch:\n >      real 18m43.201s\n >      user 1m55.787s\n >      sys 7m24.724s\n >\n > 2 worker with patch:\n >      real 18m47.373s\n >      user 2m22.970s\n >      sys 11m23.891s\n >\n > 4 worker with patch:\n >      real 18m46.878s\n >      user 2m26.791s\n >      sys 13m14.716s\n >\n > As required, I didn't have the pgbench running\n in parallel like we did\n > in the previous benchmark.\n >\n\n So, there doesn't seem to be any significant\n improvement in this\n scenario.  Now, it is not clear why there was a\n significant\n improvement in the previous run where pgbench was\n also running\n simultaneously.  I am not sure but maybe it is\n because when a lot of\n other backends were running (performing read-only\n workload) the\n backend that was responsible for doing backup was\n getting frequently\n scheduled out and it slowed down the overall backup\n process.  And when\n we start using multiple backends for backup one or\n other backup\n process is always running making the overall backup\n faster.  One idea\n to find this out is to check how much time backup\n takes when we run it\n with and without pgbench workload on HEAD (aka\n unpatched code).  Even\n if what I am saying is true or there is some other\n reason due to which\n we are seeing speedup in some cases (where there is\n a concurrent\n workload), it might not make the case for using\n multiple backends for\n backup but still, it is good to find that\n information as it might help\n in designing this feature better.\n\n > The perf report files for both Postgres server\n and pg_basebackup sides\n > are attached.\n >\n\n It is not clear which functions are taking more time\n or for which\n functions time is reduced as function symbols are\n not present in the\n reports.  I think you can refer\n \"https://wiki.postgresql.org/wiki/Profiling_with_perf\"\n to see how to\n take profiles and additionally use\n -fno-omit-frame-pointer during\n configure (you can use\n CFLAGS=\"-fno-omit-frame-pointer during\n configure).\n\n\n -- \n With Regards,\n Amit Kapila.\n EnterpriseDB: http://www.enterprisedb.com\n\n\n\n\n\n\n\n -- \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n--\n \n\n\nThanks\n &\n Regards, \nSuraj\n kharage, \nEnterpriseDB\n Corporation, \nThe\n Postgres\n Database\n Company.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n-- \n David\n\n Software Engineer\n Highgo Software Inc. (Canada)\nwww.highgo.ca\n\n\n\n\n\n\n-- \n David\n\n Software Engineer\n Highgo Software Inc. (Canada)\nwww.highgo.ca", "msg_date": "Thu, 30 Apr 2020 11:18:18 -0700", "msg_from": "David Zhang <david.zhang@highgo.ca>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Apr 30, 2020 at 4:15 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n\n> On Wed, Apr 29, 2020 at 6:11 PM Suraj Kharage\n> <suraj.kharage@enterprisedb.com> wrote:\n> >\n> > Hi,\n> >\n> > We at EnterpriseDB did some performance testing around this parallel\n> backup to check how this is beneficial and below are the results. In this\n> testing, we run the backup -\n> > 1) Without Asif’s patch\n> > 2) With Asif’s patch and combination of workers 1,2,4,8.\n> >\n> > We run those test on two setup\n> >\n> > 1) Client and Server both on the same machine (Local backups)\n> >\n> > 2) Client and server on a different machine (remote backups)\n> >\n> >\n> > Machine details:\n> >\n> > 1: Server (on which local backups performed and used as server for\n> remote backups)\n> >\n> > 2: Client (Used as a client for remote backups)\n> >\n> >\n> ...\n> >\n> >\n> > Client & Server on the same machine, the result shows around 50%\n> improvement in parallel run with worker 4 and 8. We don’t see the huge\n> performance improvement with more workers been added.\n> >\n> >\n> > Whereas, when the client and server on a different machine, we don’t see\n> any major benefit in performance. This testing result matches the testing\n> results posted by David Zhang up thread.\n> >\n> >\n> >\n> > We ran the test for 100GB backup with parallel worker 4 to see the CPU\n> usage and other information. What we noticed is that server is consuming\n> the CPU almost 100% whole the time and pg_stat_activity shows that server\n> is busy with ClientWrite most of the time.\n> >\n> >\n>\n> Was this for a setup where the client and server were on the same\n> machine or where the client was on a different machine? If it was for\n> the case where both are on the same machine, then ideally, we should\n> see ClientRead events in a similar proportion?\n>\n\nIn the particular setup, the client and server were on different machines.\n\n\n> During an offlist discussion with Robert, he pointed out that current\n> basebackup's code doesn't account for the wait event for the reading\n> of files which can change what pg_stat_activity shows? Can you please\n> apply his latest patch to improve basebackup.c's code [1] which will\n> take care of that waitevent before getting the data again?\n>\n> [1] -\n> https://www.postgresql.org/message-id/CA%2BTgmobBw-3573vMosGj06r72ajHsYeKtksT_oTxH8XvTL7DxA%40mail.gmail.com\n>\n\n\nSure, we can try out this and do a similar run to collect the\npg_stat_activity output.\n\n\n> --\n> With Regards,\n> Amit Kapila.\n> EnterpriseDB: http://www.enterprisedb.com\n>\n>\n>\n\n-- \nRushabh Lathia\n\nOn Thu, Apr 30, 2020 at 4:15 PM Amit Kapila <amit.kapila16@gmail.com> wrote:On Wed, Apr 29, 2020 at 6:11 PM Suraj Kharage\n<suraj.kharage@enterprisedb.com> wrote:\n>\n> Hi,\n>\n> We at EnterpriseDB did some performance testing around this parallel backup to check how this is beneficial and below are the results. In this testing, we run the backup -\n> 1) Without Asif’s patch\n> 2) With Asif’s patch and combination of workers 1,2,4,8.\n>\n> We run those test on two setup\n>\n> 1) Client and Server both on the same machine (Local backups)\n>\n> 2) Client and server on a different machine (remote backups)\n>\n>\n> Machine details:\n>\n> 1: Server (on which local backups performed and used as server for remote backups)\n>\n> 2: Client (Used as a client for remote backups)\n>\n>\n...\n>\n>\n> Client & Server on the same machine, the result shows around 50% improvement in parallel run with worker 4 and 8.  We don’t see the huge performance improvement with more workers been added.\n>\n>\n> Whereas, when the client and server on a different machine, we don’t see any major benefit in performance.  This testing result matches the testing results posted by David Zhang up thread.\n>\n>\n>\n> We ran the test for 100GB backup with parallel worker 4 to see the CPU usage and other information. What we noticed is that server is consuming the CPU almost 100% whole the time and pg_stat_activity shows that server is busy with ClientWrite most of the time.\n>\n>\n\nWas this for a setup where the client and server were on the same\nmachine or where the client was on a different machine?  If it was for\nthe case where both are on the same machine, then ideally, we should\nsee ClientRead events in a similar proportion?In the particular setup, the client and server were on different machines. During an offlist discussion with Robert, he pointed out that currentbasebackup's code doesn't account for the wait event for the readingof files which can change what pg_stat_activity shows?  Can you pleaseapply his latest patch to improve basebackup.c's code [1] which willtake care of that waitevent before getting the data again?[1] - https://www.postgresql.org/message-id/CA%2BTgmobBw-3573vMosGj06r72ajHsYeKtksT_oTxH8XvTL7DxA%40mail.gmail.comSure, we can try out this and do a similar run to collect the pg_stat_activity output. \n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n-- Rushabh Lathia", "msg_date": "Mon, 4 May 2020 18:52:37 +0530", "msg_from": "Rushabh Lathia <rushabh.lathia@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, May 4, 2020 at 6:22 PM Rushabh Lathia <rushabh.lathia@gmail.com>\nwrote:\n\n>\n>\n> On Thu, Apr 30, 2020 at 4:15 PM Amit Kapila <amit.kapila16@gmail.com>\n> wrote:\n>\n>> On Wed, Apr 29, 2020 at 6:11 PM Suraj Kharage\n>> <suraj.kharage@enterprisedb.com> wrote:\n>> >\n>> > Hi,\n>> >\n>> > We at EnterpriseDB did some performance testing around this parallel\n>> backup to check how this is beneficial and below are the results. In this\n>> testing, we run the backup -\n>> > 1) Without Asif’s patch\n>> > 2) With Asif’s patch and combination of workers 1,2,4,8.\n>> >\n>> > We run those test on two setup\n>> >\n>> > 1) Client and Server both on the same machine (Local backups)\n>> >\n>> > 2) Client and server on a different machine (remote backups)\n>> >\n>> >\n>> > Machine details:\n>> >\n>> > 1: Server (on which local backups performed and used as server for\n>> remote backups)\n>> >\n>> > 2: Client (Used as a client for remote backups)\n>> >\n>> >\n>> ...\n>> >\n>> >\n>> > Client & Server on the same machine, the result shows around 50%\n>> improvement in parallel run with worker 4 and 8. We don’t see the huge\n>> performance improvement with more workers been added.\n>> >\n>> >\n>> > Whereas, when the client and server on a different machine, we don’t\n>> see any major benefit in performance. This testing result matches the\n>> testing results posted by David Zhang up thread.\n>> >\n>> >\n>> >\n>> > We ran the test for 100GB backup with parallel worker 4 to see the CPU\n>> usage and other information. What we noticed is that server is consuming\n>> the CPU almost 100% whole the time and pg_stat_activity shows that server\n>> is busy with ClientWrite most of the time.\n>> >\n>> >\n>>\n>> Was this for a setup where the client and server were on the same\n>> machine or where the client was on a different machine? If it was for\n>> the case where both are on the same machine, then ideally, we should\n>> see ClientRead events in a similar proportion?\n>>\n>\n> In the particular setup, the client and server were on different machines.\n>\n>\n>> During an offlist discussion with Robert, he pointed out that current\n>> basebackup's code doesn't account for the wait event for the reading\n>> of files which can change what pg_stat_activity shows? Can you please\n>> apply his latest patch to improve basebackup.c's code [1] which will\n>> take care of that waitevent before getting the data again?\n>>\n>> [1] -\n>> https://www.postgresql.org/message-id/CA%2BTgmobBw-3573vMosGj06r72ajHsYeKtksT_oTxH8XvTL7DxA%40mail.gmail.com\n>>\n>\n>\n> Sure, we can try out this and do a similar run to collect the\n> pg_stat_activity output.\n>\n\nHave you had the chance to try this out?\n\n\n>\n>\n>> --\n>> With Regards,\n>> Amit Kapila.\n>> EnterpriseDB: http://www.enterprisedb.com\n>>\n>>\n>>\n>\n> --\n> Rushabh Lathia\n>\n\n\n-- \nHighgo Software (Canada/China/Pakistan)\nURL : http://www.highgo.ca\nADDR: 10318 WHALLEY BLVD, Surrey, BC\nEMAIL: mailto: ahsan.hadi@highgo.ca\n\nOn Mon, May 4, 2020 at 6:22 PM Rushabh Lathia <rushabh.lathia@gmail.com> wrote:On Thu, Apr 30, 2020 at 4:15 PM Amit Kapila <amit.kapila16@gmail.com> wrote:On Wed, Apr 29, 2020 at 6:11 PM Suraj Kharage\n<suraj.kharage@enterprisedb.com> wrote:\n>\n> Hi,\n>\n> We at EnterpriseDB did some performance testing around this parallel backup to check how this is beneficial and below are the results. In this testing, we run the backup -\n> 1) Without Asif’s patch\n> 2) With Asif’s patch and combination of workers 1,2,4,8.\n>\n> We run those test on two setup\n>\n> 1) Client and Server both on the same machine (Local backups)\n>\n> 2) Client and server on a different machine (remote backups)\n>\n>\n> Machine details:\n>\n> 1: Server (on which local backups performed and used as server for remote backups)\n>\n> 2: Client (Used as a client for remote backups)\n>\n>\n...\n>\n>\n> Client & Server on the same machine, the result shows around 50% improvement in parallel run with worker 4 and 8.  We don’t see the huge performance improvement with more workers been added.\n>\n>\n> Whereas, when the client and server on a different machine, we don’t see any major benefit in performance.  This testing result matches the testing results posted by David Zhang up thread.\n>\n>\n>\n> We ran the test for 100GB backup with parallel worker 4 to see the CPU usage and other information. What we noticed is that server is consuming the CPU almost 100% whole the time and pg_stat_activity shows that server is busy with ClientWrite most of the time.\n>\n>\n\nWas this for a setup where the client and server were on the same\nmachine or where the client was on a different machine?  If it was for\nthe case where both are on the same machine, then ideally, we should\nsee ClientRead events in a similar proportion?In the particular setup, the client and server were on different machines. During an offlist discussion with Robert, he pointed out that currentbasebackup's code doesn't account for the wait event for the readingof files which can change what pg_stat_activity shows?  Can you pleaseapply his latest patch to improve basebackup.c's code [1] which willtake care of that waitevent before getting the data again?[1] - https://www.postgresql.org/message-id/CA%2BTgmobBw-3573vMosGj06r72ajHsYeKtksT_oTxH8XvTL7DxA%40mail.gmail.comSure, we can try out this and do a similar run to collect the pg_stat_activity output.Have you had the chance to try this out?  \n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n-- Rushabh Lathia\n-- Highgo Software (Canada/China/Pakistan)URL : http://www.highgo.caADDR: 10318 WHALLEY BLVD, Surrey, BCEMAIL: mailto: ahsan.hadi@highgo.ca", "msg_date": "Thu, 21 May 2020 10:17:29 +0500", "msg_from": "Ahsan Hadi <ahsan.hadi@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, May 21, 2020 at 10:47 AM Ahsan Hadi <ahsan.hadi@gmail.com> wrote:\n\n>\n>\n> On Mon, May 4, 2020 at 6:22 PM Rushabh Lathia <rushabh.lathia@gmail.com>\n> wrote:\n>\n>>\n>>\n>> On Thu, Apr 30, 2020 at 4:15 PM Amit Kapila <amit.kapila16@gmail.com>\n>> wrote:\n>>\n>>> On Wed, Apr 29, 2020 at 6:11 PM Suraj Kharage\n>>> <suraj.kharage@enterprisedb.com> wrote:\n>>> >\n>>> > Hi,\n>>> >\n>>> > We at EnterpriseDB did some performance testing around this parallel\n>>> backup to check how this is beneficial and below are the results. In this\n>>> testing, we run the backup -\n>>> > 1) Without Asif’s patch\n>>> > 2) With Asif’s patch and combination of workers 1,2,4,8.\n>>> >\n>>> > We run those test on two setup\n>>> >\n>>> > 1) Client and Server both on the same machine (Local backups)\n>>> >\n>>> > 2) Client and server on a different machine (remote backups)\n>>> >\n>>> >\n>>> > Machine details:\n>>> >\n>>> > 1: Server (on which local backups performed and used as server for\n>>> remote backups)\n>>> >\n>>> > 2: Client (Used as a client for remote backups)\n>>> >\n>>> >\n>>> ...\n>>> >\n>>> >\n>>> > Client & Server on the same machine, the result shows around 50%\n>>> improvement in parallel run with worker 4 and 8. We don’t see the huge\n>>> performance improvement with more workers been added.\n>>> >\n>>> >\n>>> > Whereas, when the client and server on a different machine, we don’t\n>>> see any major benefit in performance. This testing result matches the\n>>> testing results posted by David Zhang up thread.\n>>> >\n>>> >\n>>> >\n>>> > We ran the test for 100GB backup with parallel worker 4 to see the CPU\n>>> usage and other information. What we noticed is that server is consuming\n>>> the CPU almost 100% whole the time and pg_stat_activity shows that server\n>>> is busy with ClientWrite most of the time.\n>>> >\n>>> >\n>>>\n>>> Was this for a setup where the client and server were on the same\n>>> machine or where the client was on a different machine? If it was for\n>>> the case where both are on the same machine, then ideally, we should\n>>> see ClientRead events in a similar proportion?\n>>>\n>>\n>> In the particular setup, the client and server were on different\n>> machines.\n>>\n>>\n>>> During an offlist discussion with Robert, he pointed out that current\n>>> basebackup's code doesn't account for the wait event for the reading\n>>> of files which can change what pg_stat_activity shows? Can you please\n>>> apply his latest patch to improve basebackup.c's code [1] which will\n>>> take care of that waitevent before getting the data again?\n>>>\n>>> [1] -\n>>> https://www.postgresql.org/message-id/CA%2BTgmobBw-3573vMosGj06r72ajHsYeKtksT_oTxH8XvTL7DxA%40mail.gmail.com\n>>>\n>>\n>>\n>> Sure, we can try out this and do a similar run to collect the\n>> pg_stat_activity output.\n>>\n>\n> Have you had the chance to try this out?\n>\n\nYes. My colleague Suraj tried this and here are the pg_stat_activity output\nfiles.\n\nCaptured wait events after every 3 seconds during the backup for -\n1: parallel backup for 100GB data with 4 workers\n(pg_stat_activity_normal_backup_100GB.txt)\n2: Normal backup (without parallel backup patch) for 100GB data\n(pg_stat_activity_j4_100GB.txt)\n\nHere is the observation:\n\nThe total number of events (pg_stat_activity) captured during above runs:\n- 314 events for normal backups\n- 316 events for parallel backups (-j 4)\n\nBaseBackupRead wait event numbers: (newly added)\n37 - in normal backups\n25 - in the parallel backup (-j 4)\n\nClientWrite wait event numbers:\n175 - in normal backup\n1098 - in parallel backups\n\nClientRead wait event numbers:\n0 - ClientRead in normal backup\n326 - ClientRead in parallel backups for diff processes. (all in idle state)\n\n\n\n\nThanks,\nRushabh Lathia\nwww.EnterpriseDB.com", "msg_date": "Thu, 21 May 2020 11:36:23 +0530", "msg_from": "Rushabh Lathia <rushabh.lathia@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, May 21, 2020 at 11:36 AM Rushabh Lathia\n<rushabh.lathia@gmail.com> wrote:\n>\n> On Thu, May 21, 2020 at 10:47 AM Ahsan Hadi <ahsan.hadi@gmail.com> wrote:\n>>\n>>>>\n>>>> During an offlist discussion with Robert, he pointed out that current\n>>>> basebackup's code doesn't account for the wait event for the reading\n>>>> of files which can change what pg_stat_activity shows? Can you please\n>>>> apply his latest patch to improve basebackup.c's code [1] which will\n>>>> take care of that waitevent before getting the data again?\n>>>>\n>>>> [1] - https://www.postgresql.org/message-id/CA%2BTgmobBw-3573vMosGj06r72ajHsYeKtksT_oTxH8XvTL7DxA%40mail.gmail.com\n>>>\n>>>\n>>>\n>>> Sure, we can try out this and do a similar run to collect the pg_stat_activity output.\n>>\n>>\n>> Have you had the chance to try this out?\n>\n>\n> Yes. My colleague Suraj tried this and here are the pg_stat_activity output files.\n>\n> Captured wait events after every 3 seconds during the backup for -\n> 1: parallel backup for 100GB data with 4 workers (pg_stat_activity_normal_backup_100GB.txt)\n> 2: Normal backup (without parallel backup patch) for 100GB data (pg_stat_activity_j4_100GB.txt)\n>\n> Here is the observation:\n>\n> The total number of events (pg_stat_activity) captured during above runs:\n> - 314 events for normal backups\n> - 316 events for parallel backups (-j 4)\n>\n> BaseBackupRead wait event numbers: (newly added)\n> 37 - in normal backups\n> 25 - in the parallel backup (-j 4)\n>\n> ClientWrite wait event numbers:\n> 175 - in normal backup\n> 1098 - in parallel backups\n>\n> ClientRead wait event numbers:\n> 0 - ClientRead in normal backup\n> 326 - ClientRead in parallel backups for diff processes. (all in idle state)\n>\n\nIt might be interesting to see why ClientRead/ClientWrite has\nincreased so much and can we reduce it?\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 21 May 2020 12:23:56 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, May 21, 2020 at 2:06 AM Rushabh Lathia <rushabh.lathia@gmail.com> wrote:\n> Yes. My colleague Suraj tried this and here are the pg_stat_activity output files.\n>\n> Captured wait events after every 3 seconds during the backup for -\n> 1: parallel backup for 100GB data with 4 workers (pg_stat_activity_normal_backup_100GB.txt)\n> 2: Normal backup (without parallel backup patch) for 100GB data (pg_stat_activity_j4_100GB.txt)\n>\n> Here is the observation:\n>\n> The total number of events (pg_stat_activity) captured during above runs:\n> - 314 events for normal backups\n> - 316 events for parallel backups (-j 4)\n>\n> BaseBackupRead wait event numbers: (newly added)\n> 37 - in normal backups\n> 25 - in the parallel backup (-j 4)\n>\n> ClientWrite wait event numbers:\n> 175 - in normal backup\n> 1098 - in parallel backups\n>\n> ClientRead wait event numbers:\n> 0 - ClientRead in normal backup\n> 326 - ClientRead in parallel backups for diff processes. (all in idle state)\n\nSo, basically, when we go from 1 process to 4, the additional\nprocesses spend all of their time waiting rather than doing any useful\nwork, and that's why there is no performance benefit. Presumably, the\nreason they spend all their time waiting for ClientRead/ClientWrite is\nbecause the network between the two machines is saturated, so adding\nmore processes that are trying to use it at maximum speed just leads\nto spending more time waiting for it to be available.\n\nDo we have the same results for the local backup case, where the patch helped?\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 21 May 2020 09:41:54 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, May 21, 2020 at 7:12 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n>\n> So, basically, when we go from 1 process to 4, the additional\n> processes spend all of their time waiting rather than doing any useful\n> work, and that's why there is no performance benefit. Presumably, the\n> reason they spend all their time waiting for ClientRead/ClientWrite is\n> because the network between the two machines is saturated, so adding\n> more processes that are trying to use it at maximum speed just leads\n> to spending more time waiting for it to be available.\n>\n> Do we have the same results for the local backup case, where the patch\n> helped?\n>\n\nHere is the result for local backup case (100GB data). Attaching the\ncaptured logs.\n\nThe total number of events (pg_stat_activity) captured during local runs:\n- 82 events for normal backups\n- 31 events for parallel backups (-j 4)\n\nBaseBackupRead wait event numbers: (newly added)\n24 - in normal backups\n14 - in parallel backup (-j 4)\n\nClientWrite wait event numbers:\n8 - in normal backup\n43 - in parallel backups\n\nClientRead wait event numbers:\n0 - ClientRead in normal backup\n32 - ClientRead in parallel backups for diff processes.\n\n\n-- \n--\n\nThanks & Regards,\nSuraj kharage,\nEnterpriseDB Corporation,\nThe Postgres Database Company.", "msg_date": "Fri, 22 May 2020 11:33:29 +0530", "msg_from": "Suraj Kharage <suraj.kharage@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "As far I understand, parallel backup is not a mandatory performance\nfeature, rather, one at user's discretion. This IMHO indicates that it will\nbenefit some users and it may not others.\n\nTaking a backup is an I/O intensive workload. So by parallelizing it\nthrough multiple worker threads/processes, creates an overhead of its own.\nSo what precisely are we optimizing here. Looking at a running database\nsystem in any environment, I see the following potential scenarios playing\nout. These are probably clear to everyone here, but I'm listing these for\ncompleteness and clarity.\n\nLocally Running Backup:\n(1) Server has no clients connected other than base backup.\n(2) Server has other clients connected which are actively performing\noperations causing disk I/O.\n\nRemotely Running Backup:\n(3) Server has no clients connected other than remote base backup.\n(4) Server has other clients connected which are actively performing\noperations causing disk I/O.\n\nOthers:\n(5) Server or the system running base backup has other processes competing\nfor disk or network bandwidth.\n\nGenerally speaking, I see that parallelization could potentially benefit in\nscenarios (2), (4) and (5) with the reason being that having more than one\nthread increases the likelihood that backup will now get a bigger time\nslice for disk I/O and network bandwidth. With (1) and (3), since there are\nno competing processes, addition of multiple threads or processes will only\nincrease CPU overhead whilst still getting the same network and disk time\nslice. In this particular case, the performance will degrade.\n\nIMHO, that’s why by adding other load on the server, perhaps by running\npgbench simultaneously may show improved performance for parallel backup.\nAlso, running parallel backup on a local laptop more often than yields\nimproved performance.\n\nThere are obviously other factors that may impact the performance like the\ntype of I/O scheduler being used whether CFQ or some other.\n\nIMHO, parallel backup has obvious performance benefits, but we need to\nensure that users understand that there is potential for slower backup if\nthere is no competition for resources.\n\n\n\nOn Fri, May 22, 2020 at 11:03 AM Suraj Kharage <\nsuraj.kharage@enterprisedb.com> wrote:\n\n>\n> On Thu, May 21, 2020 at 7:12 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n>>\n>> So, basically, when we go from 1 process to 4, the additional\n>> processes spend all of their time waiting rather than doing any useful\n>> work, and that's why there is no performance benefit. Presumably, the\n>> reason they spend all their time waiting for ClientRead/ClientWrite is\n>> because the network between the two machines is saturated, so adding\n>> more processes that are trying to use it at maximum speed just leads\n>> to spending more time waiting for it to be available.\n>>\n>> Do we have the same results for the local backup case, where the patch\n>> helped?\n>>\n>\n> Here is the result for local backup case (100GB data). Attaching the\n> captured logs.\n>\n> The total number of events (pg_stat_activity) captured during local runs:\n> - 82 events for normal backups\n> - 31 events for parallel backups (-j 4)\n>\n> BaseBackupRead wait event numbers: (newly added)\n> 24 - in normal backups\n> 14 - in parallel backup (-j 4)\n>\n> ClientWrite wait event numbers:\n> 8 - in normal backup\n> 43 - in parallel backups\n>\n> ClientRead wait event numbers:\n> 0 - ClientRead in normal backup\n> 32 - ClientRead in parallel backups for diff processes.\n>\n>\n> --\n> --\n>\n> Thanks & Regards,\n> Suraj kharage,\n> EnterpriseDB Corporation,\n> The Postgres Database Company.\n>\n\n\n-- \nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\nADDR: 10318 WHALLEY BLVD, Surrey, BC\nCELL:+923335449950 EMAIL: mailto:hamid.akhtar@highgo.ca\nSKYPE: engineeredvirus\n\nAs far I understand, parallel backup is not a mandatory performance feature, rather, one at user's discretion. This IMHO indicates that it will benefit some users and it may not others.Taking a backup is an I/O intensive workload. So by parallelizing it through multiple worker threads/processes, creates an overhead of its own. So what precisely are we optimizing here. Looking at a running database system in any environment, I see the following potential scenarios playing out. These are probably clear to everyone here, but I'm listing these for completeness and clarity.Locally Running Backup:(1) Server has no clients connected other than base backup.(2) Server has other clients connected which are actively performing operations causing disk I/O.Remotely Running Backup:(3) Server has no clients connected other than remote base backup.(4) Server has other clients connected which are actively performing operations causing disk I/O.Others:(5) Server or the system running base backup has other processes competing for disk or network bandwidth.Generally speaking, I see that parallelization could potentially benefit in scenarios (2), (4) and (5) with the reason being that having more than one thread increases the likelihood that backup will now get a bigger time slice for disk I/O and network bandwidth. With (1) and (3), since there are no competing processes, addition of multiple threads or processes will only increase CPU overhead whilst still getting the same network and disk time slice. In this particular case, the performance will degrade.IMHO, that’s why by adding other load on the server, perhaps by running pgbench simultaneously may show improved performance for parallel backup. Also, running parallel backup on a local laptop more often than yields improved performance.There are obviously other factors that may impact the performance like the type of I/O scheduler being used whether CFQ or some other.IMHO, parallel backup has obvious performance benefits, but we need to ensure that users understand that there is potential for slower backup if there is no competition for resources.On Fri, May 22, 2020 at 11:03 AM Suraj Kharage <suraj.kharage@enterprisedb.com> wrote:On Thu, May 21, 2020 at 7:12 PM Robert Haas <robertmhaas@gmail.com> wrote:\nSo, basically, when we go from 1 process to 4, the additional\nprocesses spend all of their time waiting rather than doing any useful\nwork, and that's why there is no performance benefit. Presumably, the\nreason they spend all their time waiting for ClientRead/ClientWrite is\nbecause the network between the two machines is saturated, so adding\nmore processes that are trying to use it at maximum speed just leads\nto spending more time waiting for it to be available.\n\nDo we have the same results for the local backup case, where the patch helped?Here is the result for local backup case (100GB data). Attaching the captured logs.The total number of events (pg_stat_activity) captured during local runs:- 82 events for normal backups- 31 events for parallel backups (-j 4)BaseBackupRead wait event numbers: (newly added)24 - in normal backups14 - in parallel backup (-j 4)ClientWrite wait event numbers:8 - in normal backup43 - in parallel backupsClientRead wait event numbers:0 - ClientRead in normal backup32 - ClientRead in parallel backups for diff processes.-- --Thanks & Regards, Suraj kharage, EnterpriseDB Corporation, The Postgres Database Company.\n-- Highgo Software (Canada/China/Pakistan)URL : www.highgo.caADDR: 10318 WHALLEY BLVD, Surrey, BCCELL:+923335449950  EMAIL: mailto:hamid.akhtar@highgo.caSKYPE: engineeredvirus", "msg_date": "Thu, 11 Jun 2020 22:40:38 +0500", "msg_from": "Hamid Akhtar <hamid.akhtar@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Thu, Jun 11, 2020 at 1:41 PM Hamid Akhtar <hamid.akhtar@gmail.com> wrote:\n> As far I understand, parallel backup is not a mandatory performance feature, rather, one at user's discretion. This IMHO indicates that it will benefit some users and it may not others.\n>\n> IMHO, parallel backup has obvious performance benefits, but we need to ensure that users understand that there is potential for slower backup if there is no competition for resources.\n\nI am sure that nobody is arguing that the patch has to be beneficial\nin all cases in order to justify applying it. However, there are\nseveral good arguments against proceding with this patch:\n\n* Every version of the patch that has been reviewed by anybody has\nbeen riddled with errors. Over and over again, testers have found\nserious bugs, and code reviewers have noticed lots of problems, too.\n\n* This approach requires rewriting a lot of current functionality,\neither by moving it to the client side or by restructuring it to work\nwith parallelism. That's a lot of work, and it seems likely to\ngenerate more work in the future as people continue to add features.\nIt's one thing to add a feature that doesn't benefit everybody; it's\nanother thing to add a feature that doesn't benefit everybody and also\nhinders future development. See\nhttp://postgr.es/m/CA+TgmoZubLXYR+Pd_gi3MVgyv5hQdLm-GBrVXkun-Lewaw12Kg@mail.gmail.com\nfor more discussion of these issues.\n\n* The scenarios in which the patch delivers a performance benefit are\nnarrow and somewhat contrived. In remote backup scenarios, AIUI, the\npatch hasn't been shown to help. In local backups, it does, but how\nlikely is it that you are going to do your local backups over the wire\nprotocol instead of by direct file copy, which is probably much\nfaster? I agree that if your server is overloaded, having multiple\nprocesses competing for the server resources will allow backup to get\na larger slice relative to other things, but that seems like a pretty\nhackish and inefficient solution to that problem. You could also argue\nthat we could provide a feature to prioritize some queries over other\nqueries by running them with tons of parallel workers just to convince\nthe OS to give them more resources, and I guess that would work, but\nit would also waste tons of resources and possibly cripple or even\ncrash your system if you used it enough. The same argument applies\nhere.\n\n* Even when the patch does provide a benefit, it seems to max out at\nabout 2.5X. Clearly it's nice to have something go 2.5X faster, but\nthe point is that it doesn't scale beyond that no matter how many\nworkers you add. That doesn't automatically mean that something is a\nbad idea, but it is a concern. At the very least, we should be able to\nsay why it doesn't scale any better than that.\n\n* Actually, we have some hints about that. Over at\nhttp://postgr.es/m/20200503174922.mfzzdafa5g4rlhez@alap3.anarazel.de\nAndres has shown that too much concurrency when copying files results\nin a dramatic performance reduction, and that a lot of the reason why\nconcurrency helps in the first place has to do with the fact that\npg_basebackup does not have any cache control (no fallocate,\nsync_file_range(WRITE), posix_fadvise(DONTNEED)). When those things\nare added the performance gets better and the benefits of concurrency\nare reduced. I suspect that would also be true for this patch. It\nwould be unreasonable to commit a large patch, especially one that\nwould hinder future development, if we could get the same benefits\nfrom a small patch that would not do so.\n\nI am not in a position to tell you how to spend your time, so you can\ncertainly pursue this patch if you wish. However, I think it's\nprobably not the best use of time. Even if you fixed all the bugs and\nreimplemented all of the functionality that needs reimplementing in\norder to make this approach work, it still doesn't make sense to\ncommit the patch if either (a) we can obtain the same benefit, or most\nof it, from a much simpler patch or (b) the patch is going to make it\nsignificantly harder to develop other features that we want to have,\nespecially if those features seem likely to be more beneficial than\nwhat this patch offers. I think both of those are likely true here.\n\nFor an example of (b), consider compression of tar files on the server\nside before transmission to the client. If you take the approach this\npatch does and move tarfile construction to the client, that is\nimpossible. Now you can argue (and perhaps you will) that this would\njust mean someone has to choose between using this feature and using\nthat feature, and why should users not have such a choice? That is a\nfair argument, but my counter-argument is that users shouldn't be\nforced into making that choice. If the parallel feature is beneficial\nenough to justify having it, then it ought to be designed in such a\nway that it works with the other features we also want to have rather\nthan forcing users to choose between them. Since I have already\nproposed (on the other thread linked above) a design that would make\nthat possible, and this design does not, I have a hard time\nunderstanding why we would pick this one, especially given all of the\nother disadvantages which it seems to have.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 12 Jun 2020 13:28:37 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "> On 12 Jun 2020, at 19:28, Robert Haas <robertmhaas@gmail.com> wrote:\n\n> I am sure that nobody is arguing that the patch has to be beneficial\n> in all cases in order to justify applying it. However, there are\n> several good arguments against proceding with this patch:\n\nThis thread has stalled with no resolution to the raised issues, and the latest\nversion of the patch (v15) posted no longer applies (I only tried 0001 which\nfailed, the green tick in the CFBot is due it mistakenlt thinking an attached\nreport is a patch). I'm marking this patch Returned with Feedback. Please\nopen a new CF entry when there is a new version of the patch.\n\ncheers ./daniel\n\n", "msg_date": "Mon, 6 Jul 2020 14:24:03 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" }, { "msg_contents": "On Mon, Jul 6, 2020 at 5:24 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> > On 12 Jun 2020, at 19:28, Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> > I am sure that nobody is arguing that the patch has to be beneficial\n> > in all cases in order to justify applying it. However, there are\n> > several good arguments against proceding with this patch:\n>\n> This thread has stalled with no resolution to the raised issues, and the\n> latest\n> version of the patch (v15) posted no longer applies (I only tried 0001\n> which\n> failed, the green tick in the CFBot is due it mistakenlt thinking an\n> attached\n> report is a patch). I'm marking this patch Returned with Feedback. Please\n> open a new CF entry when there is a new version of the patch.\n>\n> cheers ./daniel\n\n\nI think this is fair. There are quite a few valid points raised by Robert.\n\n\n-- \nHighgo Software (Canada/China/Pakistan)\nURL : www.highgo.ca\nADDR: 10318 WHALLEY BLVD, Surrey, BC\nCELL:+923335449950 EMAIL: mailto:hamid.akhtar@highgo.ca\nSKYPE: engineeredvirus\n\nOn Mon, Jul 6, 2020 at 5:24 PM Daniel Gustafsson <daniel@yesql.se> wrote:> On 12 Jun 2020, at 19:28, Robert Haas <robertmhaas@gmail.com> wrote:\n\n> I am sure that nobody is arguing that the patch has to be beneficial\n> in all cases in order to justify applying it. However, there are\n> several good arguments against proceding with this patch:\n\nThis thread has stalled with no resolution to the raised issues, and the latest\nversion of the patch (v15) posted no longer applies (I only tried 0001 which\nfailed, the green tick in the CFBot is due it mistakenlt thinking an attached\nreport is a patch).  I'm marking this patch Returned with Feedback.  Please\nopen a new CF entry when there is a new version of the patch.\n\ncheers ./danielI think this is fair. There are quite a few valid points raised by Robert.-- Highgo Software (Canada/China/Pakistan)URL : www.highgo.caADDR: 10318 WHALLEY BLVD, Surrey, BCCELL:+923335449950  EMAIL: mailto:hamid.akhtar@highgo.caSKYPE: engineeredvirus", "msg_date": "Mon, 6 Jul 2020 17:39:08 +0500", "msg_from": "Hamid Akhtar <hamid.akhtar@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP/PoC for parallel backup" } ]
[ { "msg_contents": "Hi, hackers.\n\nOne of our customers complains about slow execution of PL/pgSQL \nfunctions comparing with Oracle.\nSo he wants to compile PL/pgSQL functions (most likely just-in-time \ncompilation).\nCertainly interpreter adds quite large overhead comparing with native \ncode (~10 times) but\nmost of PL/pgSQL functions are just running some SQL queues and \niterating through results.\n\nI can not believe that JIT can significantly speed-up such functions.\nSo I decided to make simple experiment:  I created large enough table \nand implemented functions\nwhich calculates norm of one column in different languages.\n\nResults are frustrating (at least for me):\n\nPL/pgSQL:   29044.361 ms\nC/SPI:          22785.597 ms\nС/coreAPI:     2873.072 ms\nPL/Lua:        33445.520 ms\nSQL:              7397.639 ms (with parallel execution disabled)\n\nThe fact that difference between PL/pgSQL and function implemented in C \nusing SPI is not so large  was expected by me.\nBut why it is more than 3 time slower than correspondent SQL query?\nThe answer seems to be in the third result: the same function in C \nimplemented without SPI (usign table_beginscan/heap_getnext)\nLooks like SPI adds quite significant overhead.\nAnd as far as almost all PL languages are using SPI, them all suffer \nfrom it.\n\nBelow is profile of SPI function execution:\n\n   9.47%  postgres  libc-2.23.so       [.] __memcpy_avx_unaligned\n    9.19%  postgres  spitest.so         [.] spi_norm\n    8.09%  postgres  postgres           [.] AllocSetAlloc\n    4.50%  postgres  postgres           [.] tts_buffer_heap_getsomeattrs\n    4.36%  postgres  postgres           [.] heap_form_tuple\n    3.41%  postgres  postgres           [.] standard_ExecutorRun\n    3.35%  postgres  postgres           [.] ExecScan\n    3.31%  postgres  postgres           [.] palloc0\n    2.41%  postgres  postgres           [.] heapgettup_pagemode\n    2.40%  postgres  postgres           [.] AllocSetReset\n    2.25%  postgres  postgres           [.] PopActiveSnapshot\n    2.17%  postgres  postgres           [.] PortalRunFetch\n    2.16%  postgres  postgres           [.] HeapTupleSatisfiesVisibility\n    1.97%  postgres  libc-2.23.so       [.] __sigsetjmp\n    1.90%  postgres  postgres           [.] _SPI_cursor_operation\n    1.87%  postgres  postgres           [.] AllocSetFree\n    1.86%  postgres  postgres           [.] PortalRunSelect\n    1.79%  postgres  postgres           [.] heap_getnextslot\n    1.75%  postgres  postgres           [.] heap_fill_tuple\n    1.70%  postgres  postgres           [.] spi_dest_startup\n    1.50%  postgres  postgres           [.] spi_printtup\n    1.49%  postgres  postgres           [.] nocachegetattr\n    1.45%  postgres  postgres           [.] MemoryContextDelete\n    1.44%  postgres  postgres           [.] ExecJustAssignScanVar\n    1.38%  postgres  postgres           [.] CreateTupleDescCopy\n    1.33%  postgres  postgres           [.] SPI_getbinval\n    1.30%  postgres  postgres           [.] PushActiveSnapshot\n    1.30%  postgres  postgres           [.] AllocSetContextCreateInternal\n    1.22%  postgres  postgres           [.] heap_compute_data_size\n    1.22%  postgres  postgres           [.] MemoryContextCreate\n    1.14%  postgres  postgres           [.] heapgetpage\n    1.05%  postgres  postgres           [.] palloc\n    1.03%  postgres  postgres           [.] SeqNext\n\nAs you can see, most of the time is spent in allocation and copying memory.\nI wonder if somebody tried to address this problem and are there some \nplans for improving speed of PL/pgSQL and other\nstored languages?\n\nI attached to this mail sources of spi_test extension with my experiments.\nPlease build it and run norm.sql file.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Wed, 21 Aug 2019 19:41:08 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Why overhead of SPI is so large?" }, { "msg_contents": "From: Konstantin Knizhnik [mailto:k.knizhnik@postgrespro.ru]\r\n> PL/pgSQL: 29044.361 ms\r\n> C/SPI: 22785.597 ms\r\n> \r\n> The fact that difference between PL/pgSQL and function implemented in C\r\n> using SPI is not so large was expected by me.\r\n\r\nThis PL/pgSQL overhead is not so significant compared with the three times, but makes me desire some feature like Oracle's ALTER PROCEDURE ... COMPILE; that compiles the PL/SQL logic to native code. I've seen a few dozen percent speed up.\r\n\r\n\r\nRegards\r\nTakayuki Tsunakawa\r\n\r\n", "msg_date": "Thu, 22 Aug 2019 00:27:20 +0000", "msg_from": "\"Tsunakawa, Takayuki\" <tsunakawa.takay@jp.fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: Why overhead of SPI is so large?" }, { "msg_contents": "Hello.\r\n\r\nAt Wed, 21 Aug 2019 19:41:08 +0300, Konstantin Knizhnik <k.knizhnik@postgrespro.ru> wrote in <ed9da20e-01aa-d04b-d085-e6c16b14b9d7@postgrespro.ru>\r\n> Hi, hackers.\r\n> \r\n> One of our customers complains about slow execution of PL/pgSQL\r\n> functions comparing with Oracle.\r\n> So he wants to compile PL/pgSQL functions (most likely just-in-time\r\n> compilation).\r\n> Certainly interpreter adds quite large overhead comparing with native\r\n> code (~10 times) but\r\n> most of PL/pgSQL functions are just running some SQL queues and\r\n> iterating through results.\r\n> \r\n> I can not believe that JIT can significantly speed-up such functions.\r\n> So I decided to make simple experiment:  I created large enough table\r\n> and implemented functions\r\n> which calculates norm of one column in different languages.\r\n> \r\n> Results are frustrating (at least for me):\r\n> \r\n> PL/pgSQL:   29044.361 ms\r\n> C/SPI:          22785.597 ms\r\n> С/coreAPI:     2873.072 ms\r\n> PL/Lua:        33445.520 ms\r\n> SQL:              7397.639 ms (with parallel execution disabled)\r\n> \r\n> The fact that difference between PL/pgSQL and function implemented in\r\n> C using SPI is not so large  was expected by me.\r\n> But why it is more than 3 time slower than correspondent SQL query?\r\n> The answer seems to be in the third result: the same function in C\r\n> implemented without SPI (usign table_beginscan/heap_getnext)\r\n> Looks like SPI adds quite significant overhead.\r\n> And as far as almost all PL languages are using SPI, them all suffer\r\n> from it.\r\n\r\nAs far as looking the attached spitest.c, it seems that the\r\noverhead comes from cursor operation, not from SPI. As far as\r\nspitest.c goes, cursor is useless. \"SQL\" and C/coreAPI seem to\r\nbe scanning over the result from *a single* query. If that's\r\ncorrect, why don't you use SPI_execute() then scan over\r\nSPI_tuptable?\r\n\r\nregards.\r\n\r\n-- \r\nKyotaro Horiguchi\r\nNTT Open Source Software Center\r\n", "msg_date": "Thu, 22 Aug 2019 11:40:30 +0900 (Tokyo Standard Time)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "\n\nOn 22.08.2019 5:40, Kyotaro Horiguchi wrote:\n> Hello.\n>\n> At Wed, 21 Aug 2019 19:41:08 +0300, Konstantin Knizhnik <k.knizhnik@postgrespro.ru> wrote in <ed9da20e-01aa-d04b-d085-e6c16b14b9d7@postgrespro.ru>\n>> Hi, hackers.\n>>\n>> One of our customers complains about slow execution of PL/pgSQL\n>> functions comparing with Oracle.\n>> So he wants to compile PL/pgSQL functions (most likely just-in-time\n>> compilation).\n>> Certainly interpreter adds quite large overhead comparing with native\n>> code (~10 times) but\n>> most of PL/pgSQL functions are just running some SQL queues and\n>> iterating through results.\n>>\n>> I can not believe that JIT can significantly speed-up such functions.\n>> So I decided to make simple experiment:  I created large enough table\n>> and implemented functions\n>> which calculates norm of one column in different languages.\n>>\n>> Results are frustrating (at least for me):\n>>\n>> PL/pgSQL:   29044.361 ms\n>> C/SPI:          22785.597 ms\n>> С/coreAPI:     2873.072 ms\n>> PL/Lua:        33445.520 ms\n>> SQL:              7397.639 ms (with parallel execution disabled)\n>>\n>> The fact that difference between PL/pgSQL and function implemented in\n>> C using SPI is not so large  was expected by me.\n>> But why it is more than 3 time slower than correspondent SQL query?\n>> The answer seems to be in the third result: the same function in C\n>> implemented without SPI (usign table_beginscan/heap_getnext)\n>> Looks like SPI adds quite significant overhead.\n>> And as far as almost all PL languages are using SPI, them all suffer\n>> from it.\n> As far as looking the attached spitest.c, it seems that the\n> overhead comes from cursor operation, not from SPI. As far as\n> spitest.c goes, cursor is useless. \"SQL\" and C/coreAPI seem to\n> be scanning over the result from *a single* query. If that's\n> correct, why don't you use SPI_execute() then scan over\n> SPI_tuptable?\n\nScanned table is very large and doesn't fir in memory.\nThis is why I am using SPI cursors.\nPlease let me know if there is more efficient way to traverse larger \ntable using SPI.\n\n\n>\n> regards.\n>\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Thu, 22 Aug 2019 10:00:18 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "On 22.08.2019 3:27, Tsunakawa, Takayuki wrote:\n> From: Konstantin Knizhnik [mailto:k.knizhnik@postgrespro.ru]\n>> PL/pgSQL: 29044.361 ms\n>> C/SPI: 22785.597 ms\n>>\n>> The fact that difference between PL/pgSQL and function implemented in C\n>> using SPI is not so large was expected by me.\n> This PL/pgSQL overhead is not so significant compared with the three times, but makes me desire some feature like Oracle's ALTER PROCEDURE ... COMPILE; that compiles the PL/SQL logic to native code. I've seen a few dozen percent speed up.\n>\n\nActually my implementation of C/SPI version is not optimal: it is better \nto fetch several records:\n\n     while (true)\n     {\n         SPI_cursor_fetch(portal, true, 100);\n         if (SPI_processed) {\n             for (i = 0; i < SPI_processed; i++) {\n                 HeapTuple spi_tuple = SPI_tuptable->vals[i];\n                 Datum val = SPI_getbinval(spi_tuple, \nSPI_tuptable->tupdesc, 1, &is_null);\n                 double x = DatumGetFloat8(val);\n                 result += x*x;\n                 SPI_freetuple(spi_tuple);\n             }\n             SPI_freetuptable(SPI_tuptable);\n         } else\n             break;\n     }\n\nThis version shows result 9405.694 ms which is comparable with result of \nSQL query.\nUnfortunately (or fortunately) PL/pgSQL is already using prefetch. If it \nis disables (when iterate through explicitly created cursor), time of \nquery execution is increased almost twice (46552.935 ms)\n\nSo PL/SPI ratio is more than three times.\n\nUpdatede results are the following:\n\n\nImpementation\n\ttime (ms)\nPL/Lua \t32220\nPL/pgSQL \t29044\nPL/pgSQL (JIT)\n\t27594\nC/SPI \t  9406\nSQL \t  7399\nSQL (JIT)\n\t  5532\nС/coreAPI \t  2873\n\n-- \n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n\n\n\n\n\n\n\n\nOn 22.08.2019 3:27, Tsunakawa, Takayuki\n wrote:\n\n\nFrom: Konstantin Knizhnik [mailto:k.knizhnik@postgrespro.ru]\n\n\nPL/pgSQL: 29044.361 ms\nC/SPI: 22785.597 ms\n\nThe fact that difference between PL/pgSQL and function implemented in C\nusing SPI is not so large was expected by me.\n\n\n\nThis PL/pgSQL overhead is not so significant compared with the three times, but makes me desire some feature like Oracle's ALTER PROCEDURE ... COMPILE; that compiles the PL/SQL logic to native code. I've seen a few dozen percent speed up.\n\n\n\n\n Actually my implementation of C/SPI version is not optimal: it is\n better to fetch several records:\n\n     while (true)\n     {\n         SPI_cursor_fetch(portal, true, 100);\n         if (SPI_processed) {\n             for (i = 0; i < SPI_processed; i++) {\n                 HeapTuple spi_tuple = SPI_tuptable->vals[i];\n                 Datum val = SPI_getbinval(spi_tuple,\n SPI_tuptable->tupdesc, 1, &is_null);\n                 double x = DatumGetFloat8(val);\n                 result += x*x;\n                 SPI_freetuple(spi_tuple);\n             }\n             SPI_freetuptable(SPI_tuptable);\n         } else\n             break;\n     }\n\n This version shows result 9405.694 ms which is comparable with\n result of SQL query.\n Unfortunately (or fortunately) PL/pgSQL is already using prefetch.\n If it is disables (when iterate through explicitly created cursor),\n time of query execution is increased almost twice (46552.935 ms)\n\n So PL/SPI ratio is more than three times.\n\n Updatede results are the following:\n\n\n\n\n\nImpementation\n\ntime (ms)\n\n\n\nPL/Lua\n32220\n\n\nPL/pgSQL\n29044\n\n\nPL/pgSQL (JIT) \n\n27594\n\n\n\nC/SPI\n  9406\n\n\nSQL\n  7399\n\n\nSQL (JIT)  \n\n  5532\n\n\n\nС/coreAPI\n  2873\n\n\n\n --\n \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 22 Aug 2019 14:11:28 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "Some more information...\nFirst of all I found out that marking PL/pgSQL function as immutable \nsignificantly increase speed of its execution:\n19808 ms vs. 27594. It happens because exec_eval_simple_expr is taken \nsnapshot if function is volatile (default).\nI wonder if PL/pgSQL compiler can detect that evaluated expression \nitself is actually immutable  and there is no need to take snapshot\nfor each invocation of this function. Also I have tried yet another PL \nlanguage - JavaScript, which is now new outsider, despite to the fact that\nv8 JIT compiler is very good.\n\nImplementation\n\ttime (ms)\nPL/v8\n\t41550\nPL/Lua \t32220\nPL/pgSQL \t19808\nC/SPI \t  9406\nSQL \t  7399\nSQL (JIT)\n\t  5532\nС/coreAPI \t  2873\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\n\n Some more information...\n First of all I found out that marking PL/pgSQL function as immutable\n significantly increase speed of its execution: \n 19808 ms vs. 27594. It happens because exec_eval_simple_expr is\n taken snapshot if function is volatile (default).\n I wonder if PL/pgSQL compiler can detect that evaluated expression\n itself is actually immutable  and there is no need to take snapshot\n \n for each invocation of this function. Also I have tried yet another\n PL language - JavaScript, which is now new outsider, despite to the\n fact that \n v8 JIT compiler is very good. \n\n\n\n\nImplementation\n\ntime (ms)\n\n\n\nPL/v8\n\n41550\n\n\n\nPL/Lua\n32220\n\n\nPL/pgSQL\n19808\n\n\nC/SPI\n  9406\n\n\nSQL\n  7399\n\n\nSQL (JIT)  \n\n  5532\n\n\n\nС/coreAPI\n  2873\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 22 Aug 2019 18:51:15 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "čt 22. 8. 2019 v 17:51 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n> Some more information...\n> First of all I found out that marking PL/pgSQL function as immutable\n> significantly increase speed of its execution:\n> 19808 ms vs. 27594. It happens because exec_eval_simple_expr is taken\n> snapshot if function is volatile (default).\n> I wonder if PL/pgSQL compiler can detect that evaluated expression itself\n> is actually immutable and there is no need to take snapshot\n> for each invocation of this function. Also I have tried yet another PL\n> language - JavaScript, which is now new outsider, despite to the fact that\n> v8 JIT compiler is very good.\n>\n\nI have a plan to do some work in this direction. Snapshot is not necessary\nfor almost buildin functions. If expr calls only buildin functions, then\nprobably can be called without snapshot and without any work with plan\ncache.\n\nPavel\n\n>\n> Implementation\n> time (ms)\n> PL/v8\n> 41550\n> PL/Lua 32220\n> PL/pgSQL 19808\n> C/SPI 9406\n> SQL 7399\n> SQL (JIT)\n> 5532\n> С/coreAPI 2873\n>\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\nčt 22. 8. 2019 v 17:51 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n Some more information...\n First of all I found out that marking PL/pgSQL function as immutable\n significantly increase speed of its execution: \n 19808 ms vs. 27594. It happens because exec_eval_simple_expr is\n taken snapshot if function is volatile (default).\n I wonder if PL/pgSQL compiler can detect that evaluated expression\n itself is actually immutable  and there is no need to take snapshot\n \n for each invocation of this function. Also I have tried yet another\n PL language - JavaScript, which is now new outsider, despite to the\n fact that \n v8 JIT compiler is very good. I have a plan to do some work in this direction. Snapshot is not necessary for almost buildin functions. If expr calls only buildin functions, then probably can be called without snapshot and without any work with plan cache.Pavel\n\n\n\n\nImplementation\n\ntime (ms)\n\n\n\nPL/v8\n\n41550\n\n\n\nPL/Lua\n32220\n\n\nPL/pgSQL\n19808\n\n\nC/SPI\n  9406\n\n\nSQL\n  7399\n\n\nSQL (JIT)  \n\n  5532\n\n\n\nС/coreAPI\n  2873\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 22 Aug 2019 17:56:46 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "On 22.08.2019 18:56, Pavel Stehule wrote:\n>\n>\n> čt 22. 8. 2019 v 17:51 odesílatel Konstantin Knizhnik \n> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>\n> Some more information...\n> First of all I found out that marking PL/pgSQL function as\n> immutable significantly increase speed of its execution:\n> 19808 ms vs. 27594. It happens because exec_eval_simple_expr is\n> taken snapshot if function is volatile (default).\n> I wonder if PL/pgSQL compiler can detect that evaluated expression\n> itself is actually immutable  and there is no need to take snapshot\n> for each invocation of this function. Also I have tried yet\n> another PL language - JavaScript, which is now new outsider,\n> despite to the fact that\n> v8 JIT compiler is very good.\n>\n>\n> I have a plan to do some work in this direction. Snapshot is not \n> necessary for almost buildin functions. If expr calls only buildin \n> functions, then probably can be called without snapshot and without \n> any work with plan cache.\n>\n\nI wonder if the following simple patch is correct?\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 23 Aug 2019 12:05:30 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "pá 23. 8. 2019 v 11:05 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 22.08.2019 18:56, Pavel Stehule wrote:\n>\n>\n>\n> čt 22. 8. 2019 v 17:51 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n>\n>> Some more information...\n>> First of all I found out that marking PL/pgSQL function as immutable\n>> significantly increase speed of its execution:\n>> 19808 ms vs. 27594. It happens because exec_eval_simple_expr is taken\n>> snapshot if function is volatile (default).\n>> I wonder if PL/pgSQL compiler can detect that evaluated expression itself\n>> is actually immutable and there is no need to take snapshot\n>> for each invocation of this function. Also I have tried yet another PL\n>> language - JavaScript, which is now new outsider, despite to the fact that\n>> v8 JIT compiler is very good.\n>>\n>\n> I have a plan to do some work in this direction. Snapshot is not necessary\n> for almost buildin functions. If expr calls only buildin functions, then\n> probably can be called without snapshot and without any work with plan\n> cache.\n>\n>\n> I wonder if the following simple patch is correct?\n>\n\nYou cannot to believe to user defined functions so immutable flag is\ncorrect. Only buildin functions are 100% correct.\n\nCREATE OR REPLACE FUNCTION foo()\nRETURNS int AS $$\nSELECT count(*) FROM pg_class;\n$$ LANGUAGE sql IMMUTABLE;\n\nis working.\n\nBut your patch is good enough for benchmarking.\n\nPavel\n\n\n\n>\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\npá 23. 8. 2019 v 11:05 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 22.08.2019 18:56, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\nčt 22. 8. 2019 v 17:51\n odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n Some more information...\n First of all I found out that marking PL/pgSQL function as\n immutable significantly increase speed of its execution: \n 19808 ms vs. 27594. It happens because\n exec_eval_simple_expr is taken snapshot if function is\n volatile (default).\n I wonder if PL/pgSQL compiler can detect that evaluated\n expression itself is actually immutable  and there is no\n need to take snapshot \n for each invocation of this function. Also I have tried\n yet another PL language - JavaScript, which is now new\n outsider, despite to the fact that \n v8 JIT compiler is very good. \n\n\n\n\nI have a plan to do some work in this direction. Snapshot\n is not necessary for almost buildin functions. If expr calls\n only buildin functions, then probably can be called without\n snapshot and without any work with plan cache.\n\n\n\n\n\n\n I wonder if the following simple patch is correct?You cannot to believe to user defined functions so immutable flag is correct. Only buildin functions are 100% correct.CREATE OR REPLACE FUNCTION foo()RETURNS int AS $$SELECT count(*) FROM pg_class;$$ LANGUAGE sql IMMUTABLE;is working.But your patch is good enough for benchmarking.Pavel \n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 23 Aug 2019 11:10:28 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "On 23.08.2019 12:10, Pavel Stehule wrote:\n>\n>\n> pá 23. 8. 2019 v 11:05 odesílatel Konstantin Knizhnik \n> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>\n>\n>\n> On 22.08.2019 18:56, Pavel Stehule wrote:\n>>\n>>\n>> čt 22. 8. 2019 v 17:51 odesílatel Konstantin Knizhnik\n>> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>>\n>> napsal:\n>>\n>> Some more information...\n>> First of all I found out that marking PL/pgSQL function as\n>> immutable significantly increase speed of its execution:\n>> 19808 ms vs. 27594. It happens because exec_eval_simple_expr\n>> is taken snapshot if function is volatile (default).\n>> I wonder if PL/pgSQL compiler can detect that evaluated\n>> expression itself is actually immutable  and there is no need\n>> to take snapshot\n>> for each invocation of this function. Also I have tried yet\n>> another PL language - JavaScript, which is now new outsider,\n>> despite to the fact that\n>> v8 JIT compiler is very good.\n>>\n>>\n>> I have a plan to do some work in this direction. Snapshot is not\n>> necessary for almost buildin functions. If expr calls only\n>> buildin functions, then probably can be called without snapshot\n>> and without any work with plan cache.\n>>\n>\n> I wonder if the following simple patch is correct?\n>\n>\n> You cannot to believe to user defined functions so immutable flag is \n> correct. Only buildin functions are 100% correct.\n>\n> CREATE OR REPLACE FUNCTION foo()\n> RETURNS int AS $$\n> SELECT count(*) FROM pg_class;\n> $$ LANGUAGE sql IMMUTABLE;\n>\n> is working.\n\nBut such definition of the function contradicts IMMUTABLE contract, \ndoesn't it?\nIf creator of the function incorrectly classify it, then usage of such \nfunction can cause incorrect behavior.\nFor example, if function is marked as \"parallel safe\" but actually it is \nnot parallel safe, then using it in parallel plan may cause incorrect \nresults.\nBut it is a reason for disabling parallel plans for all user defined \nfunctions, isn't it?\n\nAlso nothing terrible will happen in any case. If expression is calling \nfunction which is marked is immutable but actually is not, then we can \njust get old (deteriorated)\nresult of expression. Right now, if caller function (one containing \nevaluated expression) is marked as non-volatile, then snapshot is also \nnot taken.\nSo if such function expression is calling foo() function as declared \nabove, then results will be also incorrect.\nSo I do not think some principle difference here and do not understand \nwhy we should not believe user (function creator) only in this case.\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\n\n\n\nOn 23.08.2019 12:10, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\n\npá 23. 8. 2019 v 11:05\n odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn\n 22.08.2019 18:56, Pavel Stehule wrote:\n\n\n\n\n\n\n\nčt 22. 8. 2019\n v 17:51 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n Some more information...\n First of all I found out that marking PL/pgSQL\n function as immutable significantly increase\n speed of its execution: \n 19808 ms vs. 27594. It happens because\n exec_eval_simple_expr is taken snapshot if\n function is volatile (default).\n I wonder if PL/pgSQL compiler can detect that\n evaluated expression itself is actually\n immutable  and there is no need to take snapshot\n \n for each invocation of this function. Also I\n have tried yet another PL language - JavaScript,\n which is now new outsider, despite to the fact\n that \n v8 JIT compiler is very good. \n\n\n\n\nI have a plan to do some work in this\n direction. Snapshot is not necessary for almost\n buildin functions. If expr calls only buildin\n functions, then probably can be called without\n snapshot and without any work with plan cache.\n\n\n\n\n\n\n I wonder if the following simple patch is correct?\n\n\n\n\nYou cannot to believe to user defined functions so\n immutable flag is correct. Only buildin functions are 100%\n correct.\n\n\nCREATE OR REPLACE FUNCTION foo()\nRETURNS int AS $$\nSELECT count(*) FROM pg_class;\n$$ LANGUAGE sql IMMUTABLE;\n\n\nis working.\n\n\n\n\n But such definition of the function contradicts IMMUTABLE contract,\n doesn't it?\n If creator of the function incorrectly classify it, then usage of\n such function can cause incorrect behavior.\n For example, if function is marked as \"parallel safe\" but actually\n it is not parallel safe, then using it in parallel plan may cause\n incorrect results.\n But it is a reason for disabling parallel plans for all user defined\n functions, isn't it?\n\n Also nothing terrible will happen in any case. If expression is\n calling function which is marked is immutable but actually is not, \n then we can just get old (deteriorated)\n result of expression. Right now, if caller function (one containing\n evaluated expression) is marked as non-volatile, then snapshot is\n also not taken.\n So if such function expression is calling foo() function as declared\n above, then results will be also incorrect.\n So I do not think some principle difference here and do not\n understand why we should not believe user (function creator) only in\n this case.\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 23 Aug 2019 14:21:19 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "pá 23. 8. 2019 v 13:21 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 23.08.2019 12:10, Pavel Stehule wrote:\n>\n>\n>\n> pá 23. 8. 2019 v 11:05 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n>\n>>\n>>\n>> On 22.08.2019 18:56, Pavel Stehule wrote:\n>>\n>>\n>>\n>> čt 22. 8. 2019 v 17:51 odesílatel Konstantin Knizhnik <\n>> k.knizhnik@postgrespro.ru> napsal:\n>>\n>>> Some more information...\n>>> First of all I found out that marking PL/pgSQL function as immutable\n>>> significantly increase speed of its execution:\n>>> 19808 ms vs. 27594. It happens because exec_eval_simple_expr is taken\n>>> snapshot if function is volatile (default).\n>>> I wonder if PL/pgSQL compiler can detect that evaluated expression\n>>> itself is actually immutable and there is no need to take snapshot\n>>> for each invocation of this function. Also I have tried yet another PL\n>>> language - JavaScript, which is now new outsider, despite to the fact that\n>>> v8 JIT compiler is very good.\n>>>\n>>\n>> I have a plan to do some work in this direction. Snapshot is not\n>> necessary for almost buildin functions. If expr calls only buildin\n>> functions, then probably can be called without snapshot and without any\n>> work with plan cache.\n>>\n>>\n>> I wonder if the following simple patch is correct?\n>>\n>\n> You cannot to believe to user defined functions so immutable flag is\n> correct. Only buildin functions are 100% correct.\n>\n> CREATE OR REPLACE FUNCTION foo()\n> RETURNS int AS $$\n> SELECT count(*) FROM pg_class;\n> $$ LANGUAGE sql IMMUTABLE;\n>\n> is working.\n>\n>\n> But such definition of the function contradicts IMMUTABLE contract,\n> doesn't it?\n> If creator of the function incorrectly classify it, then usage of such\n> function can cause incorrect behavior.\n> For example, if function is marked as \"parallel safe\" but actually it is\n> not parallel safe, then using it in parallel plan may cause incorrect\n> results.\n> But it is a reason for disabling parallel plans for all user defined\n> functions, isn't it?\n>\n\nIn reality it is not IMMUTABLE function. On second hand, there are lot of\napplication that depends on this behave.\n\nIt is well know trick how to reduce estimation errors related to JOINs.\nWhen immutable function has constant parameters, then it is evaluated in\nplanning time.\n\nSo sometimes was necessary to use\n\nSELECT ... FROM tab WHERE foreign_key = immutable_function('constant\nparameter')\n\ninstead JOIN.\n\nIt is ugly, but it is working perfectly. I think so until we will have\nmulti table statistics, this behave should be available in Postgres.\n\nSure, this function should not be used for functional indexes.\n\n\n>\n> Also nothing terrible will happen in any case. If expression is calling\n> function which is marked is immutable but actually is not, then we can\n> just get old (deteriorated)\n> result of expression. Right now, if caller function (one containing\n> evaluated expression) is marked as non-volatile, then snapshot is also not\n> taken.\n> So if such function expression is calling foo() function as declared\n> above, then results will be also incorrect.\n> So I do not think some principle difference here and do not understand why\n> we should not believe user (function creator) only in this case.\n>\n\n\n\n\n>\n>\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\npá 23. 8. 2019 v 13:21 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 23.08.2019 12:10, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\npá 23. 8. 2019 v 11:05\n odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn\n 22.08.2019 18:56, Pavel Stehule wrote:\n\n\n\n\n\n\n\nčt 22. 8. 2019\n v 17:51 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n Some more information...\n First of all I found out that marking PL/pgSQL\n function as immutable significantly increase\n speed of its execution: \n 19808 ms vs. 27594. It happens because\n exec_eval_simple_expr is taken snapshot if\n function is volatile (default).\n I wonder if PL/pgSQL compiler can detect that\n evaluated expression itself is actually\n immutable  and there is no need to take snapshot\n \n for each invocation of this function. Also I\n have tried yet another PL language - JavaScript,\n which is now new outsider, despite to the fact\n that \n v8 JIT compiler is very good. \n\n\n\n\nI have a plan to do some work in this\n direction. Snapshot is not necessary for almost\n buildin functions. If expr calls only buildin\n functions, then probably can be called without\n snapshot and without any work with plan cache.\n\n\n\n\n\n\n I wonder if the following simple patch is correct?\n\n\n\n\nYou cannot to believe to user defined functions so\n immutable flag is correct. Only buildin functions are 100%\n correct.\n\n\nCREATE OR REPLACE FUNCTION foo()\nRETURNS int AS $$\nSELECT count(*) FROM pg_class;\n$$ LANGUAGE sql IMMUTABLE;\n\n\nis working.\n\n\n\n\n But such definition of the function contradicts IMMUTABLE contract,\n doesn't it?\n If creator of the function incorrectly classify it, then usage of\n such function can cause incorrect behavior.\n For example, if function is marked as \"parallel safe\" but actually\n it is not parallel safe, then using it in parallel plan may cause\n incorrect results.\n But it is a reason for disabling parallel plans for all user defined\n functions, isn't it?In reality it is not IMMUTABLE function. On second hand, there are lot of application that depends on this behave. It is well know trick how to reduce estimation errors related to JOINs. When immutable function has constant parameters, then it is evaluated in planning time.So sometimes was necessary to use SELECT ... FROM tab WHERE foreign_key = immutable_function('constant parameter') instead JOIN.It is ugly, but it is working perfectly. I think so until we will have multi table statistics, this behave should be available in Postgres.Sure, this function should not be used for functional indexes. \n\n Also nothing terrible will happen in any case. If expression is\n calling function which is marked is immutable but actually is not, \n then we can just get old (deteriorated)\n result of expression. Right now, if caller function (one containing\n evaluated expression) is marked as non-volatile, then snapshot is\n also not taken.\n So if such function expression is calling foo() function as declared\n above, then results will be also incorrect.\n So I do not think some principle difference here and do not\n understand why we should not believe user (function creator) only in\n this case. \n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 23 Aug 2019 13:42:27 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "On 23.08.2019 14:42, Pavel Stehule wrote:\n>\n> In reality it is not IMMUTABLE function. On second hand, there are lot \n> of application that depends on this behave.\n>\n> It is well know trick how to reduce estimation errors related to \n> JOINs. When immutable function has constant parameters, then it is \n> evaluated in planning time.\n>\n> So sometimes was necessary to use\n>\n> SELECT ... FROM tab WHERE foreign_key = immutable_function('constant \n> parameter')\n>\n> instead JOIN.\n>\n> It is ugly, but it is working perfectly. I think so until we will have \n> multi table statistics, this behave should be available in Postgres.\n>\n> Sure, this function should not be used for functional indexes.\n>\n\nWhat about the following version of the patch?\n\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 23 Aug 2019 17:32:02 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "On Fri, Aug 23, 2019 at 11:10:28AM +0200, Pavel Stehule wrote:\n> pá 23. 8. 2019 v 11:05 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n> \n> >\n> >\n> > On 22.08.2019 18:56, Pavel Stehule wrote:\n> >\n> >\n> >\n> > čt 22. 8. 2019 v 17:51 odesílatel Konstantin Knizhnik <\n> > k.knizhnik@postgrespro.ru> napsal:\n> >\n> >> Some more information...\n> >> First of all I found out that marking PL/pgSQL function as immutable\n> >> significantly increase speed of its execution:\n> >> 19808 ms vs. 27594. It happens because exec_eval_simple_expr is taken\n> >> snapshot if function is volatile (default).\n> >> I wonder if PL/pgSQL compiler can detect that evaluated expression itself\n> >> is actually immutable and there is no need to take snapshot\n> >> for each invocation of this function. Also I have tried yet another PL\n> >> language - JavaScript, which is now new outsider, despite to the fact that\n> >> v8 JIT compiler is very good.\n> >>\n> >\n> > I have a plan to do some work in this direction. Snapshot is not necessary\n> > for almost buildin functions. If expr calls only buildin functions, then\n> > probably can be called without snapshot and without any work with plan\n> > cache.\n> >\n> >\n> > I wonder if the following simple patch is correct?\n> >\n> \n> You cannot to believe to user defined functions so immutable flag is\n> correct. Only buildin functions are 100% correct.\n> \n> CREATE OR REPLACE FUNCTION foo()\n> RETURNS int AS $$\n> SELECT count(*) FROM pg_class;\n> $$ LANGUAGE sql IMMUTABLE;\n> \n> is working.\n\nNo, it's lying to the RDBMS, so it's pilot error. The problem of\ndetermining from the function itself whether it is in fact immutable\nis, in general, equivalent to the Halting Problem, so no, we can't\nfigure it out. We do need to trust our users not to lie to us, and we\ndo not need to protect them from the consequences when they do.\n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate\n\n\n", "msg_date": "Sat, 24 Aug 2019 18:01:09 +0200", "msg_from": "David Fetter <david@fetter.org>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "so 24. 8. 2019 v 18:01 odesílatel David Fetter <david@fetter.org> napsal:\n\n> On Fri, Aug 23, 2019 at 11:10:28AM +0200, Pavel Stehule wrote:\n> > pá 23. 8. 2019 v 11:05 odesílatel Konstantin Knizhnik <\n> > k.knizhnik@postgrespro.ru> napsal:\n> >\n> > >\n> > >\n> > > On 22.08.2019 18:56, Pavel Stehule wrote:\n> > >\n> > >\n> > >\n> > > čt 22. 8. 2019 v 17:51 odesílatel Konstantin Knizhnik <\n> > > k.knizhnik@postgrespro.ru> napsal:\n> > >\n> > >> Some more information...\n> > >> First of all I found out that marking PL/pgSQL function as immutable\n> > >> significantly increase speed of its execution:\n> > >> 19808 ms vs. 27594. It happens because exec_eval_simple_expr is taken\n> > >> snapshot if function is volatile (default).\n> > >> I wonder if PL/pgSQL compiler can detect that evaluated expression\n> itself\n> > >> is actually immutable and there is no need to take snapshot\n> > >> for each invocation of this function. Also I have tried yet another PL\n> > >> language - JavaScript, which is now new outsider, despite to the fact\n> that\n> > >> v8 JIT compiler is very good.\n> > >>\n> > >\n> > > I have a plan to do some work in this direction. Snapshot is not\n> necessary\n> > > for almost buildin functions. If expr calls only buildin functions,\n> then\n> > > probably can be called without snapshot and without any work with plan\n> > > cache.\n> > >\n> > >\n> > > I wonder if the following simple patch is correct?\n> > >\n> >\n> > You cannot to believe to user defined functions so immutable flag is\n> > correct. Only buildin functions are 100% correct.\n> >\n> > CREATE OR REPLACE FUNCTION foo()\n> > RETURNS int AS $$\n> > SELECT count(*) FROM pg_class;\n> > $$ LANGUAGE sql IMMUTABLE;\n> >\n> > is working.\n>\n> No, it's lying to the RDBMS, so it's pilot error. The problem of\n> determining from the function itself whether it is in fact immutable\n> is, in general, equivalent to the Halting Problem, so no, we can't\n> figure it out. We do need to trust our users not to lie to us, and we\n> do not need to protect them from the consequences when they do.\n>\n\nI have not any problem with fixing this behave when there will be any\nalternative.\n\nI can imagine new special flag that can be used for STABLE functions, that\nenforce one shot plans and can be optimized similar like IMMUTABLE\nfunctions now - using result in planning time.\n\nThe users lie because they must - there is not a alternative. There is not\nany other solution - and estimation errors related to a joins are\nfundamental issue.\n\nRegards\n\nPavel\n\n\n\n\n\n> Best,\n> David.\n> --\n> David Fetter <david(at)fetter(dot)org> http://fetter.org/\n> Phone: +1 415 235 3778\n>\n> Remember to vote!\n> Consider donating to Postgres: http://www.postgresql.org/about/donate\n>\n\nso 24. 8. 2019 v 18:01 odesílatel David Fetter <david@fetter.org> napsal:On Fri, Aug 23, 2019 at 11:10:28AM +0200, Pavel Stehule wrote:\n> pá 23. 8. 2019 v 11:05 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n> \n> >\n> >\n> > On 22.08.2019 18:56, Pavel Stehule wrote:\n> >\n> >\n> >\n> > čt 22. 8. 2019 v 17:51 odesílatel Konstantin Knizhnik <\n> > k.knizhnik@postgrespro.ru> napsal:\n> >\n> >> Some more information...\n> >> First of all I found out that marking PL/pgSQL function as immutable\n> >> significantly increase speed of its execution:\n> >> 19808 ms vs. 27594. It happens because exec_eval_simple_expr is taken\n> >> snapshot if function is volatile (default).\n> >> I wonder if PL/pgSQL compiler can detect that evaluated expression itself\n> >> is actually immutable  and there is no need to take snapshot\n> >> for each invocation of this function. Also I have tried yet another PL\n> >> language - JavaScript, which is now new outsider, despite to the fact that\n> >> v8 JIT compiler is very good.\n> >>\n> >\n> > I have a plan to do some work in this direction. Snapshot is not necessary\n> > for almost buildin functions. If expr calls only buildin functions, then\n> > probably can be called without snapshot and without any work with plan\n> > cache.\n> >\n> >\n> > I wonder if the following simple patch is correct?\n> >\n> \n> You cannot to believe to user defined functions so immutable flag is\n> correct. Only buildin functions are 100% correct.\n> \n> CREATE OR REPLACE FUNCTION foo()\n> RETURNS int AS $$\n> SELECT count(*) FROM pg_class;\n> $$ LANGUAGE sql IMMUTABLE;\n> \n> is working.\n\nNo, it's lying to the RDBMS, so it's pilot error. The problem of\ndetermining from the function itself whether it is in fact immutable\nis, in general, equivalent to the Halting Problem, so no, we can't\nfigure it out. We do need to trust our users not to lie to us, and we\ndo not need to protect them from the consequences when they do.I have not any problem with fixing this behave when there will be any alternative. I can imagine new special flag that can be used for STABLE functions, that enforce one shot plans and can be optimized similar like IMMUTABLE functions now - using result in planning time.The users lie because they must - there is not a alternative. There is not any other solution - and estimation errors related to a joins are fundamental issue.RegardsPavel \n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate", "msg_date": "Sat, 24 Aug 2019 18:13:05 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "On Sat, Aug 24, 2019 at 12:01 PM David Fetter <david@fetter.org> wrote:\n> No, it's lying to the RDBMS, so it's pilot error. The problem of\n> determining from the function itself whether it is in fact immutable\n> is, in general, equivalent to the Halting Problem, so no, we can't\n> figure it out. We do need to trust our users not to lie to us, and we\n> do not need to protect them from the consequences when they do.\n\nDepends. I don't mind if mislabeling a function leads to \"wrong\"\nquery results, but I don't think it's OK for it to, say, crash the\nserver.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 27 Aug 2019 09:46:24 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "On 24.08.2019 19:13, Pavel Stehule wrote:\n>\n>\n> so 24. 8. 2019 v 18:01 odesílatel David Fetter <david@fetter.org \n> <mailto:david@fetter.org>> napsal:\n>\n> On Fri, Aug 23, 2019 at 11:10:28AM +0200, Pavel Stehule wrote:\n> > pá 23. 8. 2019 v 11:05 odesílatel Konstantin Knizhnik <\n> > k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>>\n> napsal:\n> >\n> > >\n> > >\n> > > On 22.08.2019 18:56, Pavel Stehule wrote:\n> > >\n> > >\n> > >\n> > > čt 22. 8. 2019 v 17:51 odesílatel Konstantin Knizhnik <\n> > > k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>>\n> napsal:\n> > >\n> > >> Some more information...\n> > >> First of all I found out that marking PL/pgSQL function as\n> immutable\n> > >> significantly increase speed of its execution:\n> > >> 19808 ms vs. 27594. It happens because exec_eval_simple_expr\n> is taken\n> > >> snapshot if function is volatile (default).\n> > >> I wonder if PL/pgSQL compiler can detect that evaluated\n> expression itself\n> > >> is actually immutable  and there is no need to take snapshot\n> > >> for each invocation of this function. Also I have tried yet\n> another PL\n> > >> language - JavaScript, which is now new outsider, despite to\n> the fact that\n> > >> v8 JIT compiler is very good.\n> > >>\n> > >\n> > > I have a plan to do some work in this direction. Snapshot is\n> not necessary\n> > > for almost buildin functions. If expr calls only buildin\n> functions, then\n> > > probably can be called without snapshot and without any work\n> with plan\n> > > cache.\n> > >\n> > >\n> > > I wonder if the following simple patch is correct?\n> > >\n> >\n> > You cannot to believe to user defined functions so immutable flag is\n> > correct. Only buildin functions are 100% correct.\n> >\n> > CREATE OR REPLACE FUNCTION foo()\n> > RETURNS int AS $$\n> > SELECT count(*) FROM pg_class;\n> > $$ LANGUAGE sql IMMUTABLE;\n> >\n> > is working.\n>\n> No, it's lying to the RDBMS, so it's pilot error. The problem of\n> determining from the function itself whether it is in fact immutable\n> is, in general, equivalent to the Halting Problem, so no, we can't\n> figure it out. We do need to trust our users not to lie to us, and we\n> do not need to protect them from the consequences when they do.\n>\n>\n> I have not any problem with fixing this behave when there will be any \n> alternative.\n>\n> I can imagine new special flag that can be used for STABLE functions, \n> that enforce one shot plans and can be optimized similar like \n> IMMUTABLE functions now - using result in planning time.\n>\n> The users lie because they must - there is not a alternative. There is \n> not any other solution - and estimation errors related to a joins are \n> fundamental issue.\n>\n\nPavel, I wonder if I can put my patch (with fix which performs this \noptimization only for built-in functions) to commitfest or you prefer to \ndo it yourself in some other way and propose your own solution?\n\n\n\nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\n\n\n\nOn 24.08.2019 19:13, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\n\nso 24. 8. 2019 v 18:01\n odesílatel David Fetter <david@fetter.org>\n napsal:\n\nOn Fri, Aug 23, 2019 at\n 11:10:28AM +0200, Pavel Stehule wrote:\n > pá 23. 8. 2019 v 11:05 odesílatel Konstantin Knizhnik\n <\n > k.knizhnik@postgrespro.ru>\n napsal:\n > \n > >\n > >\n > > On 22.08.2019 18:56, Pavel Stehule wrote:\n > >\n > >\n > >\n > > čt 22. 8. 2019 v 17:51 odesílatel Konstantin\n Knizhnik <\n > > k.knizhnik@postgrespro.ru>\n napsal:\n > >\n > >> Some more information...\n > >> First of all I found out that marking PL/pgSQL\n function as immutable\n > >> significantly increase speed of its execution:\n > >> 19808 ms vs. 27594. It happens because\n exec_eval_simple_expr is taken\n > >> snapshot if function is volatile (default).\n > >> I wonder if PL/pgSQL compiler can detect that\n evaluated expression itself\n > >> is actually immutable  and there is no need to\n take snapshot\n > >> for each invocation of this function. Also I\n have tried yet another PL\n > >> language - JavaScript, which is now new\n outsider, despite to the fact that\n > >> v8 JIT compiler is very good.\n > >>\n > >\n > > I have a plan to do some work in this direction.\n Snapshot is not necessary\n > > for almost buildin functions. If expr calls only\n buildin functions, then\n > > probably can be called without snapshot and\n without any work with plan\n > > cache.\n > >\n > >\n > > I wonder if the following simple patch is correct?\n > >\n > \n > You cannot to believe to user defined functions so\n immutable flag is\n > correct. Only buildin functions are 100% correct.\n > \n > CREATE OR REPLACE FUNCTION foo()\n > RETURNS int AS $$\n > SELECT count(*) FROM pg_class;\n > $$ LANGUAGE sql IMMUTABLE;\n > \n > is working.\n\n No, it's lying to the RDBMS, so it's pilot error. The\n problem of\n determining from the function itself whether it is in fact\n immutable\n is, in general, equivalent to the Halting Problem, so no, we\n can't\n figure it out. We do need to trust our users not to lie to\n us, and we\n do not need to protect them from the consequences when they\n do.\n\n\n\nI have not any problem with fixing this behave when there\n will be any alternative. \n\n\n\nI can imagine new special flag that can be used for\n STABLE functions, that enforce one shot plans and can be\n optimized similar like IMMUTABLE functions now - using\n result in planning time.\n\n\nThe users lie because they must - there is not a\n alternative. There is not any other solution - and\n estimation errors related to a joins are fundamental issue.\n\n\n\n\n\n\n\n Pavel, I wonder if I can put my patch (with fix which performs this\n optimization only for built-in functions) to commitfest or you\n prefer to do it yourself in some other way and propose your own\n solution?\n\n\n\nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 13 Sep 2019 10:09:27 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "pá 13. 9. 2019 v 9:09 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 24.08.2019 19:13, Pavel Stehule wrote:\n>\n>\n>\n> so 24. 8. 2019 v 18:01 odesílatel David Fetter <david@fetter.org> napsal:\n>\n>> On Fri, Aug 23, 2019 at 11:10:28AM +0200, Pavel Stehule wrote:\n>> > pá 23. 8. 2019 v 11:05 odesílatel Konstantin Knizhnik <\n>> > k.knizhnik@postgrespro.ru> napsal:\n>> >\n>> > >\n>> > >\n>> > > On 22.08.2019 18:56, Pavel Stehule wrote:\n>> > >\n>> > >\n>> > >\n>> > > čt 22. 8. 2019 v 17:51 odesílatel Konstantin Knizhnik <\n>> > > k.knizhnik@postgrespro.ru> napsal:\n>> > >\n>> > >> Some more information...\n>> > >> First of all I found out that marking PL/pgSQL function as immutable\n>> > >> significantly increase speed of its execution:\n>> > >> 19808 ms vs. 27594. It happens because exec_eval_simple_expr is taken\n>> > >> snapshot if function is volatile (default).\n>> > >> I wonder if PL/pgSQL compiler can detect that evaluated expression\n>> itself\n>> > >> is actually immutable and there is no need to take snapshot\n>> > >> for each invocation of this function. Also I have tried yet another\n>> PL\n>> > >> language - JavaScript, which is now new outsider, despite to the\n>> fact that\n>> > >> v8 JIT compiler is very good.\n>> > >>\n>> > >\n>> > > I have a plan to do some work in this direction. Snapshot is not\n>> necessary\n>> > > for almost buildin functions. If expr calls only buildin functions,\n>> then\n>> > > probably can be called without snapshot and without any work with plan\n>> > > cache.\n>> > >\n>> > >\n>> > > I wonder if the following simple patch is correct?\n>> > >\n>> >\n>> > You cannot to believe to user defined functions so immutable flag is\n>> > correct. Only buildin functions are 100% correct.\n>> >\n>> > CREATE OR REPLACE FUNCTION foo()\n>> > RETURNS int AS $$\n>> > SELECT count(*) FROM pg_class;\n>> > $$ LANGUAGE sql IMMUTABLE;\n>> >\n>> > is working.\n>>\n>> No, it's lying to the RDBMS, so it's pilot error. The problem of\n>> determining from the function itself whether it is in fact immutable\n>> is, in general, equivalent to the Halting Problem, so no, we can't\n>> figure it out. We do need to trust our users not to lie to us, and we\n>> do not need to protect them from the consequences when they do.\n>>\n>\n> I have not any problem with fixing this behave when there will be any\n> alternative.\n>\n> I can imagine new special flag that can be used for STABLE functions, that\n> enforce one shot plans and can be optimized similar like IMMUTABLE\n> functions now - using result in planning time.\n>\n> The users lie because they must - there is not a alternative. There is not\n> any other solution - and estimation errors related to a joins are\n> fundamental issue.\n>\n>\n> Pavel, I wonder if I can put my patch (with fix which performs this\n> optimization only for built-in functions) to commitfest or you prefer to do\n> it yourself in some other way and propose your own solution?\n>\n\nI think so your patch is good enough for commitfest.\n\nIt doesn't remove all overhead - I think so there is lot of overhead\nrelated to plan cache, but it in good direction.\n\nProbably for these expressions is our final target using a cached JIT - but\nnobody knows when it will be. I'll not have to time for my experiments\nbefore October.\n\n\n\n>\n>\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\npá 13. 9. 2019 v 9:09 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 24.08.2019 19:13, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\nso 24. 8. 2019 v 18:01\n odesílatel David Fetter <david@fetter.org>\n napsal:\n\nOn Fri, Aug 23, 2019 at\n 11:10:28AM +0200, Pavel Stehule wrote:\n > pá 23. 8. 2019 v 11:05 odesílatel Konstantin Knizhnik\n <\n > k.knizhnik@postgrespro.ru>\n napsal:\n > \n > >\n > >\n > > On 22.08.2019 18:56, Pavel Stehule wrote:\n > >\n > >\n > >\n > > čt 22. 8. 2019 v 17:51 odesílatel Konstantin\n Knizhnik <\n > > k.knizhnik@postgrespro.ru>\n napsal:\n > >\n > >> Some more information...\n > >> First of all I found out that marking PL/pgSQL\n function as immutable\n > >> significantly increase speed of its execution:\n > >> 19808 ms vs. 27594. It happens because\n exec_eval_simple_expr is taken\n > >> snapshot if function is volatile (default).\n > >> I wonder if PL/pgSQL compiler can detect that\n evaluated expression itself\n > >> is actually immutable  and there is no need to\n take snapshot\n > >> for each invocation of this function. Also I\n have tried yet another PL\n > >> language - JavaScript, which is now new\n outsider, despite to the fact that\n > >> v8 JIT compiler is very good.\n > >>\n > >\n > > I have a plan to do some work in this direction.\n Snapshot is not necessary\n > > for almost buildin functions. If expr calls only\n buildin functions, then\n > > probably can be called without snapshot and\n without any work with plan\n > > cache.\n > >\n > >\n > > I wonder if the following simple patch is correct?\n > >\n > \n > You cannot to believe to user defined functions so\n immutable flag is\n > correct. Only buildin functions are 100% correct.\n > \n > CREATE OR REPLACE FUNCTION foo()\n > RETURNS int AS $$\n > SELECT count(*) FROM pg_class;\n > $$ LANGUAGE sql IMMUTABLE;\n > \n > is working.\n\n No, it's lying to the RDBMS, so it's pilot error. The\n problem of\n determining from the function itself whether it is in fact\n immutable\n is, in general, equivalent to the Halting Problem, so no, we\n can't\n figure it out. We do need to trust our users not to lie to\n us, and we\n do not need to protect them from the consequences when they\n do.\n\n\n\nI have not any problem with fixing this behave when there\n will be any alternative. \n\n\n\nI can imagine new special flag that can be used for\n STABLE functions, that enforce one shot plans and can be\n optimized similar like IMMUTABLE functions now - using\n result in planning time.\n\n\nThe users lie because they must - there is not a\n alternative. There is not any other solution - and\n estimation errors related to a joins are fundamental issue.\n\n\n\n\n\n\n\n Pavel, I wonder if I can put my patch (with fix which performs this\n optimization only for built-in functions) to commitfest or you\n prefer to do it yourself in some other way and propose your own\n solution?I think so your patch is good enough for commitfest.It doesn't remove all overhead - I think so there is lot of overhead related to plan cache, but it in good direction. Probably for these expressions is our final target using a cached JIT - but nobody knows when it will be. I'll not have to time for my experiments before October. \n\n\n\nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 13 Sep 2019 09:16:51 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "On 13.09.2019 10:16, Pavel Stehule wrote:\n>\n>\n> pá 13. 9. 2019 v 9:09 odesílatel Konstantin Knizhnik \n> <k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>\n>\n>\n> On 24.08.2019 19:13, Pavel Stehule wrote:\n>>\n>>\n>> so 24. 8. 2019 v 18:01 odesílatel David Fetter <david@fetter.org\n>> <mailto:david@fetter.org>> napsal:\n>>\n>> On Fri, Aug 23, 2019 at 11:10:28AM +0200, Pavel Stehule wrote:\n>> > pá 23. 8. 2019 v 11:05 odesílatel Konstantin Knizhnik <\n>> > k.knizhnik@postgrespro.ru\n>> <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>> >\n>> > >\n>> > >\n>> > > On 22.08.2019 18:56, Pavel Stehule wrote:\n>> > >\n>> > >\n>> > >\n>> > > čt 22. 8. 2019 v 17:51 odesílatel Konstantin Knizhnik <\n>> > > k.knizhnik@postgrespro.ru\n>> <mailto:k.knizhnik@postgrespro.ru>> napsal:\n>> > >\n>> > >> Some more information...\n>> > >> First of all I found out that marking PL/pgSQL function\n>> as immutable\n>> > >> significantly increase speed of its execution:\n>> > >> 19808 ms vs. 27594. It happens because\n>> exec_eval_simple_expr is taken\n>> > >> snapshot if function is volatile (default).\n>> > >> I wonder if PL/pgSQL compiler can detect that evaluated\n>> expression itself\n>> > >> is actually immutable  and there is no need to take snapshot\n>> > >> for each invocation of this function. Also I have tried\n>> yet another PL\n>> > >> language - JavaScript, which is now new outsider,\n>> despite to the fact that\n>> > >> v8 JIT compiler is very good.\n>> > >>\n>> > >\n>> > > I have a plan to do some work in this direction. Snapshot\n>> is not necessary\n>> > > for almost buildin functions. If expr calls only buildin\n>> functions, then\n>> > > probably can be called without snapshot and without any\n>> work with plan\n>> > > cache.\n>> > >\n>> > >\n>> > > I wonder if the following simple patch is correct?\n>> > >\n>> >\n>> > You cannot to believe to user defined functions so\n>> immutable flag is\n>> > correct. Only buildin functions are 100% correct.\n>> >\n>> > CREATE OR REPLACE FUNCTION foo()\n>> > RETURNS int AS $$\n>> > SELECT count(*) FROM pg_class;\n>> > $$ LANGUAGE sql IMMUTABLE;\n>> >\n>> > is working.\n>>\n>> No, it's lying to the RDBMS, so it's pilot error. The problem of\n>> determining from the function itself whether it is in fact\n>> immutable\n>> is, in general, equivalent to the Halting Problem, so no, we\n>> can't\n>> figure it out. We do need to trust our users not to lie to\n>> us, and we\n>> do not need to protect them from the consequences when they do.\n>>\n>>\n>> I have not any problem with fixing this behave when there will be\n>> any alternative.\n>>\n>> I can imagine new special flag that can be used for STABLE\n>> functions, that enforce one shot plans and can be optimized\n>> similar like IMMUTABLE functions now - using result in planning time.\n>>\n>> The users lie because they must - there is not a alternative.\n>> There is not any other solution - and estimation errors related\n>> to a joins are fundamental issue.\n>>\n>\n> Pavel, I wonder if I can put my patch (with fix which performs\n> this optimization only for built-in functions) to commitfest or\n> you prefer to do it yourself in some other way and propose your\n> own solution?\n>\n>\n> I think so your patch is good enough for commitfest.\n>\n> It doesn't remove all overhead - I think so there is lot of overhead \n> related to plan cache, but it in good direction.\n>\n> Probably for these expressions is our final target using a cached JIT \n> - but nobody knows when it will be. I'll not have to time for my \n> experiments before October.\n>\n\nThis is profile of execution of PL/pgSQL function with my patch:\n\n    5.39%  postgres  plpgsql.so         [.] exec_assign_value\n    5.10%  postgres  postgres           [.] ExecInterpExpr\n    4.70%  postgres  postgres           [.] tts_buffer_heap_getsomeattrs\n    4.56%  postgres  plpgsql.so         [.] exec_move_row_from_fields\n    3.87%  postgres  postgres           [.] ExecScan\n    3.74%  postgres  plpgsql.so         [.] exec_eval_expr\n    3.64%  postgres  postgres           [.] heap_form_tuple\n    3.13%  postgres  postgres           [.] heap_fill_tuple\n    3.07%  postgres  postgres           [.] heapgettup_pagemode\n    2.95%  postgres  postgres           [.] heap_deform_tuple\n    2.92%  postgres  plpgsql.so         [.] plpgsql_param_eval_var\n    2.64%  postgres  postgres           [.] HeapTupleSatisfiesVisibility\n    2.61%  postgres  postgres           [.] AcquirePlannerLocks\n    2.58%  postgres  postgres           [.] AcquireExecutorLocks\n    2.43%  postgres  postgres           [.] GetCachedPlan\n    2.26%  postgres  plpgsql.so         [.] exec_stmt\n    2.23%  postgres  plpgsql.so         [.] exec_cast_value\n    1.89%  postgres  postgres           [.] AllocSetAlloc\n    1.75%  postgres  postgres           [.] palloc0\n    1.73%  postgres  plpgsql.so         [.] exec_move_row\n    1.73%  postgres  postgres           [.] OverrideSearchPathMatchesCurrent\n    1.69%  postgres  plpgsql.so         [.] assign_simple_var\n    1.63%  postgres  postgres           [.] heap_getnextslot\n    1.60%  postgres  postgres           [.] SPI_plan_get_cached_plan\n    1.55%  postgres  postgres           [.] heapgetpage\n    1.47%  postgres  postgres           [.] heap_compute_data_size\n    1.46%  postgres  postgres           [.] spi_printtup\n    1.43%  postgres  postgres           [.] float8mul\n    1.37%  postgres  postgres           [.] RevalidateCachedQuery\n    1.36%  postgres  postgres           [.] standard_ExecutorRun\n    1.35%  postgres  postgres           [.] recomputeNamespacePath\n    1.28%  postgres  postgres           [.] ExecStoreBufferHeapTuple\n    1.25%  postgres  postgres           [.] MemoryContextReset\n    1.22%  postgres  plpgsql.so         [.] exec_eval_cleanup.isra.18\n    1.20%  postgres  plpgsql.so         [.] exec_assign_expr\n    1.05%  postgres  postgres           [.] SeqNext\n    1.04%  postgres  postgres           [.] ResourceArrayRemove\n    1.00%  postgres  postgres           [.] ScanQueryForLocks\n\n\nBased on this profile it seems to me that plan cache overhead is \nrelatively small:\n\n2.43%+1.60%+1.37% < 6%\n\nBut from the other side ExecInterpExpr itself takes also about 5%.\nI do not completely understand why JIT is not currently used for \nevaluation of SPI expressions\n(why we call ExecInterpExpr and do not try  to compile this expression \neven if JIT is enabled).\nBut event if we do it and improve speed of expression evaluation 10 or \nmore time, looks like\nthat effect on total query execution time will be also negligible (5%).\n\nMost of the time is spent in pl_exec code, heap traversal , unpacking \nand copying tuple data.\nLooks like it can not be easily optimized and requires serious rewriting \nof PL/pgSQL stuff.\n\n-- \n\nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\n\n\n\nOn 13.09.2019 10:16, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\n\npá 13. 9. 2019 v 9:09\n odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru>\n napsal:\n\n\n \n\nOn\n 24.08.2019 19:13, Pavel Stehule wrote:\n\n\n\n\n\n\n\nso 24. 8. 2019\n v 18:01 odesílatel David Fetter <david@fetter.org>\n napsal:\n\nOn Fri, Aug 23,\n 2019 at 11:10:28AM +0200, Pavel Stehule wrote:\n > pá 23. 8. 2019 v 11:05 odesílatel Konstantin\n Knizhnik <\n > k.knizhnik@postgrespro.ru>\n napsal:\n > \n > >\n > >\n > > On 22.08.2019 18:56, Pavel Stehule\n wrote:\n > >\n > >\n > >\n > > čt 22. 8. 2019 v 17:51 odesílatel\n Konstantin Knizhnik <\n > > k.knizhnik@postgrespro.ru>\n napsal:\n > >\n > >> Some more information...\n > >> First of all I found out that\n marking PL/pgSQL function as immutable\n > >> significantly increase speed of its\n execution:\n > >> 19808 ms vs. 27594. It happens\n because exec_eval_simple_expr is taken\n > >> snapshot if function is volatile\n (default).\n > >> I wonder if PL/pgSQL compiler can\n detect that evaluated expression itself\n > >> is actually immutable  and there is\n no need to take snapshot\n > >> for each invocation of this\n function. Also I have tried yet another PL\n > >> language - JavaScript, which is now\n new outsider, despite to the fact that\n > >> v8 JIT compiler is very good.\n > >>\n > >\n > > I have a plan to do some work in this\n direction. Snapshot is not necessary\n > > for almost buildin functions. If expr\n calls only buildin functions, then\n > > probably can be called without snapshot\n and without any work with plan\n > > cache.\n > >\n > >\n > > I wonder if the following simple patch\n is correct?\n > >\n > \n > You cannot to believe to user defined\n functions so immutable flag is\n > correct. Only buildin functions are 100%\n correct.\n > \n > CREATE OR REPLACE FUNCTION foo()\n > RETURNS int AS $$\n > SELECT count(*) FROM pg_class;\n > $$ LANGUAGE sql IMMUTABLE;\n > \n > is working.\n\n No, it's lying to the RDBMS, so it's pilot error.\n The problem of\n determining from the function itself whether it is\n in fact immutable\n is, in general, equivalent to the Halting Problem,\n so no, we can't\n figure it out. We do need to trust our users not\n to lie to us, and we\n do not need to protect them from the consequences\n when they do.\n\n\n\nI have not any problem with fixing this behave\n when there will be any alternative. \n\n\n\nI can imagine new special flag that can be used\n for STABLE functions, that enforce one shot plans\n and can be optimized similar like IMMUTABLE\n functions now - using result in planning time.\n\n\nThe users lie because they must - there is not\n a alternative. There is not any other solution -\n and estimation errors related to a joins are\n fundamental issue.\n\n\n\n\n\n\n\n Pavel, I wonder if I can put my patch (with fix which\n performs this optimization only for built-in functions) to\n commitfest or you prefer to do it yourself in some other\n way and propose your own solution?\n\n\n\n\nI think so your patch is good enough for commitfest.\n\n\nIt doesn't remove all overhead - I think so there is lot\n of overhead related to plan cache, but it in good direction.\n \n\n\n\nProbably for these expressions is our final target using\n a cached JIT - but nobody knows when it will be. I'll not\n have to time for my experiments before October. \n\n\n\n\n\n\n\n This is profile of execution of PL/pgSQL function with my patch:\n\n   5.39%  postgres  plpgsql.so         [.]\n exec_assign_value\n    5.10%  postgres  postgres           [.] ExecInterpExpr\n   4.70%  postgres  postgres           [.]\n tts_buffer_heap_getsomeattrs\n    4.56%  postgres  plpgsql.so         [.] exec_move_row_from_fields\n    3.87%  postgres  postgres           [.] ExecScan\n    3.74%  postgres  plpgsql.so         [.] exec_eval_expr\n    3.64%  postgres  postgres           [.] heap_form_tuple\n    3.13%  postgres  postgres           [.] heap_fill_tuple\n    3.07%  postgres  postgres           [.] heapgettup_pagemode\n    2.95%  postgres  postgres           [.] heap_deform_tuple\n    2.92%  postgres  plpgsql.so         [.] plpgsql_param_eval_var\n    2.64%  postgres  postgres           [.]\n HeapTupleSatisfiesVisibility\n    2.61%  postgres  postgres           [.] AcquirePlannerLocks\n    2.58%  postgres  postgres           [.] AcquireExecutorLocks\n    2.43%  postgres  postgres           [.] GetCachedPlan\n    2.26%  postgres  plpgsql.so         [.] exec_stmt\n    2.23%  postgres  plpgsql.so         [.] exec_cast_value\n    1.89%  postgres  postgres           [.] AllocSetAlloc\n    1.75%  postgres  postgres           [.] palloc0\n    1.73%  postgres  plpgsql.so         [.] exec_move_row\n    1.73%  postgres  postgres           [.]\n OverrideSearchPathMatchesCurrent\n    1.69%  postgres  plpgsql.so         [.] assign_simple_var\n    1.63%  postgres  postgres           [.] heap_getnextslot\n    1.60%  postgres  postgres           [.] SPI_plan_get_cached_plan\n    1.55%  postgres  postgres           [.] heapgetpage\n    1.47%  postgres  postgres           [.] heap_compute_data_size\n    1.46%  postgres  postgres           [.] spi_printtup\n    1.43%  postgres  postgres           [.] float8mul\n    1.37%  postgres  postgres           [.] RevalidateCachedQuery\n    1.36%  postgres  postgres           [.] standard_ExecutorRun\n    1.35%  postgres  postgres           [.] recomputeNamespacePath\n    1.28%  postgres  postgres           [.] ExecStoreBufferHeapTuple\n    1.25%  postgres  postgres           [.] MemoryContextReset\n    1.22%  postgres  plpgsql.so         [.] exec_eval_cleanup.isra.18\n    1.20%  postgres  plpgsql.so         [.] exec_assign_expr\n    1.05%  postgres  postgres           [.] SeqNext\n    1.04%  postgres  postgres           [.] ResourceArrayRemove\n    1.00%  postgres  postgres           [.] ScanQueryForLocks\n\n\n Based on this profile it seems to me that plan cache overhead is\n relatively small:\n\n 2.43%+1.60%+1.37% < 6%\n\n But from the other side ExecInterpExpr itself takes also about 5%.\n I do not completely understand why JIT is not currently used for\n evaluation of SPI expressions\n (why we call ExecInterpExpr and do not try  to compile this\n expression even if JIT is enabled).\n But event if we do it and improve speed of expression evaluation 10\n or more time, looks like \n that effect on total query execution time will be also negligible\n (5%).\n\n Most of the time is spent in pl_exec code, heap traversal ,\n unpacking and copying tuple data.\n Looks like it can not be easily optimized and requires serious\n rewriting of PL/pgSQL stuff.\n \n--\n Konstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 13 Sep 2019 11:49:16 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "Hi\n\nI testing very simple function\n\ncreate or replace function f1(int) returns int as $$ declare i int = 0;\nbegin while i < $1 loop i = i + 1; end loop; return i; end $$ language\nplpgsql immutable;\n\nprofile - when function is marked as immutable\n\n 8,65% postgres [.] ExecInterpExpr\n ▒\n 8,59% postgres [.] AcquireExecutorLocks\n ▒\n 6,95% postgres [.] OverrideSearchPathMatchesCurrent\n ▒\n 5,72% plpgsql.so [.] plpgsql_param_eval_var\n ▒\n 5,15% postgres [.] AcquirePlannerLocks\n ▒\n 4,54% postgres [.] RevalidateCachedQuery\n ▒\n 4,52% postgres [.] GetCachedPlan\n ▒\n 3,82% postgres [.] ResourceArrayRemove\n ▒\n 2,87% postgres [.] SPI_plan_get_cached_plan\n ▒\n 2,80% plpgsql.so [.] exec_eval_expr\n ▒\n 2,70% plpgsql.so [.] exec_assign_value\n ▒\n 2,55% plpgsql.so [.] exec_stmt\n ▒\n 2,53% postgres [.] recomputeNamespacePath\n ▒\n 2,39% plpgsql.so [.] exec_cast_value\n ▒\n 2,19% postgres [.] int4pl\n ▒\n 2,13% postgres [.] int4lt\n ▒\n 1,98% postgres [.] CheckCachedPlan\n\nvolatile\n\n 7,21% postgres [.] GetSnapshotData\n 6,92% plpgsql.so [.] exec_eval_simple_expr\n 5,79% postgres [.] AcquireExecutorLocks\n 5,57% postgres [.] ExecInterpExpr\n 4,12% postgres [.] LWLockRelease\n 3,68% postgres [.] OverrideSearchPathMatchesCurrent\n 3,64% postgres [.] PopActiveSnapshot\n 3,36% plpgsql.so [.] plpgsql_param_eval_var\n 3,31% postgres [.] LWLockAttemptLock\n 3,13% postgres [.] AllocSetAlloc\n 2,91% postgres [.] GetCachedPlan\n 2,79% postgres [.] MemoryContextAlloc\n 2,76% postgres [.] AcquirePlannerLocks\n 2,70% postgres [.] ResourceArrayRemove\n 2,45% postgres [.] PushActiveSnapshot\n 2,44% postgres [.] RevalidateCachedQuery\n 2,29% postgres [.] SPI_plan_get_cached_plan\n 2,18% postgres [.] CopySnapshot\n 1,95% postgres [.] AllocSetFree\n 1,81% postgres [.] LWLockAcquire\n 1,71% plpgsql.so [.] exec_assign_value\n 1,61% plpgsql.so [.] exec_stmt\n 1,59% plpgsql.so [.] exec_eval_expr\n 1,48% postgres [.] int4pl\n 1,48% postgres [.] CheckCachedPlan\n 1,40% plpgsql.so [.] exec_cast_value\n 1,39% postgres [.] int4lt\n 1,38% postgres [.] recomputeNamespacePath\n 1,25% plpgsql.so [.] exec_eval_cleanup\n 1,08% postgres [.] ScanQueryForLocks\n 1,01% plpgsql.so [.] exec_eval_boolean\n 1,00% postgres [.] pfree\n\nFor tested function almost all CPU should be used for int4pl and int4lt\nfunctions - but there are used only 4% together. I think so almost all of\n\n 8,59% postgres [.] AcquireExecutorLocks\n ▒\n 6,95% postgres [.] OverrideSearchPathMatchesCurrent\n ▒\n 5,72% plpgsql.so [.] plpgsql_param_eval_var\n ▒\n 5,15% postgres [.] AcquirePlannerLocks\n ▒\n 4,54% postgres [.] RevalidateCachedQuery\n ▒\n 4,52% postgres [.] GetCachedPlan\n ▒\n 3,82% postgres [.] ResourceArrayRemove\n ▒\n 2,87% postgres [.] SPI_plan_get_cached_plan\n ▒\n 2,53% postgres [.] recomputeNamespacePath\n ▒\n\ncan be reduced if we know so we should to call just builtin immutable V1\nfunctions.\n\nMy example is a extrem - when you use any embedded SQL, then the profile\nwill be significantly changed. But for some cases there can be nice some\nsignificant speedup of expressions only functions (like PostGIS)\n\nRegards\n\nPavel\n\nHiI testing very simple functioncreate or replace function f1(int) returns int as $$ declare i int = 0; begin while i < $1 loop i = i + 1; end loop; return i; end $$ language plpgsql immutable;profile - when function is marked as immutable   8,65%  postgres    [.] ExecInterpExpr                                                                                              ▒   8,59%  postgres    [.] AcquireExecutorLocks                                                                                        ▒   6,95%  postgres    [.] OverrideSearchPathMatchesCurrent                                                                            ▒   5,72%  plpgsql.so  [.] plpgsql_param_eval_var                                                                                      ▒   5,15%  postgres    [.] AcquirePlannerLocks                                                                                         ▒   4,54%  postgres    [.] RevalidateCachedQuery                                                                                       ▒   4,52%  postgres    [.] GetCachedPlan                                                                                               ▒   3,82%  postgres    [.] ResourceArrayRemove                                                                                         ▒   2,87%  postgres    [.] SPI_plan_get_cached_plan                                                                                    ▒   2,80%  plpgsql.so  [.] exec_eval_expr                                                                                              ▒   2,70%  plpgsql.so  [.] exec_assign_value                                                                                           ▒   2,55%  plpgsql.so  [.] exec_stmt                                                                                                   ▒   2,53%  postgres    [.] recomputeNamespacePath                                                                                      ▒   2,39%  plpgsql.so  [.] exec_cast_value                                                                                             ▒   2,19%  postgres    [.] int4pl                                                                                                      ▒   2,13%  postgres    [.] int4lt                                                                                                      ▒   1,98%  postgres    [.] CheckCachedPlan     volatile   7,21%  postgres      [.] GetSnapshotData   6,92%  plpgsql.so    [.] exec_eval_simple_expr   5,79%  postgres      [.] AcquireExecutorLocks   5,57%  postgres      [.] ExecInterpExpr   4,12%  postgres      [.] LWLockRelease   3,68%  postgres      [.] OverrideSearchPathMatchesCurrent   3,64%  postgres      [.] PopActiveSnapshot   3,36%  plpgsql.so    [.] plpgsql_param_eval_var   3,31%  postgres      [.] LWLockAttemptLock   3,13%  postgres      [.] AllocSetAlloc   2,91%  postgres      [.] GetCachedPlan   2,79%  postgres      [.] MemoryContextAlloc   2,76%  postgres      [.] AcquirePlannerLocks   2,70%  postgres      [.] ResourceArrayRemove   2,45%  postgres      [.] PushActiveSnapshot   2,44%  postgres      [.] RevalidateCachedQuery   2,29%  postgres      [.] SPI_plan_get_cached_plan   2,18%  postgres      [.] CopySnapshot   1,95%  postgres      [.] AllocSetFree   1,81%  postgres      [.] LWLockAcquire   1,71%  plpgsql.so    [.] exec_assign_value   1,61%  plpgsql.so    [.] exec_stmt   1,59%  plpgsql.so    [.] exec_eval_expr   1,48%  postgres      [.] int4pl   1,48%  postgres      [.] CheckCachedPlan   1,40%  plpgsql.so    [.] exec_cast_value   1,39%  postgres      [.] int4lt   1,38%  postgres      [.] recomputeNamespacePath   1,25%  plpgsql.so    [.] exec_eval_cleanup   1,08%  postgres      [.] ScanQueryForLocks   1,01%  plpgsql.so    [.] exec_eval_boolean   1,00%  postgres      [.] pfreeFor tested function almost all CPU should be used for int4pl and int4lt functions - but there are used only 4% together. I think so almost all of   \r\n8,59%  postgres    [.] AcquireExecutorLocks                            \r\n                                                            ▒  \r\n 6,95%  postgres    [.] OverrideSearchPathMatchesCurrent                \r\n                                                            ▒  \r\n 5,72%  plpgsql.so  [.] plpgsql_param_eval_var                          \r\n                                                            ▒  \r\n 5,15%  postgres    [.] AcquirePlannerLocks                              \r\n                                                           ▒   4,54%\r\n  postgres    [.] RevalidateCachedQuery                                  \r\n                                                     ▒   4,52% \r\n postgres    [.] GetCachedPlan                                          \r\n                                                     ▒   3,82% \r\n postgres    [.] ResourceArrayRemove                                    \r\n                                                     ▒   2,87% \r\n postgres    [.] SPI_plan_get_cached_plan                                \r\n                                                    ▒   2,53% \r\n postgres    [.] recomputeNamespacePath                                  \r\n                                                    ▒can be reduced if we know so we should to call just builtin immutable V1 functions.My example is a extrem - when you use any embedded SQL, then the profile will be significantly changed. But for some cases there can be nice some significant speedup of expressions only functions (like PostGIS)RegardsPavel", "msg_date": "Fri, 13 Sep 2019 11:17:45 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "Hi\n\npá 23. 8. 2019 v 16:32 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 23.08.2019 14:42, Pavel Stehule wrote:\n>\n>\n> In reality it is not IMMUTABLE function. On second hand, there are lot of\n> application that depends on this behave.\n>\n> It is well know trick how to reduce estimation errors related to JOINs.\n> When immutable function has constant parameters, then it is evaluated in\n> planning time.\n>\n> So sometimes was necessary to use\n>\n> SELECT ... FROM tab WHERE foreign_key = immutable_function('constant\n> parameter')\n>\n> instead JOIN.\n>\n> It is ugly, but it is working perfectly. I think so until we will have\n> multi table statistics, this behave should be available in Postgres.\n>\n> Sure, this function should not be used for functional indexes.\n>\n>\n>\n> What about the following version of the patch?\n>\n\nI am sending review of this small patch.\n\nThis small patch reduce a overhead of usage buildin immutable functions in\nvolatile functions with simple trick. Starts snapshot only when it is\nnecessary.\n\nIn decrease runtime time about 25 % on this small example.\n\ndo $$\ndeclare i int;\nbegin\n i := 0;\n while i < 10000000\n loop\n i := i + 1;\n end loop;\nend;\n$$;\n\nIf there are more expressions, then speedup can be more interesting. If\nthere are other bottlenecks, then the speedup will be less. 25% is not bad,\nso we want to this feature.\n\nI believe so similar method can be used more aggressively with more\nsignificant performance benefit, but this is low hanging fruit and isn't\nreason to wait for future.\n\nThis patch doesn't introduce any new feature, so new tests and new doc is\nnot necessary.\nThe patch is readable, well formatted, only comments are too long. I fixed\nit.\nAll tests passed\nI fixed few warnings, and I reformated little bit function\nexpr_needs_snapshot to use if instead case, what is more usual in these\ncases.\n\nI think so this code can be marked as ready for commit\n\nRegards\n\nPavel\n\n\n>\n>\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>", "msg_date": "Tue, 5 Nov 2019 22:14:40 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "Hello.\n\nAt Tue, 5 Nov 2019 22:14:40 +0100, Pavel Stehule <pavel.stehule@gmail.com> wrote in \n> Hi\n> \n> pá 23. 8. 2019 v 16:32 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n> \n> >\n> >\n> > On 23.08.2019 14:42, Pavel Stehule wrote:\n> >\n> >\n> > In reality it is not IMMUTABLE function. On second hand, there are lot of\n> > application that depends on this behave.\n> >\n> > It is well know trick how to reduce estimation errors related to JOINs.\n> > When immutable function has constant parameters, then it is evaluated in\n> > planning time.\n> >\n> > So sometimes was necessary to use\n> >\n> > SELECT ... FROM tab WHERE foreign_key = immutable_function('constant\n> > parameter')\n> >\n> > instead JOIN.\n> >\n> > It is ugly, but it is working perfectly. I think so until we will have\n> > multi table statistics, this behave should be available in Postgres.\n> >\n> > Sure, this function should not be used for functional indexes.\n> >\n> >\n> >\n> > What about the following version of the patch?\n> >\n> \n> I am sending review of this small patch.\n> \n> This small patch reduce a overhead of usage buildin immutable functions in\n> volatile functions with simple trick. Starts snapshot only when it is\n> necessary.\n> \n> In decrease runtime time about 25 % on this small example.\n> \n> do $$\n> declare i int;\n> begin\n> i := 0;\n> while i < 10000000\n> loop\n> i := i + 1;\n> end loop;\n> end;\n> $$;\n> \n> If there are more expressions, then speedup can be more interesting. If\n> there are other bottlenecks, then the speedup will be less. 25% is not bad,\n> so we want to this feature.\n> \n> I believe so similar method can be used more aggressively with more\n> significant performance benefit, but this is low hanging fruit and isn't\n> reason to wait for future.\n> \n> This patch doesn't introduce any new feature, so new tests and new doc is\n> not necessary.\n> The patch is readable, well formatted, only comments are too long. I fixed\n> it.\n> All tests passed\n> I fixed few warnings, and I reformated little bit function\n> expr_needs_snapshot to use if instead case, what is more usual in these\n> cases.\n> \n> I think so this code can be marked as ready for commit\n\nI have some comments on this.\n\nexpr_needs_snapshot checks out some of the node already checked out in\nexec_simple_check_plan but not all. However I don't see the criteria\nof the choice.\n\nI might be too worrying, but maybe we should write the function in\nwhite-listed way, that is, expr_needs_snapshot returns false only if\nthe whole tree consists of only the node types known to the\nfunction. And any unknown node makes the function return true\nimmediately.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Thu, 07 Nov 2019 21:03:17 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "čt 7. 11. 2019 v 13:03 odesílatel Kyotaro Horiguchi <horikyota.ntt@gmail.com>\nnapsal:\n\n> Hello.\n>\n> At Tue, 5 Nov 2019 22:14:40 +0100, Pavel Stehule <pavel.stehule@gmail.com>\n> wrote in\n> > Hi\n> >\n> > pá 23. 8. 2019 v 16:32 odesílatel Konstantin Knizhnik <\n> > k.knizhnik@postgrespro.ru> napsal:\n> >\n> > >\n> > >\n> > > On 23.08.2019 14:42, Pavel Stehule wrote:\n> > >\n> > >\n> > > In reality it is not IMMUTABLE function. On second hand, there are lot\n> of\n> > > application that depends on this behave.\n> > >\n> > > It is well know trick how to reduce estimation errors related to JOINs.\n> > > When immutable function has constant parameters, then it is evaluated\n> in\n> > > planning time.\n> > >\n> > > So sometimes was necessary to use\n> > >\n> > > SELECT ... FROM tab WHERE foreign_key = immutable_function('constant\n> > > parameter')\n> > >\n> > > instead JOIN.\n> > >\n> > > It is ugly, but it is working perfectly. I think so until we will have\n> > > multi table statistics, this behave should be available in Postgres.\n> > >\n> > > Sure, this function should not be used for functional indexes.\n> > >\n> > >\n> > >\n> > > What about the following version of the patch?\n> > >\n> >\n> > I am sending review of this small patch.\n> >\n> > This small patch reduce a overhead of usage buildin immutable functions\n> in\n> > volatile functions with simple trick. Starts snapshot only when it is\n> > necessary.\n> >\n> > In decrease runtime time about 25 % on this small example.\n> >\n> > do $$\n> > declare i int;\n> > begin\n> > i := 0;\n> > while i < 10000000\n> > loop\n> > i := i + 1;\n> > end loop;\n> > end;\n> > $$;\n> >\n> > If there are more expressions, then speedup can be more interesting. If\n> > there are other bottlenecks, then the speedup will be less. 25% is not\n> bad,\n> > so we want to this feature.\n> >\n> > I believe so similar method can be used more aggressively with more\n> > significant performance benefit, but this is low hanging fruit and isn't\n> > reason to wait for future.\n> >\n> > This patch doesn't introduce any new feature, so new tests and new doc is\n> > not necessary.\n> > The patch is readable, well formatted, only comments are too long. I\n> fixed\n> > it.\n> > All tests passed\n> > I fixed few warnings, and I reformated little bit function\n> > expr_needs_snapshot to use if instead case, what is more usual in these\n> > cases.\n> >\n> > I think so this code can be marked as ready for commit\n>\n> I have some comments on this.\n>\n> expr_needs_snapshot checks out some of the node already checked out in\n> exec_simple_check_plan but not all. However I don't see the criteria\n> of the choice.\n>\n> I might be too worrying, but maybe we should write the function in\n> white-listed way, that is, expr_needs_snapshot returns false only if\n> the whole tree consists of only the node types known to the\n> function. And any unknown node makes the function return true\n> immediately.\n>\n\nhas sense\n\nPavel\n\n\n> regards.\n>\n> --\n> Kyotaro Horiguchi\n> NTT Open Source Software Center\n>\n\nčt 7. 11. 2019 v 13:03 odesílatel Kyotaro Horiguchi <horikyota.ntt@gmail.com> napsal:Hello.\n\nAt Tue, 5 Nov 2019 22:14:40 +0100, Pavel Stehule <pavel.stehule@gmail.com> wrote in \n> Hi\n> \n> pá 23. 8. 2019 v 16:32 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n> \n> >\n> >\n> > On 23.08.2019 14:42, Pavel Stehule wrote:\n> >\n> >\n> > In reality it is not IMMUTABLE function. On second hand, there are lot of\n> > application that depends on this behave.\n> >\n> > It is well know trick how to reduce estimation errors related to JOINs.\n> > When immutable function has constant parameters, then it is evaluated in\n> > planning time.\n> >\n> > So sometimes was necessary to use\n> >\n> > SELECT ... FROM tab WHERE foreign_key = immutable_function('constant\n> > parameter')\n> >\n> > instead JOIN.\n> >\n> > It is ugly, but it is working perfectly. I think so until we will have\n> > multi table statistics, this behave should be available in Postgres.\n> >\n> > Sure, this function should not be used for functional indexes.\n> >\n> >\n> >\n> > What about the following version of the patch?\n> >\n> \n> I am sending review of this small patch.\n> \n> This small patch reduce a overhead of usage buildin immutable functions in\n> volatile functions with simple trick. Starts snapshot only when it is\n> necessary.\n> \n> In decrease runtime time about 25 % on this small example.\n> \n> do $$\n> declare i int;\n> begin\n>   i := 0;\n>   while i < 10000000\n>   loop\n>     i := i + 1;\n>   end loop;\n> end;\n> $$;\n> \n> If there are more expressions, then speedup can be more interesting. If\n> there are other bottlenecks, then the speedup will be less. 25% is not bad,\n> so we want to this feature.\n> \n> I believe so similar method can be used more aggressively with more\n> significant performance benefit, but this is low hanging fruit and isn't\n> reason to wait for future.\n> \n> This patch doesn't introduce any new feature, so new tests and new doc is\n> not necessary.\n> The patch is readable, well  formatted, only comments are too long. I fixed\n> it.\n> All tests passed\n> I fixed few warnings, and I reformated little bit function\n> expr_needs_snapshot to use if instead case, what is more usual in these\n> cases.\n> \n> I think so this code can be marked as ready for commit\n\nI have some comments on this.\n\nexpr_needs_snapshot checks out some of the node already checked out in\nexec_simple_check_plan but not all. However I don't see the criteria\nof the choice.\n\nI might be too worrying, but maybe we should write the function in\nwhite-listed way, that is, expr_needs_snapshot returns false only if\nthe whole tree consists of only the node types known to the\nfunction. And any unknown node makes the function return true\nimmediately.has sensePavel\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Thu, 7 Nov 2019 13:09:52 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "On 07.11.2019 15:09, Pavel Stehule wrote:\n>\n>\n> čt 7. 11. 2019 v 13:03 odesílatel Kyotaro Horiguchi \n> <horikyota.ntt@gmail.com <mailto:horikyota.ntt@gmail.com>> napsal:\n>\n> Hello.\n>\n> At Tue, 5 Nov 2019 22:14:40 +0100, Pavel Stehule\n> <pavel.stehule@gmail.com <mailto:pavel.stehule@gmail.com>> wrote in\n> > Hi\n> >\n> > pá 23. 8. 2019 v 16:32 odesílatel Konstantin Knizhnik <\n> > k.knizhnik@postgrespro.ru <mailto:k.knizhnik@postgrespro.ru>>\n> napsal:\n> >\n> > >\n> > >\n> > > On 23.08.2019 14:42, Pavel Stehule wrote:\n> > >\n> > >\n> > > In reality it is not IMMUTABLE function. On second hand, there\n> are lot of\n> > > application that depends on this behave.\n> > >\n> > > It is well know trick how to reduce estimation errors related\n> to JOINs.\n> > > When immutable function has constant parameters, then it is\n> evaluated in\n> > > planning time.\n> > >\n> > > So sometimes was necessary to use\n> > >\n> > > SELECT ... FROM tab WHERE foreign_key =\n> immutable_function('constant\n> > > parameter')\n> > >\n> > > instead JOIN.\n> > >\n> > > It is ugly, but it is working perfectly. I think so until we\n> will have\n> > > multi table statistics, this behave should be available in\n> Postgres.\n> > >\n> > > Sure, this function should not be used for functional indexes.\n> > >\n> > >\n> > >\n> > > What about the following version of the patch?\n> > >\n> >\n> > I am sending review of this small patch.\n> >\n> > This small patch reduce a overhead of usage buildin immutable\n> functions in\n> > volatile functions with simple trick. Starts snapshot only when\n> it is\n> > necessary.\n> >\n> > In decrease runtime time about 25 % on this small example.\n> >\n> > do $$\n> > declare i int;\n> > begin\n> >   i := 0;\n> >   while i < 10000000\n> >   loop\n> >     i := i + 1;\n> >   end loop;\n> > end;\n> > $$;\n> >\n> > If there are more expressions, then speedup can be more\n> interesting. If\n> > there are other bottlenecks, then the speedup will be less. 25%\n> is not bad,\n> > so we want to this feature.\n> >\n> > I believe so similar method can be used more aggressively with more\n> > significant performance benefit, but this is low hanging fruit\n> and isn't\n> > reason to wait for future.\n> >\n> > This patch doesn't introduce any new feature, so new tests and\n> new doc is\n> > not necessary.\n> > The patch is readable, well  formatted, only comments are too\n> long. I fixed\n> > it.\n> > All tests passed\n> > I fixed few warnings, and I reformated little bit function\n> > expr_needs_snapshot to use if instead case, what is more usual\n> in these\n> > cases.\n> >\n> > I think so this code can be marked as ready for commit\n>\n> I have some comments on this.\n>\n> expr_needs_snapshot checks out some of the node already checked out in\n> exec_simple_check_plan but not all. However I don't see the criteria\n> of the choice.\n>\n> I might be too worrying, but maybe we should write the function in\n> white-listed way, that is, expr_needs_snapshot returns false only if\n> the whole tree consists of only the node types known to the\n> function. And any unknown node makes the function return true\n> immediately.\n>\n>\n> has sense\n\nThere are  62 cases handled by expression_tree_walker.\nI have inspected all of them and considered only these 6 to be \n\"dangerous\": intentionally require snapshot.\nFuncExpr, OpExpr, Query, SubPlan, AlternativeSubPlan, SubLink.\n\nSo if I use \"white-list\" approach, I have to enumerate all other 62-6=56 \ncases in expr_needs_snapshot function.\nFrankly speaking I do not this that it is good idea. New nodes are \nrarely added to the Postgres and expression_tree_walker\nin any case has to be changed to handle this new nodes. There are many \nother places where tree walker is used to check presence (or absence)\nof some properties in the tree. And none is this places assume that some \nnewly introduced node may require special handling of this property check.\n\nIn any case, if you think that explicit enumerations of this 56 cases \n(or some subset of them) is good idea, then I will do it.\nIf you have concerns about some particular nodes, I can add them to \n\"black list\".\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\n\n\n\nOn 07.11.2019 15:09, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\n\nčt 7. 11. 2019 v 13:03\n odesílatel Kyotaro Horiguchi <horikyota.ntt@gmail.com>\n napsal:\n\nHello.\n\n At Tue, 5 Nov 2019 22:14:40 +0100, Pavel Stehule <pavel.stehule@gmail.com>\n wrote in \n > Hi\n > \n > pá 23. 8. 2019 v 16:32 odesílatel Konstantin Knizhnik\n <\n > k.knizhnik@postgrespro.ru>\n napsal:\n > \n > >\n > >\n > > On 23.08.2019 14:42, Pavel Stehule wrote:\n > >\n > >\n > > In reality it is not IMMUTABLE function. On second\n hand, there are lot of\n > > application that depends on this behave.\n > >\n > > It is well know trick how to reduce estimation\n errors related to JOINs.\n > > When immutable function has constant parameters,\n then it is evaluated in\n > > planning time.\n > >\n > > So sometimes was necessary to use\n > >\n > > SELECT ... FROM tab WHERE foreign_key =\n immutable_function('constant\n > > parameter')\n > >\n > > instead JOIN.\n > >\n > > It is ugly, but it is working perfectly. I think\n so until we will have\n > > multi table statistics, this behave should be\n available in Postgres.\n > >\n > > Sure, this function should not be used for\n functional indexes.\n > >\n > >\n > >\n > > What about the following version of the patch?\n > >\n > \n > I am sending review of this small patch.\n > \n > This small patch reduce a overhead of usage buildin\n immutable functions in\n > volatile functions with simple trick. Starts snapshot\n only when it is\n > necessary.\n > \n > In decrease runtime time about 25 % on this small\n example.\n > \n > do $$\n > declare i int;\n > begin\n >   i := 0;\n >   while i < 10000000\n >   loop\n >     i := i + 1;\n >   end loop;\n > end;\n > $$;\n > \n > If there are more expressions, then speedup can be more\n interesting. If\n > there are other bottlenecks, then the speedup will be\n less. 25% is not bad,\n > so we want to this feature.\n > \n > I believe so similar method can be used more\n aggressively with more\n > significant performance benefit, but this is low\n hanging fruit and isn't\n > reason to wait for future.\n > \n > This patch doesn't introduce any new feature, so new\n tests and new doc is\n > not necessary.\n > The patch is readable, well  formatted, only comments\n are too long. I fixed\n > it.\n > All tests passed\n > I fixed few warnings, and I reformated little bit\n function\n > expr_needs_snapshot to use if instead case, what is\n more usual in these\n > cases.\n > \n > I think so this code can be marked as ready for commit\n\n I have some comments on this.\n\n expr_needs_snapshot checks out some of the node already\n checked out in\n exec_simple_check_plan but not all. However I don't see the\n criteria\n of the choice.\n\n I might be too worrying, but maybe we should write the\n function in\n white-listed way, that is, expr_needs_snapshot returns false\n only if\n the whole tree consists of only the node types known to the\n function. And any unknown node makes the function return\n true\n immediately.\n\n\n\nhas sense\n\n\n\n\n There are  62 cases handled by expression_tree_walker.\n I have inspected all of them and considered only these 6 to be\n \"dangerous\": intentionally require snapshot.\n FuncExpr, OpExpr, Query, SubPlan, AlternativeSubPlan, SubLink.\n\n So if I use \"white-list\" approach, I have to enumerate all other\n 62-6=56 cases in expr_needs_snapshot function.\n Frankly speaking I do not this that it is good idea. New nodes are\n rarely added to the Postgres and expression_tree_walker\n in any case has to be changed to handle this new nodes. There are\n many other places where tree walker is used to check presence (or\n absence)\n of some properties in the tree. And none is this places assume that\n some newly introduced node may require special handling of this\n property check.\n\n In any case, if you think that explicit enumerations of this 56\n cases (or some subset of them) is good idea, then I will do it.\n If you have concerns about some particular nodes, I can add them to \n \"black list\".\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 8 Nov 2019 16:31:07 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "pá 8. 11. 2019 v 14:31 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 07.11.2019 15:09, Pavel Stehule wrote:\n>\n>\n>\n> čt 7. 11. 2019 v 13:03 odesílatel Kyotaro Horiguchi <\n> horikyota.ntt@gmail.com> napsal:\n>\n>> Hello.\n>>\n>> At Tue, 5 Nov 2019 22:14:40 +0100, Pavel Stehule <pavel.stehule@gmail.com>\n>> wrote in\n>> > Hi\n>> >\n>> > pá 23. 8. 2019 v 16:32 odesílatel Konstantin Knizhnik <\n>> > k.knizhnik@postgrespro.ru> napsal:\n>> >\n>> > >\n>> > >\n>> > > On 23.08.2019 14:42, Pavel Stehule wrote:\n>> > >\n>> > >\n>> > > In reality it is not IMMUTABLE function. On second hand, there are\n>> lot of\n>> > > application that depends on this behave.\n>> > >\n>> > > It is well know trick how to reduce estimation errors related to\n>> JOINs.\n>> > > When immutable function has constant parameters, then it is evaluated\n>> in\n>> > > planning time.\n>> > >\n>> > > So sometimes was necessary to use\n>> > >\n>> > > SELECT ... FROM tab WHERE foreign_key = immutable_function('constant\n>> > > parameter')\n>> > >\n>> > > instead JOIN.\n>> > >\n>> > > It is ugly, but it is working perfectly. I think so until we will have\n>> > > multi table statistics, this behave should be available in Postgres.\n>> > >\n>> > > Sure, this function should not be used for functional indexes.\n>> > >\n>> > >\n>> > >\n>> > > What about the following version of the patch?\n>> > >\n>> >\n>> > I am sending review of this small patch.\n>> >\n>> > This small patch reduce a overhead of usage buildin immutable functions\n>> in\n>> > volatile functions with simple trick. Starts snapshot only when it is\n>> > necessary.\n>> >\n>> > In decrease runtime time about 25 % on this small example.\n>> >\n>> > do $$\n>> > declare i int;\n>> > begin\n>> > i := 0;\n>> > while i < 10000000\n>> > loop\n>> > i := i + 1;\n>> > end loop;\n>> > end;\n>> > $$;\n>> >\n>> > If there are more expressions, then speedup can be more interesting. If\n>> > there are other bottlenecks, then the speedup will be less. 25% is not\n>> bad,\n>> > so we want to this feature.\n>> >\n>> > I believe so similar method can be used more aggressively with more\n>> > significant performance benefit, but this is low hanging fruit and isn't\n>> > reason to wait for future.\n>> >\n>> > This patch doesn't introduce any new feature, so new tests and new doc\n>> is\n>> > not necessary.\n>> > The patch is readable, well formatted, only comments are too long. I\n>> fixed\n>> > it.\n>> > All tests passed\n>> > I fixed few warnings, and I reformated little bit function\n>> > expr_needs_snapshot to use if instead case, what is more usual in these\n>> > cases.\n>> >\n>> > I think so this code can be marked as ready for commit\n>>\n>> I have some comments on this.\n>>\n>> expr_needs_snapshot checks out some of the node already checked out in\n>> exec_simple_check_plan but not all. However I don't see the criteria\n>> of the choice.\n>>\n>> I might be too worrying, but maybe we should write the function in\n>> white-listed way, that is, expr_needs_snapshot returns false only if\n>> the whole tree consists of only the node types known to the\n>> function. And any unknown node makes the function return true\n>> immediately.\n>>\n>\n> has sense\n>\n>\n> There are 62 cases handled by expression_tree_walker.\n> I have inspected all of them and considered only these 6 to be\n> \"dangerous\": intentionally require snapshot.\n> FuncExpr, OpExpr, Query, SubPlan, AlternativeSubPlan, SubLink.\n>\n> So if I use \"white-list\" approach, I have to enumerate all other 62-6=56\n> cases in expr_needs_snapshot function.\n> Frankly speaking I do not this that it is good idea. New nodes are rarely\n> added to the Postgres and expression_tree_walker\n> in any case has to be changed to handle this new nodes. There are many\n> other places where tree walker is used to check presence (or absence)\n> of some properties in the tree. And none is this places assume that some\n> newly introduced node may require special handling of this property check.\n>\n> In any case, if you think that explicit enumerations of this 56 cases (or\n> some subset of them) is good idea, then I will do it.\n> If you have concerns about some particular nodes, I can add them to\n> \"black list\".\n>\n\nIs question how to implement this feature safely. Isn't possible to use\nsame check for functional indexes?\n\n\n\n>\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\npá 8. 11. 2019 v 14:31 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 07.11.2019 15:09, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\nčt 7. 11. 2019 v 13:03\n odesílatel Kyotaro Horiguchi <horikyota.ntt@gmail.com>\n napsal:\n\nHello.\n\n At Tue, 5 Nov 2019 22:14:40 +0100, Pavel Stehule <pavel.stehule@gmail.com>\n wrote in \n > Hi\n > \n > pá 23. 8. 2019 v 16:32 odesílatel Konstantin Knizhnik\n <\n > k.knizhnik@postgrespro.ru>\n napsal:\n > \n > >\n > >\n > > On 23.08.2019 14:42, Pavel Stehule wrote:\n > >\n > >\n > > In reality it is not IMMUTABLE function. On second\n hand, there are lot of\n > > application that depends on this behave.\n > >\n > > It is well know trick how to reduce estimation\n errors related to JOINs.\n > > When immutable function has constant parameters,\n then it is evaluated in\n > > planning time.\n > >\n > > So sometimes was necessary to use\n > >\n > > SELECT ... FROM tab WHERE foreign_key =\n immutable_function('constant\n > > parameter')\n > >\n > > instead JOIN.\n > >\n > > It is ugly, but it is working perfectly. I think\n so until we will have\n > > multi table statistics, this behave should be\n available in Postgres.\n > >\n > > Sure, this function should not be used for\n functional indexes.\n > >\n > >\n > >\n > > What about the following version of the patch?\n > >\n > \n > I am sending review of this small patch.\n > \n > This small patch reduce a overhead of usage buildin\n immutable functions in\n > volatile functions with simple trick. Starts snapshot\n only when it is\n > necessary.\n > \n > In decrease runtime time about 25 % on this small\n example.\n > \n > do $$\n > declare i int;\n > begin\n >   i := 0;\n >   while i < 10000000\n >   loop\n >     i := i + 1;\n >   end loop;\n > end;\n > $$;\n > \n > If there are more expressions, then speedup can be more\n interesting. If\n > there are other bottlenecks, then the speedup will be\n less. 25% is not bad,\n > so we want to this feature.\n > \n > I believe so similar method can be used more\n aggressively with more\n > significant performance benefit, but this is low\n hanging fruit and isn't\n > reason to wait for future.\n > \n > This patch doesn't introduce any new feature, so new\n tests and new doc is\n > not necessary.\n > The patch is readable, well  formatted, only comments\n are too long. I fixed\n > it.\n > All tests passed\n > I fixed few warnings, and I reformated little bit\n function\n > expr_needs_snapshot to use if instead case, what is\n more usual in these\n > cases.\n > \n > I think so this code can be marked as ready for commit\n\n I have some comments on this.\n\n expr_needs_snapshot checks out some of the node already\n checked out in\n exec_simple_check_plan but not all. However I don't see the\n criteria\n of the choice.\n\n I might be too worrying, but maybe we should write the\n function in\n white-listed way, that is, expr_needs_snapshot returns false\n only if\n the whole tree consists of only the node types known to the\n function. And any unknown node makes the function return\n true\n immediately.\n\n\n\nhas sense\n\n\n\n\n There are  62 cases handled by expression_tree_walker.\n I have inspected all of them and considered only these 6 to be\n \"dangerous\": intentionally require snapshot.\n FuncExpr, OpExpr, Query, SubPlan, AlternativeSubPlan, SubLink.\n\n So if I use \"white-list\" approach, I have to enumerate all other\n 62-6=56 cases in expr_needs_snapshot function.\n Frankly speaking I do not this that it is good idea. New nodes are\n rarely added to the Postgres and expression_tree_walker\n in any case has to be changed to handle this new nodes. There are\n many other places where tree walker is used to check presence (or\n absence)\n of some properties in the tree. And none is this places assume that\n some newly introduced node may require special handling of this\n property check.\n\n In any case, if you think that explicit enumerations of this 56\n cases (or some subset of them) is good idea, then I will do it.\n If you have concerns about some particular nodes, I can add them to \n \"black list\".Is question how to implement this feature safely. Isn't possible to use same check for functional indexes?\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 8 Nov 2019 16:50:16 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru> writes:\n>> čt 7. 11. 2019 v 13:03 odesílatel Kyotaro Horiguchi \n>> <horikyota.ntt@gmail.com <mailto:horikyota.ntt@gmail.com>> napsal:\n>>> I might be too worrying, but maybe we should write the function in\n>>> white-listed way, that is, expr_needs_snapshot returns false only if\n>>> the whole tree consists of only the node types known to the\n>>> function. And any unknown node makes the function return true\n>>> immediately.\n\n> There are  62 cases handled by expression_tree_walker.\n> I have inspected all of them and considered only these 6 to be \n> \"dangerous\": intentionally require snapshot.\n> FuncExpr, OpExpr, Query, SubPlan, AlternativeSubPlan, SubLink.\n\nThis is false on its face. For example, considering OpExpr but not\nits aliases DistinctExpr or NullIfExpr is just obviously wrong.\nScalarArrayOpExpr is another node that might contain a user-defined\nfunction. CoerceViaIO calls I/O functions that might easily not be\nimmutable. RowCompareExpr calls comparison functions that might\nnot be either (they are btree comparison functions, but they could\nbe cross-type comparisons, and we only require those to be stable).\nCoerceToDomain could invoke just about anything at all. Need I\ngo on?\n\n> Frankly speaking I do not this that it is good idea. New nodes are \n> rarely added to the Postgres and expression_tree_walker\n> in any case has to be changed to handle this new nodes. There are many \n> other places where tree walker is used to check presence (or absence)\n> of some properties in the tree. And none is this places assume that some \n> newly introduced node may require special handling of this property check.\n\nNone of those statements are true, in my experience.\n\nIn general, this patch seems like it's learned nothing from our\nexperiences with the late and unlamented exec_simple_check_node()\n(cf commit 00418c612). Having a piece of plpgsql that has to know\nabout all possible \"simple expression\" node types is just a major\nmaintenance headache; but there is no short-cut solution that is\nreally going to be acceptable. Either you're unsafe, or you fail\nto optimize cases that users will complain about, or you write\nand maintain a lot of code.\n\nI'm also pretty displeased with the is-it-in-the-pg_catalog-schema\ntests. Those are expensive, requiring additional catalog lookups,\nand they prove just about nothing. There are extensions that shove\nstuff into pg_catalog (look no further than contrib/adminpack), or\nusers could do it, so you really still are relying on the whole world\nto get immutability right. If we're going to not trust immutability\nmarkings on user-defined objects, I'd be inclined to do it by\nchecking that the object's OID is less than FirstGenbkiObjectId.\n\nBut maybe we should just forget that bit of paranoia and rely solely\non contain_mutable_functions(). That gets rid of the new maintenance\nrequirement, and I think arguably it's OK. An \"immutable\" function\nwhose result depends on changes that were just made by the calling\nfunction is pretty obviously mislabeled, so people won't have much of\na leg to stand on if they complain about that. Pavel's argument\nupthread that people sometimes intentionally mislabel functions as\nimmutable isn't really relevant: in his example, at least, the user\nis intentionally trying to get the function to be evaluated early.\nSo whether it sees the effects of changes just made by the calling\nfunction doesn't seem like it would matter to such a user.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 11 Nov 2019 12:22:54 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "\n\nOn 11.11.2019 20:22, Tom Lane wrote:\n>\n> None of those statements are true, in my experience.\n>\n> In general, this patch seems like it's learned nothing from our\n> experiences with the late and unlamented exec_simple_check_node()\n> (cf commit 00418c612). Having a piece of plpgsql that has to know\n> about all possible \"simple expression\" node types is just a major\n> maintenance headache; but there is no short-cut solution that is\n> really going to be acceptable. Either you're unsafe, or you fail\n> to optimize cases that users will complain about, or you write\n> and maintain a lot of code.\n>\n> I'm also pretty displeased with the is-it-in-the-pg_catalog-schema\n> tests. Those are expensive, requiring additional catalog lookups,\n> and they prove just about nothing. There are extensions that shove\n> stuff into pg_catalog (look no further than contrib/adminpack), or\n> users could do it, so you really still are relying on the whole world\n> to get immutability right. If we're going to not trust immutability\n> markings on user-defined objects, I'd be inclined to do it by\n> checking that the object's OID is less than FirstGenbkiObjectId.\n>\n> But maybe we should just forget that bit of paranoia and rely solely\n> on contain_mutable_functions(). That gets rid of the new maintenance\n> requirement, and I think arguably it's OK. An \"immutable\" function\n> whose result depends on changes that were just made by the calling\n> function is pretty obviously mislabeled, so people won't have much of\n> a leg to stand on if they complain about that. Pavel's argument\n> upthread that people sometimes intentionally mislabel functions as\n> immutable isn't really relevant: in his example, at least, the user\n> is intentionally trying to get the function to be evaluated early.\n> So whether it sees the effects of changes just made by the calling\n> function doesn't seem like it would matter to such a user.\n>\n> \t\t\tregards, tom lane\n\nIn my opinion contain_mutable_functions() is the best solution.\nBut if it is not acceptable, I will rewrite the patch in white-list fashion.\n\nI do not understand the argument about expensive \nis-it-in-the-pg_catalog-schema test.\nIsCatalogNameaspace is doing just simple comparison without any catalog \nlookups:\n\nbool\nIsCatalogNamespace(Oid namespaceId)\n{\n     return namespaceId == PG_CATALOG_NAMESPACE;\n}\n\nI may agree that it \"proves nothing\" if extension can put stuff in \npg_catalog.\nI can replace it with comparison with FirstGenbkiObjectId.\nBut all this makes sense only if using contain_mutable_function() is not \nacceptable.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Tue, 12 Nov 2019 11:27:24 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "At Tue, 12 Nov 2019 11:27:24 +0300, Konstantin Knizhnik <k.knizhnik@postgrespro.ru> wrote in \n> \n> \n> On 11.11.2019 20:22, Tom Lane wrote:\n> >\n> > None of those statements are true, in my experience.\n> >\n> > In general, this patch seems like it's learned nothing from our\n> > experiences with the late and unlamented exec_simple_check_node()\n> > (cf commit 00418c612). Having a piece of plpgsql that has to know\n> > about all possible \"simple expression\" node types is just a major\n> > maintenance headache; but there is no short-cut solution that is\n> > really going to be acceptable. Either you're unsafe, or you fail\n> > to optimize cases that users will complain about, or you write\n> > and maintain a lot of code.\n> >\n> > I'm also pretty displeased with the is-it-in-the-pg_catalog-schema\n> > tests. Those are expensive, requiring additional catalog lookups,\n> > and they prove just about nothing. There are extensions that shove\n> > stuff into pg_catalog (look no further than contrib/adminpack), or\n> > users could do it, so you really still are relying on the whole world\n> > to get immutability right. If we're going to not trust immutability\n> > markings on user-defined objects, I'd be inclined to do it by\n> > checking that the object's OID is less than FirstGenbkiObjectId.\n> >\n> > But maybe we should just forget that bit of paranoia and rely solely\n> > on contain_mutable_functions(). That gets rid of the new maintenance\n> > requirement, and I think arguably it's OK. An \"immutable\" function\n> > whose result depends on changes that were just made by the calling\n> > function is pretty obviously mislabeled, so people won't have much of\n> > a leg to stand on if they complain about that. Pavel's argument\n> > upthread that people sometimes intentionally mislabel functions as\n> > immutable isn't really relevant: in his example, at least, the user\n> > is intentionally trying to get the function to be evaluated early.\n> > So whether it sees the effects of changes just made by the calling\n> > function doesn't seem like it would matter to such a user.\n> >\n> > \t\t\tregards, tom lane\n> \n> In my opinion contain_mutable_functions() is the best solution.\n> But if it is not acceptable, I will rewrite the patch in white-list\n> fashion.\n\nI agree for just relying on contain_mutable_functions for the same\nreasons to Tom.\n\n> I do not understand the argument about expensive\n> is-it-in-the-pg_catalog-schema test.\n> IsCatalogNameaspace is doing just simple comparison without any\n> catalog lookups:\n> \n> bool\n> IsCatalogNamespace(Oid namespaceId)\n> {\n>     return namespaceId == PG_CATALOG_NAMESPACE;\n> }\n> \n> I may agree that it \"proves nothing\" if extension can put stuff in\n> pg_catalog.\n> I can replace it with comparison with FirstGenbkiObjectId.\n> But all this makes sense only if using contain_mutable_function() is\n> not acceptable.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Wed, 13 Nov 2019 10:25:47 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "Kyotaro Horiguchi <horikyota.ntt@gmail.com> writes:\n> At Tue, 12 Nov 2019 11:27:24 +0300, Konstantin Knizhnik <k.knizhnik@postgrespro.ru> wrote in \n>> In my opinion contain_mutable_functions() is the best solution.\n>> But if it is not acceptable, I will rewrite the patch in white-list\n>> fashion.\n\n> I agree for just relying on contain_mutable_functions for the same\n> reasons to Tom.\n\nI've set the CF entry to \"Waiting on Author\" pending a new patch\nthat does it like that.\n\n>> I do not understand the argument about expensive\n>> is-it-in-the-pg_catalog-schema test.\n>> IsCatalogNameaspace is doing just simple comparison without any\n>> catalog lookups:\n\nAs far as that goes, get_func_namespace() is the expensive part,\nnot IsCatalogNamespace(). If we were going to go down this path,\nit'd perhaps be worthwhile to expand that and the adjacent\nfunc_volatile() test into bulkier code that just does one syscache\nfetch of the pg_proc row. But we're not, so it's moot.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 20 Nov 2019 15:18:24 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "> I've set the CF entry to \"Waiting on Author\" pending a new patch\n> that does it like that.\n\nWith contain_mutable_functions the patch becomes trivial.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 21 Nov 2019 12:31:23 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "čt 21. 11. 2019 v 10:31 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n> > I've set the CF entry to \"Waiting on Author\" pending a new patch\n> > that does it like that.\n>\n> With contain_mutable_functions the patch becomes trivial.\n>\n\nStable functions doesn't need own snapshot too, so it is not fully correct,\nbut it is on safe side.\n\nPavel\n\n\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\nčt 21. 11. 2019 v 10:31 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n> I've set the CF entry to \"Waiting on Author\" pending a new patch\n> that does it like that.\n\nWith contain_mutable_functions the patch becomes trivial.Stable functions doesn't need own snapshot too, so it is not fully correct, but it is on safe side.Pavel\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Thu, 21 Nov 2019 19:47:32 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "Pavel Stehule <pavel.stehule@gmail.com> writes:\n> čt 21. 11. 2019 v 10:31 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n>> With contain_mutable_functions the patch becomes trivial.\n\n> Stable functions doesn't need own snapshot too, so it is not fully correct,\n> but it is on safe side.\n\nNo, I doubt that. A stable function is allowed to inspect database state,\nand if it's being called by a volatile function, it has every right to\nexpect that it'd see updates-so-far made by the volatile function.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 21 Nov 2019 14:44:37 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "čt 21. 11. 2019 v 20:44 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:\n\n> Pavel Stehule <pavel.stehule@gmail.com> writes:\n> > čt 21. 11. 2019 v 10:31 odesílatel Konstantin Knizhnik <\n> > k.knizhnik@postgrespro.ru> napsal:\n> >> With contain_mutable_functions the patch becomes trivial.\n>\n> > Stable functions doesn't need own snapshot too, so it is not fully\n> correct,\n> > but it is on safe side.\n>\n> No, I doubt that. A stable function is allowed to inspect database state,\n> and if it's being called by a volatile function, it has every right to\n> expect that it'd see updates-so-far made by the volatile function.\n>\n\nfor this I need new snapshot?\n\n\n> regards, tom lane\n>\n\nčt 21. 11. 2019 v 20:44 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:Pavel Stehule <pavel.stehule@gmail.com> writes:\n> čt 21. 11. 2019 v 10:31 odesílatel Konstantin Knizhnik <\n> k.knizhnik@postgrespro.ru> napsal:\n>> With contain_mutable_functions the patch becomes trivial.\n\n> Stable functions doesn't need own snapshot too, so it is not fully correct,\n> but it is on safe side.\n\nNo, I doubt that.  A stable function is allowed to inspect database state,\nand if it's being called by a volatile function, it has every right to\nexpect that it'd see updates-so-far made by the volatile function.for this I need new snapshot? \n\n                        regards, tom lane", "msg_date": "Fri, 22 Nov 2019 06:15:25 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "At Fri, 22 Nov 2019 06:15:25 +0100, Pavel Stehule <pavel.stehule@gmail.com> wrote in \n> čt 21. 11. 2019 v 20:44 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:\n> \n> > Pavel Stehule <pavel.stehule@gmail.com> writes:\n> > > čt 21. 11. 2019 v 10:31 odesílatel Konstantin Knizhnik <\n> > > k.knizhnik@postgrespro.ru> napsal:\n> > >> With contain_mutable_functions the patch becomes trivial.\n> >\n> > > Stable functions doesn't need own snapshot too, so it is not fully\n> > correct,\n> > > but it is on safe side.\n> >\n> > No, I doubt that. A stable function is allowed to inspect database state,\n> > and if it's being called by a volatile function, it has every right to\n> > expect that it'd see updates-so-far made by the volatile function.\n> \n> for this I need new snapshot?\n\nIt depends on what we regard as \"query\" or \"command\" here. It seems to\nme that every line in a plpgsql function is regarded as a \"query\" for\nstable function, even if the function is called in another \"query\".\n\nIn short, we need it, I think.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 22 Nov 2019 15:33:40 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "pá 22. 11. 2019 v 7:33 odesílatel Kyotaro Horiguchi <horikyota.ntt@gmail.com>\nnapsal:\n\n> At Fri, 22 Nov 2019 06:15:25 +0100, Pavel Stehule <pavel.stehule@gmail.com>\n> wrote in\n> > čt 21. 11. 2019 v 20:44 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:\n> >\n> > > Pavel Stehule <pavel.stehule@gmail.com> writes:\n> > > > čt 21. 11. 2019 v 10:31 odesílatel Konstantin Knizhnik <\n> > > > k.knizhnik@postgrespro.ru> napsal:\n> > > >> With contain_mutable_functions the patch becomes trivial.\n> > >\n> > > > Stable functions doesn't need own snapshot too, so it is not fully\n> > > correct,\n> > > > but it is on safe side.\n> > >\n> > > No, I doubt that. A stable function is allowed to inspect database\n> state,\n> > > and if it's being called by a volatile function, it has every right to\n> > > expect that it'd see updates-so-far made by the volatile function.\n> >\n> > for this I need new snapshot?\n>\n> It depends on what we regard as \"query\" or \"command\" here. It seems to\n> me that every line in a plpgsql function is regarded as a \"query\" for\n> stable function, even if the function is called in another \"query\".\n>\n> In short, we need it, I think.\n>\n\nok, then the limits just to only immutable functions is wrong\n\nI test it, and there is a problem already. We doesn't raise a exception,\nbut the result is wrong\n\n\ncreate table foo(a int);\n\ncreate or replace function f1(int)\nreturns void as $$\nbegin\n insert into foo values($1);\nend;\n$$ language plpgsql;\n\ncreate or replace function f2(int)\nreturns void as $$declare r record;\nbegin\n perform f1(); for r in select * from foo loop raise notice '%', r; end\nloop;\nend;\n$$ language plpgsql immutable; -- or stable with same behave\n\nSo current state is:\n\na) we allow to call volatile functions from nonvolatile (stable, immutable)\nthat really does write\nb) but this change is not visible in parent nonvolatile functions. Is\nvisible only in volatile functions.\n\nIs it expected behave?\n\nSo now, there are described issues already. And the limit to just immutable\nfunction is not enough - these functions should be immutable buildin.\n\nThe core of these problems is based on function's flags related to planner\noptimizations.\n\nMaybe other flags WRITE | READ | PURE can help.\n\nNow we don't know if volatile function writes to database or not - surely\nrandom function doesn't do this. We can implement new set of flags, that\ncan reduce a overhead with snapshots.\n\nThe function random() can be VOLATILE PURE - and we will know, so result\nof this function is not stable, but this function doesn't touch data engine.\n\nWhen we don't have these flags, then the current logic is used, when we\nhave these flags, then it will be used. These flags can be more strict\n\nwe should not to allow any WRITE from READ function, or we should not allow\nREAD from PURE functions.\n\nNotes, comments?\n\nPavel\n\n\nThis test should\n\n>\n> regards.\n>\n> --\n> Kyotaro Horiguchi\n> NTT Open Source Software Center\n>\n\npá 22. 11. 2019 v 7:33 odesílatel Kyotaro Horiguchi <horikyota.ntt@gmail.com> napsal:At Fri, 22 Nov 2019 06:15:25 +0100, Pavel Stehule <pavel.stehule@gmail.com> wrote in \n> čt 21. 11. 2019 v 20:44 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:\n> \n> > Pavel Stehule <pavel.stehule@gmail.com> writes:\n> > > čt 21. 11. 2019 v 10:31 odesílatel Konstantin Knizhnik <\n> > > k.knizhnik@postgrespro.ru> napsal:\n> > >> With contain_mutable_functions the patch becomes trivial.\n> >\n> > > Stable functions doesn't need own snapshot too, so it is not fully\n> > correct,\n> > > but it is on safe side.\n> >\n> > No, I doubt that.  A stable function is allowed to inspect database state,\n> > and if it's being called by a volatile function, it has every right to\n> > expect that it'd see updates-so-far made by the volatile function.\n> \n> for this I need new snapshot?\n\nIt depends on what we regard as \"query\" or \"command\" here. It seems to\nme that every line in a plpgsql function is regarded as a \"query\" for\nstable function, even if the function is called in another \"query\".\n\nIn short, we need it, I think.ok, then the limits just to only immutable functions is wrongI test it, and there is a problem already. We doesn't raise a exception, but the result is wrongcreate table foo(a int);create or replace function f1(int)returns void as $$begin  insert into foo values($1);end;$$ language plpgsql;create or replace function f2(int)returns void as $$declare r record;begin  perform f1(); for r in select * from foo loop raise notice '%', r; end loop; end;$$ language plpgsql immutable; -- or stable with same behaveSo current state is:a) we allow to call volatile functions from nonvolatile (stable, immutable) that really does writeb) but this change is not visible in parent nonvolatile functions. Is visible only in volatile functions. Is it expected behave?So now, there are described issues already. And the limit to just immutable function is not enough - these functions should be immutable buildin.The core of these problems is based on function's flags related to planner optimizations. Maybe other flags WRITE | READ | PURE can help. Now we don't know if volatile function writes to database or not - surely random function doesn't do this. We can implement new set of flags, that can reduce a overhead with snapshots.The function random() can be VOLATILE PURE - and we will know, so  result of this function is not stable, but this function doesn't touch data engine.When we don't have these flags, then the current logic is used, when we have these flags, then it will be used. These flags can be more strictwe should not to allow any WRITE from READ function, or we should not allow READ from PURE functions.Notes, comments?PavelThis test should \n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Fri, 22 Nov 2019 08:08:24 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "On 22.11.2019 10:08, Pavel Stehule wrote:\n>\n> I test it, and there is a problem already. We doesn't raise a \n> exception, but the result is wrong\n>\n>\n> create table foo(a int);\n>\n> create or replace function f1(int)\n> returns void as $$\n> begin\n>   insert into foo values($1);\n> end;\n> $$ language plpgsql;\n>\n> create or replace function f2(int)\n> returns void as $$declare r record;\n> begin\n>   perform f1(); for r in select * from foo loop raise notice '%', r; \n> end loop;\n> end;\n> $$ language plpgsql immutable; -- or stable with same behave\n>\n> So current state is:\n>\n> a) we allow to call volatile functions from nonvolatile (stable, \n> immutable) that really does write\n> b) but this change is not visible in parent nonvolatile functions. Is \n> visible only in volatile functions.\n>\n> Is it expected behave?\n\nI think that in theory it is definitely not correct to call volatile \nfunction from non-volatile.\nBut there are two questions:\n1. Are we able to check it? Please taken in account that:\n  - at the moment of \"create function f2()\"  called function f1() may \nnot yet be defined\n  - instead of perform f1() it can do \"execute 'select f1()'\" and it is \nnot possible to check it at compile time.\n2. Is it responsibility of programmer to correctly specify function \nproperties or it should be done by compiler?\n   If we follow YWIYGI rule, then your definition of f2() is not correct \nand that it is why you will get wrong result in this case.\n   If we what to completely rely on compiler, then... we do not not \nvolatile/immutable/stable/qualifiers at all! Compiler should deduce this \ninformation itself.\n   But it will be non-trivial if ever possible, take in account 1)\n\nIn principle it is possible to add checks which will produce warning in \ncase of calling volatile function or executing dynamic SQL from \nnon-volatile function.\nIf such extra checking will be considered useful, I can propose patch \ndoing it.\nBut IMHO optimizer should rely on function qualifier provided by \nprogrammer and it is acceptable to produce wrong result if this \ninformation is not correct.\n\n>\n> So now, there are described issues already. And the limit to just \n> immutable function is not enough - these functions should be immutable \n> buildin.\n>\n> The core of these problems is based on function's flags related to \n> planner optimizations.\n>\n> Maybe other flags WRITE | READ | PURE can help.\n>\n> Now we don't know if volatile function writes to database or not - \n> surely random function doesn't do this. We can implement new set of \n> flags, that can reduce a overhead with snapshots.\n>\n> The function random() can be VOLATILE PURE - and we will know, so  \n> result of this function is not stable, but this function doesn't touch \n> data engine.\n>\n> When we don't have these flags, then the current logic is used, when \n> we have these flags, then it will be used. These flags can be more strict\n>\n> we should not to allow any WRITE from READ function, or we should not \n> allow READ from PURE functions.\n>\n> Notes, comments?\nI think that even current model with \"volatile\", \"immutable\" and \n\"stable\" is complex enough.\nAdding more qualifiers will make it even more obscure and error-prone.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\n\n\n\nOn 22.11.2019 10:08, Pavel Stehule\n wrote:\n\n\n\n\n\nI test it, and there is a problem already. We doesn't\n raise a exception, but the result is wrong\n\n\n\n\ncreate table foo(a int);\n\n\ncreate or replace function f1(int)\n returns void as $$\n begin\n   insert into foo values($1);\n end;\n $$ language plpgsql;\n\n\ncreate or replace function f2(int)\n returns void as $$declare r record;\n begin\n   perform f1(); for r in select * from foo loop raise notice\n '%', r; end loop; \n end;\n $$ language plpgsql immutable; -- or stable with same behave\n\n\n\nSo current state is:\n\n\na) we allow to call volatile functions from nonvolatile\n (stable, immutable) that really does write\n\nb) but this change is not visible in parent nonvolatile\n functions. Is visible only in volatile functions. \n\n\n\nIs it expected behave?\n\n\n\n\n\n I think that in theory it is definitely not correct to call volatile\n function from non-volatile. \n But there are two questions:\n 1. Are we able to check it? Please taken in account that:\n  - at the moment of \"create function f2()\"  called function f1() may\n not yet be defined \n  - instead of perform f1() it can do \"execute 'select f1()'\" and it\n is not possible to check it at compile time.  \n 2. Is it responsibility of programmer to correctly specify function\n properties or it should be done by compiler? \n   If we follow YWIYGI rule, then your definition of f2() is not\n correct and that it is why you will get wrong result in this case.\n   If we what to completely rely on compiler, then... we do not not\n volatile/immutable/stable/qualifiers at all! Compiler should deduce\n this information itself.\n   But it will be non-trivial if ever possible, take in account 1) \n\n In principle it is possible to add checks which will produce warning\n in case of calling volatile function or executing dynamic SQL from\n non-volatile function. \n If such extra checking will be considered useful, I can propose\n patch doing it.\n But IMHO optimizer should rely on function qualifier provided by\n programmer and it is acceptable to produce wrong result if this\n information is not correct.\n\n\n\n\n\n\nSo now, there are described issues already. And the limit\n to just immutable function is not enough - these functions\n should be immutable buildin.\n\n\nThe core of these problems is based on function's flags\n related to planner optimizations. \n\n\n\nMaybe other flags WRITE | READ | PURE can help. \n\n\n\nNow we don't know if volatile function writes to database\n or not - surely random function doesn't do this. We can\n implement new set of flags, that can reduce a overhead with\n snapshots.\n\n\nThe function random() can be VOLATILE PURE - and we will\n know, so  result of this function is not stable, but this\n function doesn't touch data engine.\n\n\nWhen we don't have these flags, then the current logic is\n used, when we have these flags, then it will be used. These\n flags can be more strict\n\n\nwe should not to allow any WRITE from READ function, or\n we should not allow READ from PURE functions.\n\n\nNotes, comments?\n\n\n\n I think that even current model with \"volatile\", \"immutable\" and\n \"stable\" is complex enough.\n Adding more qualifiers will make it even more obscure and\n error-prone.\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 22 Nov 2019 10:32:51 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "pá 22. 11. 2019 v 8:32 odesílatel Konstantin Knizhnik <\nk.knizhnik@postgrespro.ru> napsal:\n\n>\n>\n> On 22.11.2019 10:08, Pavel Stehule wrote:\n>\n>\n> I test it, and there is a problem already. We doesn't raise a exception,\n> but the result is wrong\n>\n>\n> create table foo(a int);\n>\n> create or replace function f1(int)\n> returns void as $$\n> begin\n> insert into foo values($1);\n> end;\n> $$ language plpgsql;\n>\n> create or replace function f2(int)\n> returns void as $$declare r record;\n> begin\n> perform f1(); for r in select * from foo loop raise notice '%', r; end\n> loop;\n> end;\n> $$ language plpgsql immutable; -- or stable with same behave\n>\n> So current state is:\n>\n> a) we allow to call volatile functions from nonvolatile (stable,\n> immutable) that really does write\n> b) but this change is not visible in parent nonvolatile functions. Is\n> visible only in volatile functions.\n>\n> Is it expected behave?\n>\n>\n> I think that in theory it is definitely not correct to call volatile\n> function from non-volatile.\n> But there are two questions:\n> 1. Are we able to check it? Please taken in account that:\n> - at the moment of \"create function f2()\" called function f1() may not\n> yet be defined\n> - instead of perform f1() it can do \"execute 'select f1()'\" and it is not\n> possible to check it at compile time.\n>\n\nIt's not possible to check it compile time now.\n\n2. Is it responsibility of programmer to correctly specify function\n> properties or it should be done by compiler?\n> If we follow YWIYGI rule, then your definition of f2() is not correct\n> and that it is why you will get wrong result in this case.\n>\n\nmaybe - a) but it is not documented, b) is not a postgresql's philosophy\nreturn bad result - and c) it is not user friendly. There should be raised\nerror or result should be correct.\n\nTheoretically this feature can be used for logging - you can write to log\ntable from immutable or stable function - so it can has some use case.\nProbably if we implement autonomous transactions, then this behave should\nbe correct.\n\n>\n> If we what to completely rely on compiler, then... we do not not\n> volatile/immutable/stable/qualifiers at all! Compiler should deduce this\n> information itself.\n> But it will be non-trivial if ever possible, take in account 1)\n>\n\nI am able to do it in plpgsql_check for plpgsql. But probably it is not\npossible do it for PLPerl, PLPythonu, ..\n\n>\n> In principle it is possible to add checks which will produce warning in\n> case of calling volatile function or executing dynamic SQL from\n> non-volatile function.\n> If such extra checking will be considered useful, I can propose patch\n> doing it.\n> But IMHO optimizer should rely on function qualifier provided by\n> programmer and it is acceptable to produce wrong result if this information\n> is not correct.\n>\n\nWe should to distinguish between bad result and not well optimized plan.\n\n\n\n>\n> So now, there are described issues already. And the limit to just\n> immutable function is not enough - these functions should be immutable\n> buildin.\n>\n> The core of these problems is based on function's flags related to planner\n> optimizations.\n>\n> Maybe other flags WRITE | READ | PURE can help.\n>\n> Now we don't know if volatile function writes to database or not - surely\n> random function doesn't do this. We can implement new set of flags, that\n> can reduce a overhead with snapshots.\n>\n> The function random() can be VOLATILE PURE - and we will know, so result\n> of this function is not stable, but this function doesn't touch data engine.\n>\n> When we don't have these flags, then the current logic is used, when we\n> have these flags, then it will be used. These flags can be more strict\n>\n> we should not to allow any WRITE from READ function, or we should not\n> allow READ from PURE functions.\n>\n> Notes, comments?\n>\n> I think that even current model with \"volatile\", \"immutable\" and \"stable\"\n> is complex enough.\n> Adding more qualifiers will make it even more obscure and error-prone.\n>\n\nI don't think - the classic example is random() function. It's volatile,\nbut you don't need special snapshot for calling this function.\n\nStill any change of behave can breaks lot of applications, because how we\ncan see, Postgres is very tolerant now.\n\n\n> --\n> Konstantin Knizhnik\n> Postgres Professional: http://www.postgrespro.com\n> The Russian Postgres Company\n>\n>\n\npá 22. 11. 2019 v 8:32 odesílatel Konstantin Knizhnik <k.knizhnik@postgrespro.ru> napsal:\n\n\n\nOn 22.11.2019 10:08, Pavel Stehule\n wrote:\n\n\n\n\nI test it, and there is a problem already. We doesn't\n raise a exception, but the result is wrong\n\n\n\n\ncreate table foo(a int);\n\n\ncreate or replace function f1(int)\n returns void as $$\n begin\n   insert into foo values($1);\n end;\n $$ language plpgsql;\n\n\ncreate or replace function f2(int)\n returns void as $$declare r record;\n begin\n   perform f1(); for r in select * from foo loop raise notice\n '%', r; end loop; \n end;\n $$ language plpgsql immutable; -- or stable with same behave\n\n\n\nSo current state is:\n\n\na) we allow to call volatile functions from nonvolatile\n (stable, immutable) that really does write\n\nb) but this change is not visible in parent nonvolatile\n functions. Is visible only in volatile functions. \n\n\n\nIs it expected behave?\n\n\n\n\n\n I think that in theory it is definitely not correct to call volatile\n function from non-volatile. \n But there are two questions:\n 1. Are we able to check it? Please taken in account that:\n  - at the moment of \"create function f2()\"  called function f1() may\n not yet be defined \n  - instead of perform f1() it can do \"execute 'select f1()'\" and it\n is not possible to check it at compile time.  It's not possible to check it compile time now. \n 2. Is it responsibility of programmer to correctly specify function\n properties or it should be done by compiler? \n   If we follow YWIYGI rule, then your definition of f2() is not\n correct and that it is why you will get wrong result in this case.maybe - a) but it is not documented, b) is not a postgresql's philosophy return bad result - and c) it is not user friendly. There should be raised error or result should be correct.Theoretically this feature can be used for logging - you can write to log table from immutable or stable function - so it can has some use case. Probably if we implement autonomous transactions, then this behave should be correct.  \n   If we what to completely rely on compiler, then... we do not not\n volatile/immutable/stable/qualifiers at all! Compiler should deduce\n this information itself.\n   But it will be non-trivial if ever possible, take in account 1) I am able to do it in plpgsql_check for plpgsql. But probably it is not possible do it for PLPerl, PLPythonu, .. \n\n In principle it is possible to add checks which will produce warning\n in case of calling volatile function or executing dynamic SQL from\n non-volatile function. \n If such extra checking will be considered useful, I can propose\n patch doing it.\n But IMHO optimizer should rely on function qualifier provided by\n programmer and it is acceptable to produce wrong result if this\n information is not correct.We should to distinguish  between bad result and not well optimized plan. \n\n\n\n\n\n\nSo now, there are described issues already. And the limit\n to just immutable function is not enough - these functions\n should be immutable buildin.\n\n\nThe core of these problems is based on function's flags\n related to planner optimizations. \n\n\n\nMaybe other flags WRITE | READ | PURE can help. \n\n\n\nNow we don't know if volatile function writes to database\n or not - surely random function doesn't do this. We can\n implement new set of flags, that can reduce a overhead with\n snapshots.\n\n\nThe function random() can be VOLATILE PURE - and we will\n know, so  result of this function is not stable, but this\n function doesn't touch data engine.\n\n\nWhen we don't have these flags, then the current logic is\n used, when we have these flags, then it will be used. These\n flags can be more strict\n\n\nwe should not to allow any WRITE from READ function, or\n we should not allow READ from PURE functions.\n\n\nNotes, comments?\n\n\n\n I think that even current model with \"volatile\", \"immutable\" and\n \"stable\" is complex enough.\n Adding more qualifiers will make it even more obscure and\n error-prone.I don't think - the classic example is random() function. It's volatile, but you don't need special snapshot for calling this function.Still any change of behave can breaks lot of applications, because how we can see, Postgres is very tolerant now. \n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 22 Nov 2019 09:05:19 +0100", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "On 22.11.2019 11:05, Pavel Stehule wrote:\n>\n>\n> We should to distinguish  between bad result and not well optimized plan.\n>\nIf it is not possible to implement runtime check tha timmutable function \nis not making any changes in database.\nPlease notice, that even right now without any get snapshot optimization \nPostgres can produce incorrect result in case of incorrectly specidied \nimmutable or stable qualifiers.\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n\n\n\n\n\n\nOn 22.11.2019 11:05, Pavel Stehule\n wrote:\n\n\n\n\n\n\n\nWe should to distinguish  between bad result and not well\n optimized plan. \n\n\n\n\n\n\n If it is not possible to implement runtime check tha timmutable\n function is not making any changes in database.\n Please notice, that even right now without any get snapshot\n optimization Postgres can produce incorrect result in case of\n incorrectly specidied immutable or stable qualifiers.\n\n\n-- \nKonstantin Knizhnik\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 22 Nov 2019 11:15:51 +0300", "msg_from": "Konstantin Knizhnik <k.knizhnik@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "At Fri, 22 Nov 2019 08:08:24 +0100, Pavel Stehule <pavel.stehule@gmail.com> wrote in \n> pá 22. 11. 2019 v 7:33 odesílatel Kyotaro Horiguchi <horikyota.ntt@gmail.com>\n> napsal:\n> \n> > At Fri, 22 Nov 2019 06:15:25 +0100, Pavel Stehule <pavel.stehule@gmail.com>\n> > wrote in\n> > > čt 21. 11. 2019 v 20:44 odesílatel Tom Lane <tgl@sss.pgh.pa.us> napsal:\n> > >\n> > > > Pavel Stehule <pavel.stehule@gmail.com> writes:\n> > > > > čt 21. 11. 2019 v 10:31 odesílatel Konstantin Knizhnik <\n> > > > > k.knizhnik@postgrespro.ru> napsal:\n> > > > >> With contain_mutable_functions the patch becomes trivial.\n> > > >\n> > > > > Stable functions doesn't need own snapshot too, so it is not fully\n> > > > correct,\n> > > > > but it is on safe side.\n> > > >\n> > > > No, I doubt that. A stable function is allowed to inspect database\n> > state,\n> > > > and if it's being called by a volatile function, it has every right to\n> > > > expect that it'd see updates-so-far made by the volatile function.\n> > >\n> > > for this I need new snapshot?\n> >\n> > It depends on what we regard as \"query\" or \"command\" here. It seems to\n> > me that every line in a plpgsql function is regarded as a \"query\" for\n> > stable function, even if the function is called in another \"query\".\n> >\n> > In short, we need it, I think.\n> >\n> \n> ok, then the limits just to only immutable functions is wrong\n> \n> I test it, and there is a problem already. We doesn't raise a exception,\n> but the result is wrong\n> \n> create table foo(a int);\n> \n> create or replace function f1(int)\n> returns void as $$\n> begin\n> insert into foo values($1);\n> end;\n> $$ language plpgsql;\n> \n> create or replace function f2(int)\n> returns void as $$declare r record;\n> begin\n> perform f1(); for r in select * from foo loop raise notice '%', r; end\n> loop;\n> end;\n> $$ language plpgsql immutable; -- or stable with same behave\n> \n> So current state is:\n> \n> a) we allow to call volatile functions from nonvolatile (stable, immutable)\n> that really does write\n> b) but this change is not visible in parent nonvolatile functions. Is\n> visible only in volatile functions.\n> \n> Is it expected behave?\n\nI'm not sure, volatility is the total bahavior of the function,\nregardless of whatever the function does internally. Even though I'm\nnot sure how to use volatile functions in non-volatile functions, I\ndon't see direct reason or how to inhibit that and I think we don't\neven need to bother that. It's owe to the definier of the function.\n\n> So now, there are described issues already. And the limit to just immutable\n> function is not enough - these functions should be immutable buildin.\n> \n> The core of these problems is based on function's flags related to planner\n> optimizations.\n> \n> Maybe other flags WRITE | READ | PURE can help.\n> \n> Now we don't know if volatile function writes to database or not - surely\n> random function doesn't do this. We can implement new set of flags, that\n> can reduce a overhead with snapshots.\n> \n> The function random() can be VOLATILE PURE - and we will know, so result\n> of this function is not stable, but this function doesn't touch data engine.\n> \n> When we don't have these flags, then the current logic is used, when we\n> have these flags, then it will be used. These flags can be more strict\n> \n> we should not to allow any WRITE from READ function, or we should not allow\n> READ from PURE functions.\n> \n> Notes, comments?\n> \n> Pavel\n\nI think such fine-grained categorization is beyond our maintainance\ncapability and users still much cannot follow. I recall of an extreme\ndiscussion that the result of immutable system functions still can\nmutate beyond major version upgrade. Volatility is mere a hint and,\nperhaps as Robert said somewhere, the baseline we should do is to\navoid crash for any possible configuration.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 22 Nov 2019 18:41:41 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" }, { "msg_contents": "Kyotaro Horiguchi <horikyota.ntt@gmail.com> writes:\n> At Fri, 22 Nov 2019 08:08:24 +0100, Pavel Stehule <pavel.stehule@gmail.com> wrote in \n>> a) we allow to call volatile functions from nonvolatile (stable, immutable)\n>> that really does write\n>> b) but this change is not visible in parent nonvolatile functions. Is\n>> visible only in volatile functions.\n>> \n>> Is it expected behave?\n\n> I'm not sure, volatility is the total bahavior of the function,\n> regardless of whatever the function does internally. Even though I'm\n> not sure how to use volatile functions in non-volatile functions, I\n> don't see direct reason or how to inhibit that and I think we don't\n> even need to bother that. It's owe to the definier of the function.\n\nI'm pretty sure we had this discussion long ago when we implemented\nthe existing read-only-function restrictions in plpgsql. Yeah, in\nprinciple an immutable function should refuse to call non-immutable\nfunctions, but the practical costs and benefits of doing that aren't\nvery attractive. The existing rules are inexpensive to enforce and\ncatch most mistakes in this area. Catching the other few percent of\nmistakes would require a really significant change, not only on our\npart but also users' parts --- for example, forgetting to label a\nfunction as immutable when it could be might break your application\nentirely.\n\nI made some cosmetic fixes in the proposed patch and pushed it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 22 Nov 2019 15:11:09 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Why overhead of SPI is so large?" } ]
[ { "msg_contents": "We've repeatedly kicked around the idea of getting rid of the\npg_pltemplate catalog in favor of keeping that information directly in\nthe languages' extension files [1][2][3][4]. The primary abstract\nargument for that is that it removes a way in which our in-tree PLs\nare special compared to out-of-tree PLs, which can't have entries in\npg_pltemplate. A concrete argument for it is that it might simplify\nfixing the python-2-vs-python-3 mess, since one of the issues there\nis that pg_pltemplate has hard-wired knowledge that \"plpythonu\" is\nPython 2. Accordingly, attached is a patch series that ends by\nremoving that catalog.\n\nAs I noted in [2], the main stumbling block to doing this is that\nthe code associated with pg_pltemplate provides a privilege override\nmechanism that allows non-superuser database owners to install trusted\nPLs. For backwards compatibility if nothing else, we probably want to\nkeep that ability, though it'd be nice if it weren't such a hard-wired\nbehavior.\n\nPatch 0001 below addresses this problem by inventing a concept of\n\"trustable\" (not necessarily trusted) extensions. An extension that\nwould normally require superuser permissions (e.g., because it creates\nC functions) can now be installed by a non-superuser if (a) it is\nmarked trustable in the extension's control file, AND (b) it is\nlisted as trusted in one of two new GUCs, trusted_extensions_dba and\ntrusted_extensions_anyone. (These names could stand a visit to the\nbikeshed, no doubt.) Extensions matching trusted_extensions_dba can\nbe installed by a database owner, while extensions matching\ntrusted_extensions_anyone can be installed by anybody. The default\nsettings of these GUCs provide backwards-compatible behavior, but\nthey can be adjusted to provide more or less ability to install\nextensions. (This design is basically what Andres advocated in [2].)\n\nIn this patch series, I've only marked the trusted-PL extensions as\ntrustable, but we should probably make most of the contrib extensions\ntrustable --- not, say, adminpack, but surely most of the datatype\nand transform modules could be marked trustable. (Maybe we could\nmake the default GUC settings more permissive, too.)\n\nAs coded, the two GUCs are not lists of extension names but rather\nregexes. You could use them as lists, eg \"^plperl$|^plpgsql$|^pltcl$\"\nbut that's a bit tedious, especially if someone wants to trust most\nor all of contrib. I am a tad worried about user-friendliness of\nthis notation, but I think we need something with wild-cards, and\nthat's the only wild-card-capable matching engine we have available\nat a low level.\n\nYou might wonder why bother with the trustable flag rather than just\nrelying on the GUCs. The answer is mostly paranoia: I'm worried about\nsomebody writing e.g. \"plperl\" with no anchors and not realizing that\nthat will match \"plperlu\" as well. Anyway, since we're talking about\npotential escalation-to-superuser security problems, I think having\nboth belt and suspenders protection on untrusted languages is wise.\n\nThere are no regression tests for this functionality in 0001,\nbut I added one in 0002.\n\nPatch 0002 converts all the in-tree PLs to use fully specified\nCREATE LANGUAGE and not rely on pg_pltemplate.\n\nI had a better idea about how to manage permissions than what was\ndiscussed in [3]; we can just give ownership of the language\nobject to the user calling CREATE EXTENSION. Doing it that way\nmeans that we end up with exactly the same catalog state as we\ndo in existing releases. And that should mean that we don't have\nto treat this as an extension version upgrade. So I just modified\nthe 1.0 scripts in-place instead of adding 1.0--1.1 scripts. It\nlooks to me like there's no need to touch the from-unpackaged\nscripts, either. And by the same token this isn't really an issue\nfor pg_upgrade.\n\n(I noticed while testing this that pg_upgrade fails to preserve\nownership on extensions, but that's not new; this patch is not\nmaking that situation any better or worse than it was. Still,\nmaybe we oughta try to fix that sometime soon too.)\n\nPatch 0003 removes CREATE LANGUAGE's reliance on pg_pltemplate.\nCREATE LANGUAGE without parameters is now interpreted as\nCREATE EXTENSION, thus providing a forward compatibility path\nfor old dump files.\n\nNote: this won't help for *really* old dump files, ie those containing\nCREATE LANGUAGE commands that do have parameters but the parameters are\nwrong according to modern usage. This is a hazard for dumps coming\nfrom 8.0 or older servers; we invented pg_pltemplate in 8.1 primarily\nas a way of cleaning up such dumps [5]. I think that that's far enough\nback that we don't have to worry about how convenient it will be to go\nfrom 8.0-or-older to v13-or-newer in one jump.\n\nFinally, patch 0004 removes the now-unused catalog and cleans up some\nincidental comments referring to it.\n\nOnce this is in, we could start thinking about whether we actually\nwant to change anything about plpython in the near future.\n\n\t\t\tregards, tom lane\n\n[1] https://www.postgresql.org/message-id/flat/763f2fe4-743f-d530-8831-20811edd3d6a%402ndquadrant.com\n[2] https://www.postgresql.org/message-id/flat/7495.1524861244%40sss.pgh.pa.us\n[3] https://www.postgresql.org/message-id/flat/5351890.TdMePpdHBD%40nb.usersys.redhat.com\n[4] https://www.postgresql.org/message-id/flat/CAKmB1PGDAy9mXxSTqUchYEi4iJAA6NKVj4P5BtAzvQ9wSDUwJw@mail.gmail.com\n[5] https://www.postgresql.org/message-id/flat/5088.1125525412@sss.pgh.pa.us", "msg_date": "Wed, 21 Aug 2019 15:29:22 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On 2019-08-21 21:29, Tom Lane wrote:\n> Patch 0001 below addresses this problem by inventing a concept of\n> \"trustable\" (not necessarily trusted) extensions. An extension that\n> would normally require superuser permissions (e.g., because it creates\n> C functions) can now be installed by a non-superuser if (a) it is\n> marked trustable in the extension's control file, AND (b) it is\n> listed as trusted in one of two new GUCs, trusted_extensions_dba and\n> trusted_extensions_anyone. (These names could stand a visit to the\n> bikeshed, no doubt.) Extensions matching trusted_extensions_dba can\n> be installed by a database owner, while extensions matching\n> trusted_extensions_anyone can be installed by anybody. The default\n> settings of these GUCs provide backwards-compatible behavior, but\n> they can be adjusted to provide more or less ability to install\n> extensions. (This design is basically what Andres advocated in [2].)\n\nI think this overall direction is good. I'm not so fond of the interfaces.\n\nUsing GUCs to control some of this creates yet another place where \npermission information is kept, and with it questions about how to get \nto it, how to edit it, or to back it up and restore it, etc. Also, \nlist-based parameters are particularly hard to manage by automated \ntools. I think we can do this within the existing permission system, \nfor example with pre-defined roles (for example, GRANT \npg_create_trusted_extension ...). Also, CREATE EXTENSION should somehow \nbe controlled by the CREATE privilege on the containing database, so a \nseparate setting for database owner vs. regular user might not be \nnecessary. Regular users would need both the role membership (given by \nthe overall superuser) and the privilege within the database (given by \nthe database owner).\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 6 Nov 2019 08:52:29 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> On 2019-08-21 21:29, Tom Lane wrote:\n>> Patch 0001 below addresses this problem by inventing a concept of\n>> \"trustable\" (not necessarily trusted) extensions. An extension that\n>> would normally require superuser permissions (e.g., because it creates\n>> C functions) can now be installed by a non-superuser if (a) it is\n>> marked trustable in the extension's control file, AND (b) it is\n>> listed as trusted in one of two new GUCs, trusted_extensions_dba and\n>> trusted_extensions_anyone.\n\n> I think this overall direction is good. I'm not so fond of the interfaces.\n\n> Using GUCs to control some of this creates yet another place where \n> permission information is kept, and with it questions about how to get \n> to it, how to edit it, or to back it up and restore it, etc. Also, \n> list-based parameters are particularly hard to manage by automated \n> tools. I think we can do this within the existing permission system, \n> for example with pre-defined roles (for example, GRANT \n> pg_create_trusted_extension ...). Also, CREATE EXTENSION should somehow \n> be controlled by the CREATE privilege on the containing database, so a \n> separate setting for database owner vs. regular user might not be \n> necessary. Regular users would need both the role membership (given by \n> the overall superuser) and the privilege within the database (given by \n> the database owner).\n\nHm. In principle I'm okay with the idea of having a predefined role\nor two for extension installation. I think though that we could not\neasily make that design emulate the current behavior, wherein database\nowners automatically have the ability to install trusted PLs. The\nsuperuser would have to take the additional step of granting them a\nrole to let them do that. Maybe that's just fine --- from some\nangles it could be seen as an improvement --- but it is an\nincompatibility. Anybody have a problem with that?\n\nDo we need more than one level of extension trust-ability (and more\nthan one predefined role to go with that)? Assuming that we go ahead\nand mark all the safe-looking contrib modules as trustable, granting\n\"pg_install_extensions\" or whatever we call it would then give a DB\nowner more privilege than just the ability to install trusted PLs.\nBut maybe that's fine too.\n\nI agree with the idea of requiring a DB-level privilege as well as\nthe overall role. Is it okay to re-use the CREATE privilege (which\ntoday only allows for CREATE SCHEMA), or do we need another one?\nI think re-using CREATE is probably all right, since it would only be\nuseful for this purpose to users who also have \"pg_install_extensions\".\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 06 Nov 2019 10:06:42 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> > On 2019-08-21 21:29, Tom Lane wrote:\n> >> Patch 0001 below addresses this problem by inventing a concept of\n> >> \"trustable\" (not necessarily trusted) extensions. An extension that\n> >> would normally require superuser permissions (e.g., because it creates\n> >> C functions) can now be installed by a non-superuser if (a) it is\n> >> marked trustable in the extension's control file, AND (b) it is\n> >> listed as trusted in one of two new GUCs, trusted_extensions_dba and\n> >> trusted_extensions_anyone.\n> \n> > I think this overall direction is good. I'm not so fond of the interfaces.\n\nI'm not really thrilled with this interface either.\n\n> > Using GUCs to control some of this creates yet another place where \n> > permission information is kept, and with it questions about how to get \n> > to it, how to edit it, or to back it up and restore it, etc. Also, \n> > list-based parameters are particularly hard to manage by automated \n> > tools. I think we can do this within the existing permission system, \n> > for example with pre-defined roles (for example, GRANT \n> > pg_create_trusted_extension ...). Also, CREATE EXTENSION should somehow \n> > be controlled by the CREATE privilege on the containing database, so a \n> > separate setting for database owner vs. regular user might not be \n> > necessary. Regular users would need both the role membership (given by \n> > the overall superuser) and the privilege within the database (given by \n> > the database owner).\n\nTwo things- first, this doesn't actually cover everything that the\nproposed GUCs do- specifically, the proposed GUCs give you a way to\nlimit what specific extensions are allowed to be installed, and by whom.\nMoving to a GRANT-based system removes the extension specificity and\nleaves with just \"is user X allowed to install extensions\". Second,\nthis approach is requiring that a user who is allowed to create\nextensions must also be allowed to create schemas on the database in\nquestion.\n\n> Hm. In principle I'm okay with the idea of having a predefined role\n> or two for extension installation. I think though that we could not\n> easily make that design emulate the current behavior, wherein database\n> owners automatically have the ability to install trusted PLs. The\n> superuser would have to take the additional step of granting them a\n> role to let them do that. Maybe that's just fine --- from some\n> angles it could be seen as an improvement --- but it is an\n> incompatibility. Anybody have a problem with that?\n\nI'm certainly fine with a little backwards incompatibility breakage to\nremove pg_pltemplate.\n\n> Do we need more than one level of extension trust-ability (and more\n> than one predefined role to go with that)? Assuming that we go ahead\n> and mark all the safe-looking contrib modules as trustable, granting\n> \"pg_install_extensions\" or whatever we call it would then give a DB\n> owner more privilege than just the ability to install trusted PLs.\n> But maybe that's fine too.\n\nI also agree with the idea of making PLs be closer to extensions, and\nthis change would move us in that direction too.\n\n> I agree with the idea of requiring a DB-level privilege as well as\n> the overall role. Is it okay to re-use the CREATE privilege (which\n> today only allows for CREATE SCHEMA), or do we need another one?\n\nIf we just created another one, wouldn't that remove the need to have a\ndatabase role? I certainly understand that default roles in the\ndatabase are useful, but I don't think we should be using them in cases\nwhere a traditional GRANT-based privilege could be used instead, and\nthis certainly seems like a case where a user could just have \"CREATE\nEXTENSION\" as a privilege GRANT'd to their role, at a database level,\nand they would then be able to create (trusted) extensions in that\ndatabase. That would also make it independent of the \"CREATE SCHEMA\"\nprivilege that we have now, removing the need to wonder about the above\nquestion regarding combining the two.\n\nThis is far from the first time we've talked about allowing privilege\nbased control over who is allowed to create what kind of objects in the\nsystem. That kind of fine-grained control over other objects would also\nbe a good improvement to our privilege system (not everyone needs to be\nable to create functions and operators, particularly when those are\nactually roles that are logged into by services who shouldn't ever be\ncreating those kinds of objects even if they, maybe, need to create\ntables or similar...).\n\n> I think re-using CREATE is probably all right, since it would only be\n> useful for this purpose to users who also have \"pg_install_extensions\".\n\nWith this, you couldn't have a user who is able to create extensions but\nnot able to create schemas though. That kind of combining of privileges\ntogether really goes against the general principle of 'least privilege',\nunless the action associated with one necessairly requires the other,\nbut I don't believe that's the case here.\n\nThanks,\n\nStephen", "msg_date": "Thu, 7 Nov 2019 13:38:56 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n>> Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n>>> Using GUCs to control some of this creates yet another place where \n>>> permission information is kept, and with it questions about how to get \n>>> to it, how to edit it, or to back it up and restore it, etc. Also, \n>>> list-based parameters are particularly hard to manage by automated \n>>> tools. I think we can do this within the existing permission system, \n>>> for example with pre-defined roles (for example, GRANT \n>>> pg_create_trusted_extension ...). Also, CREATE EXTENSION should somehow \n>>> be controlled by the CREATE privilege on the containing database, so a \n>>> separate setting for database owner vs. regular user might not be \n>>> necessary. Regular users would need both the role membership (given by \n>>> the overall superuser) and the privilege within the database (given by \n>>> the database owner).\n\n> Two things- first, this doesn't actually cover everything that the\n> proposed GUCs do- specifically, the proposed GUCs give you a way to\n> limit what specific extensions are allowed to be installed, and by whom.\n> Moving to a GRANT-based system removes the extension specificity and\n> leaves with just \"is user X allowed to install extensions\".\n\nTrue. But do we care? We did not have that flexibility before, either.\nI'd still keep the \"trustable\" property (probably renamed to \"trusted\"\nfor simplicity) for extensions, so in the worst case, an admin could\nedit extension control files to add or remove the per-extension flag.\n\n> Second,\n> this approach is requiring that a user who is allowed to create\n> extensions must also be allowed to create schemas on the database in\n> question.\n\nThat doesn't seem like a big objection from here. We could fix it\nby making a separate privilege bit, but I doubt that it's worth using\nup one of our limited set of spare bits for.\n\n>> I agree with the idea of requiring a DB-level privilege as well as\n>> the overall role. Is it okay to re-use the CREATE privilege (which\n>> today only allows for CREATE SCHEMA), or do we need another one?\n\n> If we just created another one, wouldn't that remove the need to have a\n> database role?\n\nNo, because then being DB owner would be alone be enough to let you\ninstall extensions (since as owner, you could certainly grant yourself\nall privileges on the DB, even if this were somehow not the default).\nWe'd have to mangle GRANT's behavior to avoid that, and I don't think\nwe should. Nor do I think that DB ownership ought to be enough\nprivilege by itself.\n\n>> I think re-using CREATE is probably all right, since it would only be\n>> useful for this purpose to users who also have \"pg_install_extensions\".\n\n> With this, you couldn't have a user who is able to create extensions but\n> not able to create schemas though. That kind of combining of privileges\n> together really goes against the general principle of 'least privilege',\n> unless the action associated with one necessairly requires the other,\n> but I don't believe that's the case here.\n\nA point here is that many extensions involve creating their own schemas\nanyway. Also, the ability to \"relocate\" an extension to a different\nschema is pretty meaningless if you can't create a schema to put it in.\n\nIf I thought that there were a use-case for letting someone create\nextensions but not schemas, I'd be more eager to invent a new bit.\nBut I'm having a *really* hard time envisioning a live use-case\nfor that. Granting extension-creation ability requires a whole lot\nmore trust in the grantee than the ability to make new schemas\n(which, in themselves, have about zero impact on anybody else).\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 07 Nov 2019 13:54:12 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> Stephen Frost <sfrost@snowman.net> writes:\n> >> Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> >>> Using GUCs to control some of this creates yet another place where \n> >>> permission information is kept, and with it questions about how to get \n> >>> to it, how to edit it, or to back it up and restore it, etc. Also, \n> >>> list-based parameters are particularly hard to manage by automated \n> >>> tools. I think we can do this within the existing permission system, \n> >>> for example with pre-defined roles (for example, GRANT \n> >>> pg_create_trusted_extension ...). Also, CREATE EXTENSION should somehow \n> >>> be controlled by the CREATE privilege on the containing database, so a \n> >>> separate setting for database owner vs. regular user might not be \n> >>> necessary. Regular users would need both the role membership (given by \n> >>> the overall superuser) and the privilege within the database (given by \n> >>> the database owner).\n> \n> > Two things- first, this doesn't actually cover everything that the\n> > proposed GUCs do- specifically, the proposed GUCs give you a way to\n> > limit what specific extensions are allowed to be installed, and by whom.\n> > Moving to a GRANT-based system removes the extension specificity and\n> > leaves with just \"is user X allowed to install extensions\".\n> \n> True. But do we care? We did not have that flexibility before, either.\n\nI'm not 100% sure that we do, but I wanted to mention it as a\ndifference. Certainly there have previously been suggestions of having\na 'whitelist' similar to what you initially proposed, that are\nextensions which non-superusers are allowed to install.\n\n> I'd still keep the \"trustable\" property (probably renamed to \"trusted\"\n> for simplicity) for extensions, so in the worst case, an admin could\n> edit extension control files to add or remove the per-extension flag.\n\nAt a high level, I agree with the idea of an extension being able to be\nmarked as one that's \"trusted\" or not, but we would also need to come up\nwith exactly what that means for it to really have value, and I don't\nthink we've really done that yet.\n\n> > Second,\n> > this approach is requiring that a user who is allowed to create\n> > extensions must also be allowed to create schemas on the database in\n> > question.\n> \n> That doesn't seem like a big objection from here. We could fix it\n> by making a separate privilege bit, but I doubt that it's worth using\n> up one of our limited set of spare bits for.\n\nI do not agree that we should just shift to using default roles instead\nof adding new options to GRANT because of an entirely internal\nimplementation detail that we could fix (and should, as I've said for\nprobably 10 years now...).\n\n> >> I agree with the idea of requiring a DB-level privilege as well as\n> >> the overall role. Is it okay to re-use the CREATE privilege (which\n> >> today only allows for CREATE SCHEMA), or do we need another one?\n> \n> > If we just created another one, wouldn't that remove the need to have a\n> > database role?\n> \n> No, because then being DB owner would be alone be enough to let you\n> install extensions (since as owner, you could certainly grant yourself\n> all privileges on the DB, even if this were somehow not the default).\n> We'd have to mangle GRANT's behavior to avoid that, and I don't think\n> we should. Nor do I think that DB ownership ought to be enough\n> privilege by itself.\n\nReally? Why do you think that DB ownership shouldn't be enough for\nthis, for trusted extensions?\n\nI agree that we don't want to mangle GRANT's behavior, at all, for this.\n\n> >> I think re-using CREATE is probably all right, since it would only be\n> >> useful for this purpose to users who also have \"pg_install_extensions\".\n> \n> > With this, you couldn't have a user who is able to create extensions but\n> > not able to create schemas though. That kind of combining of privileges\n> > together really goes against the general principle of 'least privilege',\n> > unless the action associated with one necessairly requires the other,\n> > but I don't believe that's the case here.\n> \n> A point here is that many extensions involve creating their own schemas\n> anyway. Also, the ability to \"relocate\" an extension to a different\n> schema is pretty meaningless if you can't create a schema to put it in.\n\nWhat extensions require creating their own schema? Every single\nextension that's in contrib can be installed into the public schema\n(concurrently, even) except for two hacks- plpgsql and adminpack, and\nthose go into pg_catalog for historical reasons more than anything else.\n\nCreating a schema is an option for extensions but it isn't a\nrequirement. I agree that you need the ability to create schemas if you\nwant to relocate one, but that's like needing SELECT to do an UPDATE\nwithout a WHERE clause. I also don't know that extension relocation is\nreally something that's commonly done.\n\n> If I thought that there were a use-case for letting someone create\n> extensions but not schemas, I'd be more eager to invent a new bit.\n> But I'm having a *really* hard time envisioning a live use-case\n> for that. Granting extension-creation ability requires a whole lot\n> more trust in the grantee than the ability to make new schemas\n> (which, in themselves, have about zero impact on anybody else).\n\nThe idea of 'least privilege' isn't \"well, I'm gonna grant you this\nother thing that you don't actually need, just because I trust you with\nthis privilege that you do need.\"\n\nThanks,\n\nStephen", "msg_date": "Thu, 7 Nov 2019 14:13:20 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On 11/7/19 2:13 PM, Stephen Frost wrote:\n\n>> That doesn't seem like a big objection from here. We could fix it\n>> by making a separate privilege bit, but I doubt that it's worth using\n>> up one of our limited set of spare bits for.\n> \n> I do not agree that we should just shift to using default roles instead\n> of adding new options to GRANT because of an entirely internal\n\nAm I mis-following the conversation in some way? I'm having trouble\nseeing this as a question about a privilege bit, because that leads\nstraight on to the question of what database object carries the acl\nitem that grants that bit to a role. An extension isn't yet a database\nobject until after you create it.\n\nSo isn't this more a proposal to add another boolean attribute\nto pg_authid, along the lines of rolcreatedb or rolbypassrls?\n\n\nOn the other hand, maybe thinking of it as a privilege bit could\nlead somewhere interesting. A not-yet-installed extension isn't\na real database object, but it does have a synthesized existence\nas a row in the pg_available_extensions view. Maybe that could\nhave an acl column, where a privilege (why not just CREATE?) could\nbe granted to one or more roles. Synthesizing that could rely on\nsome directive in the control file, or in some separate\nextension_creators.conf file that would associate extensions with\nroles.\n\nThat would avoid using a new bit, avoid adding a pg_authid attribute,\nand avoid setting in stone a particular predefined role or two or\na single final meaning of 'trusted'. A site could create a few roles\nand edit extension_creators.conf to associate extensions with them.\n\nMaybe that's just a more ad-hoc and GUCless way of circling back\nto what the original proposal would be doing with GUCs....\n\nRegards,\n-Chap\n\n\n", "msg_date": "Thu, 7 Nov 2019 14:40:57 -0500", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> * Tom Lane (tgl@sss.pgh.pa.us) wrote:\n>> Stephen Frost <sfrost@snowman.net> writes:\n>>> Two things- first, this doesn't actually cover everything that the\n>>> proposed GUCs do- specifically, the proposed GUCs give you a way to\n>>> limit what specific extensions are allowed to be installed, and by whom.\n>>> Moving to a GRANT-based system removes the extension specificity and\n>>> leaves with just \"is user X allowed to install extensions\".\n\n>> True. But do we care? We did not have that flexibility before, either.\n\n> I'm not 100% sure that we do, but I wanted to mention it as a\n> difference. Certainly there have previously been suggestions of having\n> a 'whitelist' similar to what you initially proposed, that are\n> extensions which non-superusers are allowed to install.\n\nRight, but I'm not sure that we need multiple layers of that. Flags\nin the extension control files are a clear and understandable mechanism\nfor that. I didn't especially like the idea of a GUC-based whitelist\neven when I proposed it, and Peter's points against it are compelling\ntoo, so I don't really want to go down that path anymore. Do you have\nanother mechanism in mind?\n\n> At a high level, I agree with the idea of an extension being able to be\n> marked as one that's \"trusted\" or not, but we would also need to come up\n> with exactly what that means for it to really have value, and I don't\n> think we've really done that yet.\n\nAgreed, we'd need to have a policy for what we'd mark. The policy that\nI more or less had in mind was to mark a contrib module as trusted if it\ndoes not provide a mechanism for privilege escalation (such as access to\nthe filesystem, in the case of adminpack). Some people might feel that\n\"contrib module X shouldn't be trusted because I'm not convinced it hasn't\ngot bugs\", but I fear if we start trying to make decisions on that basis,\nwe'll be spending a whole lot of time arguing hypotheticals.\n\n>> That doesn't seem like a big objection from here. We could fix it\n>> by making a separate privilege bit, but I doubt that it's worth using\n>> up one of our limited set of spare bits for.\n\n> I do not agree that we should just shift to using default roles instead\n> of adding new options to GRANT because of an entirely internal\n> implementation detail that we could fix (and should, as I've said for\n> probably 10 years now...).\n\nThe default role is not a substitute for the GRANT bit, in my view of\nthis. I think that what we're saying with that, or at least what\nPeter evidently had in mind, is that we want extension installers to\nhave *both* privileges from the superuser and privileges from the\nspecific DB's owner. We can manage the latter with GRANT, but not the\nformer.\n\nIt's certainly arguable that requiring a superuser-granted role is\nenough privilege and we shouldn't bother with having a per-DB\nrestriction capability. I'd be more inclined to go that route than\nto add the overhead of a brand new ACL bit.\n\n> Really? Why do you think that DB ownership shouldn't be enough for\n> this, for trusted extensions?\n\nDB owners have never been particularly highly privileged in the past.\nI think that suddenly saying they can install extensions is moving\nthe understanding of that privilege level quite a bit. Although\nadmittedly, the precedent of trusted PLs would point to allowing them\nto install trusted extensions without further ado. So maybe a\ndifferent take on this is \"allow installing trusted extensions if you\nare DB owner *or* have the pg_install_trusted_extensions role\"?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 07 Nov 2019 14:45:32 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Chapman Flack <chap@anastigmatix.net> writes:\n> So isn't this more a proposal to add another boolean attribute\n> to pg_authid, along the lines of rolcreatedb or rolbypassrls?\n\nI think we've mostly concluded that default roles are superior\nto pg_authid attributes. The latter are legacy things rather\nthan a model to keep extending.\n\n> On the other hand, maybe thinking of it as a privilege bit could\n> lead somewhere interesting. A not-yet-installed extension isn't\n> a real database object, but it does have a synthesized existence\n> as a row in the pg_available_extensions view. Maybe that could\n> have an acl column, where a privilege (why not just CREATE?) could\n> be granted to one or more roles. Synthesizing that could rely on\n> some directive in the control file, or in some separate\n> extension_creators.conf file that would associate extensions with\n> roles.\n\nMeh ... that seems like building a whole new set of infrastructure\nto solve something that we already have a couple of good models\nfor (i.e., default roles and object-based permissions). I really\ndoubt it's worth the trouble to do that.\n\nAlthough upthread I mentioned the possibility of a database admin\nediting extension control files, I think most people would consider\nthat to be a truly last resort; you generally want those files to\nremain as-distributed. The alternative of a new config file is\nslightly less unmaintainable, but only slightly. There'd be no\nway to update it from inside the database, short of writing a lot\nof new infrastructure comparable to ALTER SYSTEM, and surely we\ndon't want to do that.\n\n> Maybe that's just a more ad-hoc and GUCless way of circling back\n> to what the original proposal would be doing with GUCs....\n\nYeah, I think if we really need per-extension configurability\nof this, we're going to end up with a GUC. It's just not worth\nthe trouble to build another mechanism that would support such a\nneed. But I'm currently taking the position that we don't need\nto support that.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 07 Nov 2019 15:00:37 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "I wrote:\n> Stephen Frost <sfrost@snowman.net> writes:\n>> Really? Why do you think that DB ownership shouldn't be enough for\n>> this, for trusted extensions?\n\n> DB owners have never been particularly highly privileged in the past.\n> I think that suddenly saying they can install extensions is moving\n> the understanding of that privilege level quite a bit. Although\n> admittedly, the precedent of trusted PLs would point to allowing them\n> to install trusted extensions without further ado. So maybe a\n> different take on this is \"allow installing trusted extensions if you\n> are DB owner *or* have the pg_install_trusted_extensions role\"?\n\nAfter sleeping on it, I'm liking that idea; it's simple, and it\npreserves the existing behavior that DB owners can install trusted PLs\nwithout any extra permissions. Now, if we follow this up by marking\nmost of contrib as trusted, we'd be expanding that existing privilege.\nBut I think that's all right: I don't recall anybody ever complaining\nthat they wanted to prevent DB owners from installing trusted PLs, and\nI do recall people wishing that it didn't take superuser to install\nthe other stuff.\n\nAccordingly, here's a patchset that does it like that.\n\nI decided after looking at the existing default role names that\n\"pg_install_trusted_extension\" (no plural) was more consistent\nwith the existing names than adding an \"s\". I don't find that\nprecedent particularly charming, but it's what we've got.\n\nI also renamed the extension property from \"trustable\" to \"trusted\".\nThere are at least a couple of reasons to be dissatisfied with that:\n\n(1) There's potential for confusion between the notion of a trusted\nextension and that of a trusted PL; those properties do roughly\nsimilar things, but they're not exactly equivalent. I didn't think\nthis was enough of a problem to justify choosing a different name,\nbut somebody else might think differently.\n\n(2) If we were starting this design from scratch, we'd probably not\nhave two interrelated boolean properties \"superuser\" and \"trusted\",\nbut one three-state enum property. The enum approach would likely\nbe a lot easier to extend if we eventually grow more privilege\nlevels for extension installation. I'm not sure whether it's worth\nbreaking backwards compatibility now to keep our options open for\nthat, though. We could preserve extension control file\ncompatibility easily enough by keeping \"superuser = true\" and\n\"superuser = false\" as allowed legacy spellings for two values of\nan enum property. But the pg_available_extension_versions view is\na tougher nut. On the other hand, maybe replacing its \"superuser\"\ncolumn with something else wouldn't really cause many problems.\n\nOther than getting rid of the GUCs in favor of this design,\nit's mostly the same patchset as before. 0003 and 0004 haven't\nchanged at all, and 0002 only differs by adjusting the test case.\n\n\t\t\tregards, tom lane", "msg_date": "Sat, 09 Nov 2019 15:24:12 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "I wrote:\n> Accordingly, here's a patchset that does it like that.\n\nThe cfbot noticed that a couple of patches committed this week\ncreated (trivial) conflicts with this patchset. Here's a v3\nrebased up to HEAD; no interesting changes.\n\n\t\t\tregards, tom lane", "msg_date": "Fri, 15 Nov 2019 16:22:17 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "I wrote:\n> The cfbot noticed that a couple of patches committed this week\n> created (trivial) conflicts with this patchset. Here's a v3\n> rebased up to HEAD; no interesting changes.\n\nThe 2020 copyright update broke this patchset again. Here's a rebase.\nNo changes except for some minor rearrangement of the CREATE LANGUAGE\nman page in 0003.\n\n\t\t\tregards, tom lane", "msg_date": "Sun, 05 Jan 2020 17:51:37 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Thu, Nov 7, 2019 at 2:13 PM Stephen Frost <sfrost@snowman.net> wrote:\n> I do not agree that we should just shift to using default roles instead\n> of adding new options to GRANT because of an entirely internal\n> implementation detail that we could fix (and should, as I've said for\n> probably 10 years now...).\n\n+1.\n\nI'm not sure that Tom's latest design idea is a bad one, but I\nstrongly suspect that wrapping ourselves around the axle to work\naround our unwillingness to widen a 16-bit quantity to 32 bits (or a\n32 bit quantity to 64 bits) is a bad idea. Perhaps there are also\ndesign ideas that we should consider, like separating \"basic\"\nprivileges and \"extended\" privileges or coming up with some altogether\nnew and better representation. But limiting ourselves to 4 more\nprivileges ever cannot be the right solution.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Mon, 6 Jan 2020 11:29:02 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> On Thu, Nov 7, 2019 at 2:13 PM Stephen Frost <sfrost@snowman.net> wrote:\n>> I do not agree that we should just shift to using default roles instead\n>> of adding new options to GRANT because of an entirely internal\n>> implementation detail that we could fix (and should, as I've said for\n>> probably 10 years now...).\n\n> +1.\n\n> I'm not sure that Tom's latest design idea is a bad one, but I\n> strongly suspect that wrapping ourselves around the axle to work\n> around our unwillingness to widen a 16-bit quantity to 32 bits (or a\n> 32 bit quantity to 64 bits) is a bad idea. Perhaps there are also\n> design ideas that we should consider, like separating \"basic\"\n> privileges and \"extended\" privileges or coming up with some altogether\n> new and better representation. But limiting ourselves to 4 more\n> privileges ever cannot be the right solution.\n\nSo, is that actually an objection to the current proposal, or just\nan unrelated rant?\n\nIf we think that a privilege bit on databases can actually add something\nuseful to this design, the fact that it moves us one bit closer to needing\nto widen AclMode doesn't seem like a serious objection. But I don't\nactually see what such a bit will buy for this purpose. A privilege bit\non a database is presumably something that can be granted or revoked by\nthe database owner, and I do not see that we want any such behavior for\nextension installation privileges.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 06 Jan 2020 13:27:47 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> Robert Haas <robertmhaas@gmail.com> writes:\n> > On Thu, Nov 7, 2019 at 2:13 PM Stephen Frost <sfrost@snowman.net> wrote:\n> >> I do not agree that we should just shift to using default roles instead\n> >> of adding new options to GRANT because of an entirely internal\n> >> implementation detail that we could fix (and should, as I've said for\n> >> probably 10 years now...).\n> \n> > +1.\n> \n> > I'm not sure that Tom's latest design idea is a bad one, but I\n> > strongly suspect that wrapping ourselves around the axle to work\n> > around our unwillingness to widen a 16-bit quantity to 32 bits (or a\n> > 32 bit quantity to 64 bits) is a bad idea. Perhaps there are also\n> > design ideas that we should consider, like separating \"basic\"\n> > privileges and \"extended\" privileges or coming up with some altogether\n> > new and better representation. But limiting ourselves to 4 more\n> > privileges ever cannot be the right solution.\n> \n> So, is that actually an objection to the current proposal, or just\n> an unrelated rant?\n\nIt strikes me as related since using a bit was one of the objections to\nusing the GRANT-a-privilege approach.\n\n> If we think that a privilege bit on databases can actually add something\n> useful to this design, the fact that it moves us one bit closer to needing\n> to widen AclMode doesn't seem like a serious objection. But I don't\n> actually see what such a bit will buy for this purpose. A privilege bit\n> on a database is presumably something that can be granted or revoked by\n> the database owner, and I do not see that we want any such behavior for\n> extension installation privileges.\n\nGiven that extensions are database-level objects, I ask: why not?\nDatabase owners are already able to create schema, and therefore to\ncreate any object inside an extension that doesn't require a superuser\nto create, why not let them also create the framework for those objects\nto exist in, in the form of an extension?\n\nWhen it comes to *trusted* extensions, I would view those in basically\nthe exact same way we view *trusted* languages- that is, if they're\ntrusted, then they can't be used to bypass the privilege system that\nexists in PG, nor can they be used to operate directly on the filesystem\nor open sockets, etc, at least- not without further checks. For\nexample, I would think postgres_fdw could be a 'trusted' extension,\nsince it only allows superusers to create FDWs, and you can't create a\nserver unless you have rights on the FDW.\n\nWhen it comes to *untrusted* extensions, we could limit those to being\nonly installable by superusers, in the same way that functions in\nuntrusted languages are only able to be created by superusers (except,\nperhaps as part of a trusted extension, assuming we can work through\nthis).\n\nNow, I'm no fan of growing the set of things that only a superuser can\ndo, but I don't see that as being what we're doing here because we're\n(hopefully) going to at least make it so that non-superusers can do some\nthings (create trusted extensions) that used to only be possible for\nsuperusers to do, even if it still requires being a superuser to create\nuntrusted extensions. If someone comes up with a really strong use-case\nthen for allowing non-superusers to create untrusted extensions, then we\ncould consider how to enable that and maybe a default role makes sense\nfor that specific case, but I don't think anyone's really made that\ncase and I certainly don't think we want the privilege to create trusted\nextensions and the privilege to create untrusted ones to be the same-\nit's clear made that users will want to grant out those abilities\nindependently.\n\nThanks,\n\nStephen", "msg_date": "Mon, 6 Jan 2020 14:14:41 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Mon, Jan 6, 2020 at 1:27 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> So, is that actually an objection to the current proposal, or just\n> an unrelated rant?\n\nWell, you brought up the topic of remaining bits in the context of the\nproposal, so I guess it's related. And I said pretty clearly that it\nwasn't necessarily an objection.\n\nBut regarding your proposal:\n\n> After sleeping on it, I'm liking that idea; it's simple, and it\n> preserves the existing behavior that DB owners can install trusted PLs\n> without any extra permissions. Now, if we follow this up by marking\n> most of contrib as trusted, we'd be expanding that existing privilege.\n> But I think that's all right: I don't recall anybody ever complaining\n> that they wanted to prevent DB owners from installing trusted PLs, and\n> I do recall people wishing that it didn't take superuser to install\n> the other stuff.\n\nIf somebody were to complain about this, what could they complain\nabout? Potential complaints:\n\n1. I'm the superuser and I don't want my DB owners to be able to\ninstall extensions other than trusted PLs.\n2. Or I want to control which specific ones they can install.\n3. I'm a non-superuser DB owner and I want to delegate permissions to\ninstall trusted extensions to some other user who is not a DB owner.\n\nAll of those sound reasonably legitimate; against that, you can always\nargue that permissions should be more finely grained, and it's not\nalways worth the implementation effort to make it possible. On #1, I\ntend to think that *most* people would be happy rather than sad about\nDB owners being able to install extensions; after all, evil extensions\ncan be restricted by removing them from the disk (or marking them\nuntrusted), and most people who set up a database are hoping it's\ngoing to get used for something. But somebody might not like it,\nespecially if e.g. it turns out that one of our \"trusted\" extensions\nhas a horrible security vulnerability. On #2, I can certainly imagine\nlarge providers having a view about which extensions they think are\nsafe enough for users to install that differs from ours, and if that\nhorrible security vulnerability materializes it sure would be nice to\nbe able to easily disable access to just that one. #3 seems less\nlikely to be an issue, but it's not unthinkable.\n\n\"GRANT INSTALL ON mydb\" seems like it would solve #1 and #3. You could\ngrant a particular DB owner permission to install extensions, or not.\nIf you have them that power WITH GRANT OPTION, then they could\nsub-delegate. It wouldn't do anything about #2; that would require\nsome more complex scheme.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Mon, 6 Jan 2020 15:56:55 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> On Mon, Jan 6, 2020 at 1:27 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> After sleeping on it, I'm liking that idea; it's simple, and it\n>> preserves the existing behavior that DB owners can install trusted PLs\n>> without any extra permissions. Now, if we follow this up by marking\n>> most of contrib as trusted, we'd be expanding that existing privilege.\n>> But I think that's all right: I don't recall anybody ever complaining\n>> that they wanted to prevent DB owners from installing trusted PLs, and\n>> I do recall people wishing that it didn't take superuser to install\n>> the other stuff.\n\n> If somebody were to complain about this, what could they complain\n> about? Potential complaints:\n\n> 1. I'm the superuser and I don't want my DB owners to be able to\n> install extensions other than trusted PLs.\n> 2. Or I want to control which specific ones they can install.\n> 3. I'm a non-superuser DB owner and I want to delegate permissions to\n> install trusted extensions to some other user who is not a DB owner.\n\nSure, but all of these seem to be desires for features that could be\nadded later. As for #1, we could have that just by not taking the\nnext step of marking anything but the PLs trusted (something that is\ngoing to happen anyway for v13, if this patch doesn't move faster).\n#2 is not a feature that exists now, either; actually, the patch *adds*\nit, to the extent that the superuser is willing to adjust extension\ncontrol files. Likewise, #3 is not a feature that exists now. Also,\nthe patch adds something that looks partly like #3, in that the\nsuperuser could grant pg_install_trusted_extension with admin option\nto database users who should be allowed to delegate it. Perhaps that's\ninadequate, but I don't see why we can't wait for complaints before\ntrying to design something that satisfies hypothetical use cases.\n\nThe facts that I'm worried about are that this is already the January\n'fest, and if we don't want to ship v13 with python 2 as still the\npreferred python, we need to not only get this patch committed but do\nsome less-than-trivial additional work (that hasn't even been started).\nSo I'm getting very resistant to requests for more features in this patch.\nI think everything you're suggesting above could be tackled later,\nwhen and if there's actual field demand for it.\n\n> \"GRANT INSTALL ON mydb\" seems like it would solve #1 and #3.\n\nIt's not apparent to me that that's better, and it seems possible that\nit's worse. The fact that a DB owner could grant that privilege to\nhimself means that you might as well just have it on all the time.\nLike a table owner's DML rights, it would only be useful to prevent\naccidentally shooting yourself in the foot ... but who accidentally\nissues CREATE EXTENSION? And if they do (for an extension that\ndeserves to be marked trusted) what harm is done really? Worst\ncase is you drop it again.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 06 Jan 2020 17:38:38 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> Robert Haas <robertmhaas@gmail.com> writes:\n> > On Mon, Jan 6, 2020 at 1:27 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> After sleeping on it, I'm liking that idea; it's simple, and it\n> >> preserves the existing behavior that DB owners can install trusted PLs\n> >> without any extra permissions. Now, if we follow this up by marking\n> >> most of contrib as trusted, we'd be expanding that existing privilege.\n> >> But I think that's all right: I don't recall anybody ever complaining\n> >> that they wanted to prevent DB owners from installing trusted PLs, and\n> >> I do recall people wishing that it didn't take superuser to install\n> >> the other stuff.\n> \n> > If somebody were to complain about this, what could they complain\n> > about? Potential complaints:\n> \n> > 1. I'm the superuser and I don't want my DB owners to be able to\n> > install extensions other than trusted PLs.\n\nI don't agree that this is actually a sensible use-case, so I'm not\nreally sure why we're discussing solutions to make it work. It happens\nto be how things work because pg_pltemplate exists before we had\nextensions and we never went back and cleaned that up- but that's\nexactly what we're trying to do here, and adding in a nice feature at\nthe same time.\n\n> > 2. Or I want to control which specific ones they can install.\n\nThis is exactly what the 'trusted' bit is for, isn't it? If you think\nthat we need something that's actually a permission matrix between roles\nand specific extensions, that's a whole different level, certainly, and\nI don't think anyone's asked for or contemplated such a need.\n\nI do like the idea of having a way to install more-or-less all\nextensions out on to the filesystem and then giving superusers an\nability to decide which ones are 'trusted' and which ones are not,\nwithout having to hand-hack the control files. I don't particularly\nlike using GUCs for that but I'm not sure what a better option looks\nlike and I'm not completely convinced we really need this. If we really\ngo down this route (without resorting to GUCs or something) then we'd \nneed an additional catalog table that $someone is allowed to populate\nthrough some kind of SQL and a whole lot of extra work and I definitely\ndon't think we need that right now.\n\n> > 3. I'm a non-superuser DB owner and I want to delegate permissions to\n> > install trusted extensions to some other user who is not a DB owner.\n\nThis is a use-case that I do think exists (or, at least, I'm a superuser\nor a DB owner and I'd like to delegate that privilege to another user).\n\n> Sure, but all of these seem to be desires for features that could be\n> added later. \n\nWe can't very well add a default role in one release and then decide we\nwant to use the GRANT-privilege system in the next and remove it...\n\n> As for #1, we could have that just by not taking the\n> next step of marking anything but the PLs trusted (something that is\n> going to happen anyway for v13, if this patch doesn't move faster).\n\nUgh. I find that to be a pretty horrible result. Yes, we could mark\nextensions later as 'trusted' but that'd be another year..\n\n> #2 is not a feature that exists now, either; actually, the patch *adds*\n> it, to the extent that the superuser is willing to adjust extension\n> control files. Likewise, #3 is not a feature that exists now. Also,\n> the patch adds something that looks partly like #3, in that the\n> superuser could grant pg_install_trusted_extension with admin option\n> to database users who should be allowed to delegate it. Perhaps that's\n> inadequate, but I don't see why we can't wait for complaints before\n> trying to design something that satisfies hypothetical use cases.\n\n#3 from Robert's list certainly strikes me as a valid use-case and not\njust hypothetical.\n\n> The facts that I'm worried about are that this is already the January\n> 'fest, and if we don't want to ship v13 with python 2 as still the\n> preferred python, we need to not only get this patch committed but do\n> some less-than-trivial additional work (that hasn't even been started).\n> So I'm getting very resistant to requests for more features in this patch.\n> I think everything you're suggesting above could be tackled later,\n> when and if there's actual field demand for it.\n\nPerhaps I'm wrong, but I wouldn't think changing this from a\ndefault-role based approach over to a GRANT'able right using our\nexisting GRANT system would be a lot of work. I agree that addressing\nsome of the use-cases proposed above could be a great deal of work but,\nas I say above, I don't agree that we need to address all of them.\n\n> > \"GRANT INSTALL ON mydb\" seems like it would solve #1 and #3.\n> \n> It's not apparent to me that that's better, and it seems possible that\n> it's worse. The fact that a DB owner could grant that privilege to\n> himself means that you might as well just have it on all the time.\n\nI agree that the DB owner should have that right by default, just like\nthey have any of the other DB-level rights that exist, just like how the\nGRANT system in general works today. If they remove it from themselves,\nthen that's on them and they won't be able to create extensions until\nthey GRANT it back to themselves.\n\nI do *not* agree that this means we shouldn't have DB-level rights for\ndatabase owners and that we should just go hand-hack the system to have\nexplicit \"is this the DB owner?\" checks. The suggestion you're making\nhere seems to imply we should go hack up the CREATE SCHEMA check to have\nit see if the user is the DB owner and then allow it, instead of doing\nour normal privilege checks, and I don't think that makes any sense. I\ndefinitely don't like the idea of having this privilege act in any more\nspecial way than our other privileges (be it a default-role or a GRANT'd\nprivilege, though obviously I'm much happier with the latter than the\nformer for this case).\n\n> Like a table owner's DML rights, it would only be useful to prevent\n> accidentally shooting yourself in the foot ... but who accidentally\n> issues CREATE EXTENSION? And if they do (for an extension that\n> deserves to be marked trusted) what harm is done really? Worst\n> case is you drop it again.\n\nWhy are we talking about adding code for this though? The GRANT system\nalready handles all of this just fine and we rarely hear complaints from\npeople about it.\n\nThanks,\n\nStephen", "msg_date": "Mon, 6 Jan 2020 18:07:18 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> Perhaps I'm wrong, but I wouldn't think changing this from a\n> default-role based approach over to a GRANT'able right using our\n> existing GRANT system would be a lot of work.\n\nNobody has proposed a GRANT-based API that seems even close to\nacceptable from where I sit. A new privilege bit on databases\nis not it, at least not unless it works completely unlike\nany other privilege bit. It's giving control to the DB owners,\nnot the superuser, and that seems like quite the wrong thing\nfor this purpose.\n\nOr to put it another way: I think that the grantable role, which\nultimately is handed out by the superuser, is the primary permissions\nAPI in this design. The fact that DB owners effectively have that\nsame privilege is a wart for backwards-compatibility. If we were\ndoing this from scratch, that wart wouldn't be there. What you're\nproposing is to make the wart the primary (indeed sole) permissions\ncontrol mechanism for extension installation, and that just seems\ncompletely wrong. Superusers would have effectively *no* say in\nwho gets to install trusted extensions, which is turning the whole\nthing on its head I think; it's certainly not responding to either\nof Robert's first two points.\n\nIf we were willing to break backwards compatibility, what I'd prefer\nis to just have the grantable role, and to say that you have to grant\nthat to DB owners if you want them to be able to install PLs. I'm\nnot sure how loud the howls would be if we did that, but it'd be a\nlot cleaner than any of these other ideas.\n\n> I do *not* agree that this means we shouldn't have DB-level rights for\n> database owners and that we should just go hand-hack the system to have\n> explicit \"is this the DB owner?\" checks. The suggestion you're making\n> here seems to imply we should go hack up the CREATE SCHEMA check to have\n> it see if the user is the DB owner and then allow it, instead of doing\n> our normal privilege checks, and I don't think that makes any sense.\n\nUh, what? Nothing in what I'm proposing goes anywhere near the\npermissions needed for CREATE SCHEMA.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 06 Jan 2020 18:26:45 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> Stephen Frost <sfrost@snowman.net> writes:\n> > Perhaps I'm wrong, but I wouldn't think changing this from a\n> > default-role based approach over to a GRANT'able right using our\n> > existing GRANT system would be a lot of work.\n> \n> Nobody has proposed a GRANT-based API that seems even close to\n> acceptable from where I sit. A new privilege bit on databases\n> is not it, at least not unless it works completely unlike\n> any other privilege bit. It's giving control to the DB owners,\n> not the superuser, and that seems like quite the wrong thing\n> for this purpose.\n\nI'm seriously confused by this. Maybe we need to step back for a moment\nbecause there are things that already exist today that I don't think\nwe're really contemplating.\n\nThe first is this- ANYONE can create an extension in the system today,\nif it's marked as superuser=false. If anything, it seems like that's\nprobably too loose- certainly based on your contention that ONLY\nsuperusers should wield such a power and that letting anyone else do so\nis a right that a superuser must explicitly grant.\n\n> Or to put it another way: I think that the grantable role, which\n> ultimately is handed out by the superuser, is the primary permissions\n> API in this design. The fact that DB owners effectively have that\n> same privilege is a wart for backwards-compatibility. If we were\n> doing this from scratch, that wart wouldn't be there. What you're\n> proposing is to make the wart the primary (indeed sole) permissions\n> control mechanism for extension installation, and that just seems\n> completely wrong. Superusers would have effectively *no* say in\n> who gets to install trusted extensions, which is turning the whole\n> thing on its head I think; it's certainly not responding to either\n> of Robert's first two points.\n\nSuperusers don't have any (direct) say in who gets to create schemas\neither, yet we don't seem to have a lot of people complaining about it.\nIn fact, superusers don't have any say in who gets to create functions,\nor operators, or tables, or indexes, or EXTENSIONS, either. The fact is\nthat DB owners can *already* create most objects, including extensions,\nin the DB system without the superuser being able to say anything about\nit.\n\nI really don't understand this hold-up when it comes to (trusted)\nextensions. Consider that, today, in many ways, PLs *are* the 'trusted'\nextensions that DB owners are already allowed to install. They're\nlibraries of C functions that are trusted to do things right and\ntherefore they can be allowed to be installed by DB owners.\n\nIf we had a generic way to have a C library declare that it only exposes\n'trusted' C functions, would we deny users the ability to create those\nfunctions in the database, when they can create functions in a variety\nof other trusted languages? Why would the fact that they're C\nfunctions, in that case, make them somehow special? That is, in fact,\n*exactly* what's already going on with pltemplate and trusted languages.\n\nHaving trusted extensions is giving us exactly what pltemplate does, but\nin a generic way where any C library (or whatever else) can be declared\nas trusted, as defined by the extension framework around it, and\ntherefore able to be installed by DB owners. Considering we haven't got\nany kind of check in the system today around extension creation, itself,\nthis hardly seems like a large step to me- one could even argue that\nmaybe we should just let ANYONE create them, but I'm not asking for\nthat (in fact, I could probably be argued into agreeing to remove the\nability for $anyone to create non-superuser extensions today, if we\nadded this privilege...).\n\n> If we were willing to break backwards compatibility, what I'd prefer\n> is to just have the grantable role, and to say that you have to grant\n> that to DB owners if you want them to be able to install PLs. I'm\n> not sure how loud the howls would be if we did that, but it'd be a\n> lot cleaner than any of these other ideas.\n\nIf we can't come to agreement regarding using a regular GRANT'able\nright, then I'd much rather break backwards compatibility than have such\na hacked up wart like this special case you're talking about for PLs.\n\n> > I do *not* agree that this means we shouldn't have DB-level rights for\n> > database owners and that we should just go hand-hack the system to have\n> > explicit \"is this the DB owner?\" checks. The suggestion you're making\n> > here seems to imply we should go hack up the CREATE SCHEMA check to have\n> > it see if the user is the DB owner and then allow it, instead of doing\n> > our normal privilege checks, and I don't think that makes any sense.\n> \n> Uh, what? Nothing in what I'm proposing goes anywhere near the\n> permissions needed for CREATE SCHEMA.\n\nI understand that- you're talking about just having this 'wart' for\nCREATE EXTENSION and I don't agree with having the 'wart' at all. To\nstart doing this for PLs would be completely inconsistent with the way\nthe rest of the privilege system works and that's not ok.\n\nThanks,\n\nStephen", "msg_date": "Mon, 6 Jan 2020 18:56:23 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Mon, Jan 6, 2020 at 6:56 PM Stephen Frost <sfrost@snowman.net> wrote:\n> The first is this- ANYONE can create an extension in the system today,\n> if it's marked as superuser=false. If anything, it seems like that's\n> probably too loose- certainly based on your contention that ONLY\n> superusers should wield such a power and that letting anyone else do so\n> is a right that a superuser must explicitly grant.\n\nI don't think this argument makes any sense. Sure, anyone can create\nan extension with superuser=false, but so what? From a security point\nof view, when you create such an extension, you are using your own\nprivileges to do things that you could do anyway. The interesting case\nis creating an extension that requires superuser privileges, probably\nbecause it's going to call C functions. The superuser can and must\nhave the last word regarding who is allowed to do such things, because\nthe superuser is equivalent to the OS user and any other user of the\nsystem is not. The \"tenants\" of the database system can't be allowed\nto use it for things which the \"owner\" does not wish to permit.\n\nOn Mon, Jan 6, 2020 at 6:26 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> If we were willing to break backwards compatibility, what I'd prefer\n> is to just have the grantable role, and to say that you have to grant\n> that to DB owners if you want them to be able to install PLs. I'm\n> not sure how loud the howls would be if we did that, but it'd be a\n> lot cleaner than any of these other ideas.\n\nThat seems like a fine idea. Then the superuser has ultimate control,\nand can decide which database owners they want to trust, and whether\nthey'd like the database owners to be able to subdelegate those\npermissions. The only thing it doesn't do is give any control over\nexactly which extensions can be installed by non-superusers, which\nwould be a really nice thing to have, especially if we're going to\nsignificant expand the list of trusted extensions (something that I\nthink is, overall, quite a good idea). I accept Tom's argument that he\nisn't obliged to add every related feature somebody might want just\nbecause he's doing some work in this area, but not his contention that\nthe demand for such a feature is entirely hypothetical and the\nsuggestion that perhaps nobody will care anyway. I expect the reaction\nto be along the lines of \"hey, it's great that we can let DB owners do\nthis now, but it's really too bad that I can't blacklist\n$SCARY_EXTENSION\". I don't think that we'll be better off if this\nentire proposal gets voted down for lack of that capability, but I\nthink it would be a really good thing to add.\n\nFWIW, I don't really buy the argument that you can adjust the\nextension control files to get out from under this problem.\nTechnically, that is true. But in practice, the extension control\nfiles are provided by your packager, and you don't want to modify them\nbecause then your packaging system will get grumpy with you. While\nit's reasonable for the packaging to provide a tentative answer to the\nquestion of what should be trusted, trust is ultimately a matter of\nlocal policy, and that policy should be configured someplace that's\nnot managed by RPM.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 7 Jan 2020 12:08:45 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Robert Haas (robertmhaas@gmail.com) wrote:\n> On Mon, Jan 6, 2020 at 6:56 PM Stephen Frost <sfrost@snowman.net> wrote:\n> > The first is this- ANYONE can create an extension in the system today,\n> > if it's marked as superuser=false. If anything, it seems like that's\n> > probably too loose- certainly based on your contention that ONLY\n> > superusers should wield such a power and that letting anyone else do so\n> > is a right that a superuser must explicitly grant.\n> \n> I don't think this argument makes any sense. Sure, anyone can create\n> an extension with superuser=false, but so what? From a security point\n> of view, when you create such an extension, you are using your own\n> privileges to do things that you could do anyway. The interesting case\n> is creating an extension that requires superuser privileges, probably\n> because it's going to call C functions. The superuser can and must\n> have the last word regarding who is allowed to do such things, because\n> the superuser is equivalent to the OS user and any other user of the\n> system is not. The \"tenants\" of the database system can't be allowed\n> to use it for things which the \"owner\" does not wish to permit.\n\nWhat's the security issue from installing a trusted extension?\n\n> On Mon, Jan 6, 2020 at 6:26 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > If we were willing to break backwards compatibility, what I'd prefer\n> > is to just have the grantable role, and to say that you have to grant\n> > that to DB owners if you want them to be able to install PLs. I'm\n> > not sure how loud the howls would be if we did that, but it'd be a\n> > lot cleaner than any of these other ideas.\n> \n> That seems like a fine idea. Then the superuser has ultimate control,\n> and can decide which database owners they want to trust, and whether\n> they'd like the database owners to be able to subdelegate those\n> permissions. The only thing it doesn't do is give any control over\n> exactly which extensions can be installed by non-superusers, which\n> would be a really nice thing to have, especially if we're going to\n> significant expand the list of trusted extensions (something that I\n> think is, overall, quite a good idea). I accept Tom's argument that he\n> isn't obliged to add every related feature somebody might want just\n> because he's doing some work in this area, but not his contention that\n> the demand for such a feature is entirely hypothetical and the\n> suggestion that perhaps nobody will care anyway. I expect the reaction\n> to be along the lines of \"hey, it's great that we can let DB owners do\n> this now, but it's really too bad that I can't blacklist\n> $SCARY_EXTENSION\". I don't think that we'll be better off if this\n> entire proposal gets voted down for lack of that capability, but I\n> think it would be a really good thing to add.\n\nWhy would it be trusted if it's $SCARY_EXTENSION ...? Why are we trying\nto punt on solving for that question by installing a much more\ncomplicated system here than is really necessary, just to avoid having\nto make that decision?\n\nIf the extension is trusted, then there isn't a security issue with it,\nand it isn't scary, by definition, imv, which negates these arguments\nabout making the right to install it have to be hand delegated by a\nsuperuser and needing a system for managing who is allowed to install\nwhat extension.\n\nIf these functions were to just be put into core (as many really should\nbe...), instead of being out in contrib, this whole issue also wouldn't\nexist and everyone would be able to use the functions (at least, those\nthat we decide are safe for users to directly use- and with appropriate\nprivilege access over ones that aren't), without any \"the superuser must\napprove of this explicitly after installation\" fuss.\n\n> FWIW, I don't really buy the argument that you can adjust the\n> extension control files to get out from under this problem.\n> Technically, that is true. But in practice, the extension control\n> files are provided by your packager, and you don't want to modify them\n> because then your packaging system will get grumpy with you. While\n> it's reasonable for the packaging to provide a tentative answer to the\n> question of what should be trusted, trust is ultimately a matter of\n> local policy, and that policy should be configured someplace that's\n> not managed by RPM.\n\nThis I tend to agree with- hacking around with control files or other\nfiles installed with extensions from RPMs isn't a great plan.\n\nA possible alternative would be to have a *new* configuration file (not\npart of the GUC system) which admins could hack up to specify who should\nbe allowed to install what extension. Or we make that a catalog table\ninstead because, well, such things should probably be in the database\nwhere we can have dependency management and validity checking...\n\nOn the other hand, having individual packages for different extensions\nis a pretty handy way of letting an administrator decide if they want\nthat extension to be installed on their system or not. That's a pain\nfor contrib because, really, all of those should really just be in core,\nor not included if we aren't confident that they're safe to use.\n\nThanks,\n\nStephen", "msg_date": "Tue, 7 Jan 2020 13:17:27 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Tue, Jan 7, 2020 at 1:17 PM Stephen Frost <sfrost@snowman.net> wrote:\n> Why would it be trusted if it's $SCARY_EXTENSION ...? Why are we trying\n> to punt on solving for that question by installing a much more\n> complicated system here than is really necessary, just to avoid having\n> to make that decision?\n\nI'm not convinced that whether or not something is trusted is an\naltogether objective question. For instance, postgres_fdw probably\ndoesn't let you become the superuser, unless it has bugs. But it does\nlet you make network connections originating from the database host,\nand somebody might reasonably want to restrict that in a\nsecurity-sensitive environment. But the same user might be totally OK\nwith a particular database owner installing citext.\n\n> If these functions were to just be put into core (as many really should\n> be...), instead of being out in contrib, this whole issue also wouldn't\n> exist and everyone would be able to use the functions (at least, those\n> that we decide are safe for users to directly use- and with appropriate\n> privilege access over ones that aren't), without any \"the superuser must\n> approve of this explicitly after installation\" fuss.\n\nWell, I don't agree with the idea of moving everything into core, but\nI think a good solution to the problem at hand will reduce the fuss\nwhile allowing superusers to retain some control.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 7 Jan 2020 13:55:50 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings!\n\n* Robert Haas (robertmhaas@gmail.com) wrote:\n> On Tue, Jan 7, 2020 at 1:17 PM Stephen Frost <sfrost@snowman.net> wrote:\n> > Why would it be trusted if it's $SCARY_EXTENSION ...? Why are we trying\n> > to punt on solving for that question by installing a much more\n> > complicated system here than is really necessary, just to avoid having\n> > to make that decision?\n> \n> I'm not convinced that whether or not something is trusted is an\n> altogether objective question. \n\nHow have we managed to have an answer to that question for all of the\nlanguages that work with PG then..? I feel like the answer is actually\npretty clear, at least if we view it in that light, and in the specific\ncase below, we are in agreement on which way it goes.\n\n> For instance, postgres_fdw probably\n> doesn't let you become the superuser, unless it has bugs. But it does\n> let you make network connections originating from the database host,\n> and somebody might reasonably want to restrict that in a\n> security-sensitive environment. But the same user might be totally OK\n> with a particular database owner installing citext.\n\nAgreement! Progress! At least as it relates to, specifically,\npostgres_fdw and about how non-superusers should have to be granted\nsomething special to be allowed to make network connections.\n\nHere's the thing though.. creating the extension isn't *really* (in our\npermissions model anyway) what lets you create outbound connections-\nit's creating a 'SERVER', and to be able to do that you need to have\nUSAGE rights on the FDW, which, normally, only a superuser can create.\nThe crux here is that the FDW is created as part of the extension\nthough. As long as only superusers can create extensions, that's fine,\nbut when we allow others to do so, we come to an interesting question:\n\nNo matter how we end up allowing a non-superuser to create a trusted\nextension, who should end up owning it and being able to modify it\nand/or grant access to objects within it?\n\nWe don't currently have anything that prevents objects from an\nextension from being modified by their owner, for example, and that\nseems like a problem from where I'm sitting when you're talking about\nhaving non-superusers creating objects that previously only superusers\ncould, and where the ownership-level rights on those objects would allow\nthat user to do things we generally don't feel an 'untrusted' user\nshould be able to.\n\nWhich basically leads to- in my mental model of this, the 'create\ntrusted extension' action would be kind of like a 'sudo apt install',\nwhere the result is an extension that's installed as if a superuser did\ninstall it and therefore it's owned by a superuser and the DB owner\ncan't go monkey around with any of the functions or tables or such\n(unless allowed by the extension), beyond granting access (or not) to\nthe schema that the extension is installed into (which is actually more\nthan the 'sudo apt install' example above would probably let you do).\nFurther, that installation doesn't give the DB owner any more rights to\ndo things on the system than they already had.\n\nOf course, there's the other option, which is to just agree that,\nbecause of the way postgres_fdw works, it's gotta be marked as\nuntrusted. I would ask though- are we really sure that we aren't ever\ngoing to have any issues with functions in untrusted languages (or any\nother objects) created by extensions being owned by non-superusers?\n\n> > If these functions were to just be put into core (as many really should\n> > be...), instead of being out in contrib, this whole issue also wouldn't\n> > exist and everyone would be able to use the functions (at least, those\n> > that we decide are safe for users to directly use- and with appropriate\n> > privilege access over ones that aren't), without any \"the superuser must\n> > approve of this explicitly after installation\" fuss.\n> \n> Well, I don't agree with the idea of moving everything into core, but\n> I think a good solution to the problem at hand will reduce the fuss\n> while allowing superusers to retain some control.\n\nI don't actually mean everything, just to be clear, but a whole lot of\nwhat's in contrib really could be in core with only a relatively modest\nincrease in the size of our base install/catalog (and, yes, I know some\npeople would complain about that, but in that case I'd argue that maybe\nwe should arrange to let them optionally not include those during the\nbuild or something else because they're probably taking other steps to\nminimize the size of PG on disk if they care that much..).\n\nHaving something like postgres_fdw installed as part of core would also\naddress the complications we have above regarding who owns it and who\ngets to grant out access to it.\n\nThanks,\n\nStephen", "msg_date": "Tue, 7 Jan 2020 16:36:18 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Tue, Jan 7, 2020 at 4:36 PM Stephen Frost <sfrost@snowman.net> wrote:\n> Here's the thing though.. creating the extension isn't *really* (in our\n> permissions model anyway) what lets you create outbound connections-\n> it's creating a 'SERVER', and to be able to do that you need to have\n> USAGE rights on the FDW, which, normally, only a superuser can create.\n> The crux here is that the FDW is created as part of the extension\n> though. As long as only superusers can create extensions, that's fine,\n> but when we allow others to do so, we come to an interesting question:\n>\n> No matter how we end up allowing a non-superuser to create a trusted\n> extension, who should end up owning it and being able to modify it\n> and/or grant access to objects within it?\n\nHmm. Good question. But it's addressed in the documentation for the\npatch Tom wrote, so I don't know why we need to discuss it de novo.\nHis answer seems pretty sensible and also happens to, I think, match\nwhat you've written here.\n\n> Of course, there's the other option, which is to just agree that,\n> because of the way postgres_fdw works, it's gotta be marked as\n> untrusted. I would ask though- are we really sure that we aren't ever\n> going to have any issues with functions in untrusted languages (or any\n> other objects) created by extensions being owned by non-superusers?\n\nBut I don't see what the question of \"who owns the objects?\" has to do\nwith whether a superuser might want to allow some extensions to be\ninstalled but not others. I think someone might want that, and if I\nunderstand correctly, Tom thought so too when he wrote v1 of the\npatch, because it had some capabilities along these lines. All I'm\ndoing is arguing that his first instinct was correct. And I'm not even\nsure that you're disagreeing, since you seem to think that the\nquestion of whether postgres_fdw ought to be marked trusted is\ndebatable. I'm really not sure what we're arguing about here.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 7 Jan 2020 18:49:01 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Robert Haas (robertmhaas@gmail.com) wrote:\n> On Tue, Jan 7, 2020 at 4:36 PM Stephen Frost <sfrost@snowman.net> wrote:\n> > Here's the thing though.. creating the extension isn't *really* (in our\n> > permissions model anyway) what lets you create outbound connections-\n> > it's creating a 'SERVER', and to be able to do that you need to have\n> > USAGE rights on the FDW, which, normally, only a superuser can create.\n> > The crux here is that the FDW is created as part of the extension\n> > though. As long as only superusers can create extensions, that's fine,\n> > but when we allow others to do so, we come to an interesting question:\n> >\n> > No matter how we end up allowing a non-superuser to create a trusted\n> > extension, who should end up owning it and being able to modify it\n> > and/or grant access to objects within it?\n> \n> Hmm. Good question. But it's addressed in the documentation for the\n> patch Tom wrote, so I don't know why we need to discuss it de novo.\n> His answer seems pretty sensible and also happens to, I think, match\n> what you've written here.\n\nI would disagree about it matching what I wrote, but only because it\ngoes farther and lets the extension choose, which is even better.\nThanks for pointing that out, I had missed how that was addressed.\n\n> > Of course, there's the other option, which is to just agree that,\n> > because of the way postgres_fdw works, it's gotta be marked as\n> > untrusted. I would ask though- are we really sure that we aren't ever\n> > going to have any issues with functions in untrusted languages (or any\n> > other objects) created by extensions being owned by non-superusers?\n> \n> But I don't see what the question of \"who owns the objects?\" has to do\n> with whether a superuser might want to allow some extensions to be\n> installed but not others. I think someone might want that, and if I\n> understand correctly, Tom thought so too when he wrote v1 of the\n> patch, because it had some capabilities along these lines. All I'm\n> doing is arguing that his first instinct was correct. And I'm not even\n> sure that you're disagreeing, since you seem to think that the\n> question of whether postgres_fdw ought to be marked trusted is\n> debatable. I'm really not sure what we're arguing about here.\n\nHere's the thing though- I *am* disagreeing, and that Tom had addressed\nthe ownership issue solidifies my feeling that the justification that's\nbeen proposed for why a superuser might want to allow some extensions to\nbe installed but not others (beyond the \"trustable\" question that we are\nproposing to address) isn't valid.\n\nYou raised the point regarding postgres_fdw and a DB owner being able to\nrun 'create extension postgres_fdw;' and to then make network\nconnections, but that's proven to be invalid because, assuming we make\npostgres_fdw trustable, we will surely make the FDW itself that's\ncreated be owned by the bootstrap superuser and therefore the DB owner\n*couldn't* create such network connections- at least, now without an\nadditional step being taken by a superuser. Further, it's pretty clear\nto everyone *why* that additional step has to be taken for postgres_fdw.\n\nSo I come back to the questions that were raised up-thread but either\nweren't answered or were done so with invalid points, as explained above\nregarding postgres_fdw:\n\nWhat's the security issue from installing a trusted extension?\n\nWhy would a $SCARY_EXTENSION be marked as trusted?\n\nIf there's no security issue, and no $SCARY_EXTENSION that's marked as\ntrusted, then why wouldn't a superuser be comfortable allowing a DB\nowner to install a trusted extension into the DB they own? The DB where\nthey can create any other trusted object from functions in trusted\nlanguages to operators to schemas to tables and indexes and views and\nall the others? What is the superuser concerned about? What do they\nneed to check before allowing this? What's dangerous about allowing it?\n\nMaybe it would help to say that I'm seeing the pattern here being\nsomething along the lines of:\n\n0) DBA owns prod database, but is not a superuser.\n1) DBA decides they want $trusted_extension but it isn't installed\n2) DBA submits a ticket to the infra team and says \"please install this\n RPM on to this database server\"\n3) infra reviews that request and decides if they're ok with the RPM\n4) infra resolves the ticket and installs the RPM,\n5) DBA then runs 'create extension $trusted_extension;' and go about\n doing whatever it is they want to do with that extension.\n\nThe approach you're advocating for, assuming I've understood it\ncorrectly, requires the infra team to also log in to the database as the\npostgres superuser and then grant this role to the DBA, and I just don't\nsee the justification for that additional step, and I'm sure they're\ngoing to be asking themselves \"why do I need to do this..? what power\nis this granting? why is this dangerous? What about this isn't to be\ntrusted?\"\n\nTo the question of \"how do we know if the extension is trusted?\" I\nanswer- how do we know a PL is trusted? We have to evaluate it,\nconsider what it allows the user to do, see if it has appropriate checks\nto make sure the user can't circumvent our privilege system and can't\nbreak out of the 'box', as it were, and then decide on if it's trusted\nor not. Sure, if we mark it as trusted then we have to deal with fixing\nany bugs that come up with it, including security issues, but that's\njust the same as we do with the core code (and, for the most part, what\nwe do with the core extensions also anyway... I can't think of a single\ncase off-hand where we have said \"well, you have to actually install\nthat extension, so we aren't going to address this security issue that\nyou found in it\"), so I don't see it as being that difficult for us to\nalso do that for extensions.\n\nThanks,\n\nStephen", "msg_date": "Tue, 7 Jan 2020 19:32:47 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Tue, Jan 7, 2020 at 7:32 PM Stephen Frost <sfrost@snowman.net> wrote:\n> You raised the point regarding postgres_fdw and a DB owner being able to\n> run 'create extension postgres_fdw;' and to then make network\n> connections, but that's proven to be invalid because, assuming we make\n> postgres_fdw trustable, we will surely make the FDW itself that's\n> created be owned by the bootstrap superuser and therefore the DB owner\n> *couldn't* create such network connections- at least, now without an\n> additional step being taken by a superuser. Further, it's pretty clear\n> to everyone *why* that additional step has to be taken for postgres_fdw.\n\nTo me, this seems more accidental than the natural fallout of good design.\n\n> Why would a $SCARY_EXTENSION be marked as trusted?\n\nWell, again, my point in using postgres_fdw as an example was not that\nit should be untrusted, or that it should be trusted, but that\ndifferent people might have different views about that question, and\ntherefore configurability would be good. I believe the same thing\napplies in other cases. For me, this boils down to the view that the\nsuperuser can have arbitrary preferences about what C code they want\nto let users run, and they need not justify such views with reference\nto anything in particular. Some superuser can decide that they think\nhstore is great stuff but bloom is too experimental and isn is a pile\nof crap, and that all seems perfectly legitimate to me. And some other\nsuperuser can have a different view and that seems fine, too. I can't\nthink of any reason why a particular installation should have to\ndecide between certifying most of contrib and certifying none of it,\nwith no intermediate options. I guess you see it differently.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Wed, 8 Jan 2020 17:49:06 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Robert Haas (robertmhaas@gmail.com) wrote:\n> On Tue, Jan 7, 2020 at 7:32 PM Stephen Frost <sfrost@snowman.net> wrote:\n> > You raised the point regarding postgres_fdw and a DB owner being able to\n> > run 'create extension postgres_fdw;' and to then make network\n> > connections, but that's proven to be invalid because, assuming we make\n> > postgres_fdw trustable, we will surely make the FDW itself that's\n> > created be owned by the bootstrap superuser and therefore the DB owner\n> > *couldn't* create such network connections- at least, now without an\n> > additional step being taken by a superuser. Further, it's pretty clear\n> > to everyone *why* that additional step has to be taken for postgres_fdw.\n\n(guessing it was clear, but sorry for the typo above, 'now' should have\nbeen 'not')\n\n> To me, this seems more accidental than the natural fallout of good design.\n\nI disagree that the privilege design for FDWs was accidental. Perhaps\nit was a mistake to automatically run the CREATE FDW as part of the\nextension script, but that doesn't really change any of the argument I'm\nmaking.\n\n> > Why would a $SCARY_EXTENSION be marked as trusted?\n> \n> Well, again, my point in using postgres_fdw as an example was not that\n> it should be untrusted, or that it should be trusted, but that\n> different people might have different views about that question, and\n> therefore configurability would be good. I believe the same thing\n> applies in other cases. For me, this boils down to the view that the\n> superuser can have arbitrary preferences about what C code they want\n> to let users run, and they need not justify such views with reference\n> to anything in particular. Some superuser can decide that they think\n> hstore is great stuff but bloom is too experimental and isn is a pile\n> of crap, and that all seems perfectly legitimate to me. And some other\n> superuser can have a different view and that seems fine, too. I can't\n> think of any reason why a particular installation should have to\n> decide between certifying most of contrib and certifying none of it,\n> with no intermediate options. I guess you see it differently.\n\nWhat I see differently is that the purview of those decisions should be\nthat of the DB owner and not the superuser. If the superuser really\nwants to own those decisions, then they should be the DB owner too, and\nthen they can also control what schemas exist and who can use them, or\nthey can GRANT that right out only to whomever they trust with it, and\nlikewise could GRANT out this install-extension right out to whomever\nthey deem worthy.\n\nAs it relates to things in contrib that could be classified as 'a pile\nof crap' or 'too experimental'- that's *our* failing, and one which we\nshould accept and address instead of punting on it. In my recollection,\nthis is far from the first time someone's suggested that maybe we should\ntry to clean up contrib. I don't accept that our reluctance to punt\nthings out of contrib that shouldn't be there is an acceptable argument\nagainst using our existing GRANT system for this new right or sufficient\njustification to use a default role instead.\n\nThanks,\n\nStephen", "msg_date": "Wed, 8 Jan 2020 18:09:35 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Wed, Jan 8, 2020 at 6:09 PM Stephen Frost <sfrost@snowman.net> wrote:\n> > To me, this seems more accidental than the natural fallout of good design.\n>\n> I disagree that the privilege design for FDWs was accidental.\n\nThat seems like a stronger statement than the one I made...\n\n> What I see differently is that the purview of those decisions should be\n> that of the DB owner and not the superuser.\n\nYeah, I don't agree with that at all. If I'm a hosting provider, I\nwant to tell my customers what they're allowed to run and what they're\nnot allowed to run, but I don't want them to have to call me when they\nwant to run an extension I've decided is OK.\n\n> As it relates to things in contrib that could be classified as 'a pile\n> of crap' or 'too experimental'- that's *our* failing, and one which we\n> should accept and address instead of punting on it.\n\nI don't think changing what's in contrib helps much. Even if we rm\n-rf'd it, there's the same problem with out-of-core extensions. Joe\nExtensionman may think his extension ought to be trusted, and package\nit as such, but Paula Skepticaldba is entitled to think Joe's view of\nthe security risks originating from his code is overly rosy.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Wed, 8 Jan 2020 21:07:20 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Robert Haas (robertmhaas@gmail.com) wrote:\n> On Wed, Jan 8, 2020 at 6:09 PM Stephen Frost <sfrost@snowman.net> wrote:\n> > > To me, this seems more accidental than the natural fallout of good design.\n> >\n> > I disagree that the privilege design for FDWs was accidental.\n> \n> That seems like a stronger statement than the one I made...\n\nPerhaps I misunderstood what you were referring to then.\n\n> > What I see differently is that the purview of those decisions should be\n> > that of the DB owner and not the superuser.\n> \n> Yeah, I don't agree with that at all. If I'm a hosting provider, I\n> want to tell my customers what they're allowed to run and what they're\n> not allowed to run, but I don't want them to have to call me when they\n> want to run an extension I've decided is OK.\n\nNow I'm really floored because I've also been contemplating exactly the\nsituation of a hosting provider. In my experience, there's a few pretty\ncommon themes among the ones that I've played with:\n\n- Users definitely don't get true PG superuser\n- They certainly like users to be able to install trusted extensions\n- They'd generally prefer to minimize the size of their fork\n\nI've been feeling like the solution I'm pushing for would, in the end,\n*reduce* the amount of code they have that's different from PG, which I\nbelieve they'd see as an entirely good thing. The approach proposed in\nthis thread seems likely to either increase the size of the fork or, at\nbest, be about the same size.\n\nNow the question boils down to \"what's trusted?\" and if I'm a hosting\nprovider, it'd sure be nice to foist off the responsibility of figuring\nthat out on a community that I can trust that will do so at no cost to\nme, and who will address any bugs or security holes in those trusted\nextensions for me.\n\nRealistically, we pretty much already do that for contrib and that's\nreally all that's relevant here- anything else would need to be\nphysically installed on the system in order for a user to be able to\ninstall it, and I expect hosting providers to be pretty happy with a\nsolution that boils down to just having to install RPMs, or not (or the\nequivilant with regard to putting files into the right places and such).\n\nNow, if we're talking about defining repositories or allowing users to\nupload their *own* C code from their systems in to PG and install that\nas an extension, then, sure, that's gotta be limited to a superuser (and\nwouldn't be allowed by hosting providers). If the extension is\ninstalled on the system though, and it's marked as trusted, then why do\nwe need a superuser to take some additional action to allow it to be\ninstalled..?\n\nWhen it comes to the hosting provider case, I'd argue that what we're\nmissing here is a way for them to give their \"not-quite-a-superuser\nrole\" the ability to have certain capabilities (at install time, of\ncourse)- a good example of that would be \"allowed to make outbound\nnetwork connections\", with a way to then be able to delegate out that\nability to others. Then they'd actually be able to use things like\npostgres_fdw and dblink after they're installed and without having to\nget a superuser to grant them that ability post-install (and that order\nof operations issue is a pretty key one- it's far simpler to set things\nup and hand them over to the user than to have some operation that has\nto happen as an actual superuser after the installation is done).\n\nEven if we marked postgres_fdw as trusted, and used this default-role\nbased approach, we're almost certainly going to have the FDW itself be\nowned by the bootstrap superuser and therefore whatever non-superuser\nrole that installs it wouldn't be able to actually use it without some\nother changes. I'd love to get to a point where you could have an\ninitially set up system with a not-quite-superuser role that would be\nable to actually install AND use postgres_fdw, without having to fork\nPG.\n\n> > As it relates to things in contrib that could be classified as 'a pile\n> > of crap' or 'too experimental'- that's *our* failing, and one which we\n> > should accept and address instead of punting on it.\n> \n> I don't think changing what's in contrib helps much. Even if we rm\n> -rf'd it, there's the same problem with out-of-core extensions. Joe\n> Extensionman may think his extension ought to be trusted, and package\n> it as such, but Paula Skepticaldba is entitled to think Joe's view of\n> the security risks originating from his code is overly rosy.\n\nOut of core extensions have to get installed on to the system though,\nthey don't just show up magically, and lots and lots of folks out there\nfrom corporate infrastructure groups to hosting providers have got lots\nof experience with deciding what they'll allow to be installed on a\nsystem and what they won't, what repositories of code they'll trust and\nwhich they won't.\n\nOf course, when it comes to contrib extensions, if we don't feel\ncomfortable with them and we don't want to spend the time to vet them,\nwe can certainly just leave them marked as 'untrusted' and tell anyone\nwho wants to make them trusted that they need to put in the effort to\nreview that extension and get everyone comfortable with it.\n\nThanks,\n\nStephen", "msg_date": "Thu, 9 Jan 2020 10:09:11 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Thu, Jan 9, 2020 at 10:09 AM Stephen Frost <sfrost@snowman.net> wrote:\n> [ wall of text ]\n\nI don't see anything in here I really disagree with, but nor do I\nunderstand why any of it means that giving superusers the ability to\ncustomize which extensions are database-owner-installable would be a\nbad thing.\n\n> > I don't think changing what's in contrib helps much. Even if we rm\n> > -rf'd it, there's the same problem with out-of-core extensions. Joe\n> > Extensionman may think his extension ought to be trusted, and package\n> > it as such, but Paula Skepticaldba is entitled to think Joe's view of\n> > the security risks originating from his code is overly rosy.\n>\n> Out of core extensions have to get installed on to the system though,\n> they don't just show up magically, and lots and lots of folks out there\n> from corporate infrastructure groups to hosting providers have got lots\n> of experience with deciding what they'll allow to be installed on a\n> system and what they won't, what repositories of code they'll trust and\n> which they won't.\n\nYou seem to be ignoring the actual point of that example, which is\nthat someone may want to install the extension but have a different\nview than the packager about whether it should be trusted.\n\nYou seem to think that that hosting providers and system\nadministrators will be thrilled to accept the judgement of developers\nabout which extensions should be trusted in their environment. Great!\nI'm not trying to take away their ability to accept the judgement of\ndevelopers on that question. However, I also think some people will\nwant more control.\n\nEvidently you disagree, and that's fine, even if I don't understand\nwhy. Given some of the development projects you've done in the past, I\nfind it extremely surprising to here you now taking the position that\nfine-grained security controls are, in this case, unnecessary and\nuseless, but you don't have to like it everywhere just because you\nlike it for some things.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 9 Jan 2020 10:42:35 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Robert Haas (robertmhaas@gmail.com) wrote:\n> On Thu, Jan 9, 2020 at 10:09 AM Stephen Frost <sfrost@snowman.net> wrote:\n> > [ wall of text ]\n\nThis really isn't helpful.\n\n> I don't see anything in here I really disagree with, but nor do I\n> understand why any of it means that giving superusers the ability to\n> customize which extensions are database-owner-installable would be a\n> bad thing.\n\nAlright, I think there's definitely something we need to sort through.\n\nIf you agree that the approach I advocated means less code for hosting\nproviders to have to change in their fork, and that they don't want to\ngive users superuser, and that they want non-superusers to be able to\ninstall extensions, and that they really don't want to modify things\npost-install, then I don't get why you're against the DB-level privilege\nthat I've been advocating for except that it's \"not as customizable.\"\n\nAre you saying that in order to have something here that we must make it\nso that a superuser is able to specifiy, individually, which extensions\ncan be installed by which users? You keep coming back to this point of\nsaying that you want this to be 'customizable' but I really don't see\nany justification for the level of customization you're asking for- but\nI see an awful lot of work involved. When there's a lot of work\ninvolved for a use-case that no one is actually asking for, I'm really\nskeptical. The use-cases that you've presented, at least thus far,\ncertainly haven't swayed me into thinking that you're right that there's\na justifiable use-case here for this level of complicated privileges.\n\nI'm also not convinced that such a design would even be practical- we\ndon't know all of the extensions that a given PG install will be able to\nhave when it's first installed. If postgis isn't on the filesystem when\nsomeone installs PG, how do I, as a superuser, say that $user is allowed\nto install postgis? Or do we always have to have this two-step \"install\non filesystem\", \"grant privs to $user to install\" process? What if that\nextension is then uninstalled from the filesystem? Do we have to clean\nup the GRANT that was done?\n\n> > > I don't think changing what's in contrib helps much. Even if we rm\n> > > -rf'd it, there's the same problem with out-of-core extensions. Joe\n> > > Extensionman may think his extension ought to be trusted, and package\n> > > it as such, but Paula Skepticaldba is entitled to think Joe's view of\n> > > the security risks originating from his code is overly rosy.\n> >\n> > Out of core extensions have to get installed on to the system though,\n> > they don't just show up magically, and lots and lots of folks out there\n> > from corporate infrastructure groups to hosting providers have got lots\n> > of experience with deciding what they'll allow to be installed on a\n> > system and what they won't, what repositories of code they'll trust and\n> > which they won't.\n> \n> You seem to be ignoring the actual point of that example, which is\n> that someone may want to install the extension but have a different\n> view than the packager about whether it should be trusted.\n\nWhy would someone want to install something that isn't trusted? You're\nimplying that's what is happening here, but it doesn't make any sense to\nme and without it making sense I can't agree that it's a sensible enough\nuse-case to demand a lot of work be put into it.\n\n> You seem to think that that hosting providers and system\n> administrators will be thrilled to accept the judgement of developers\n> about which extensions should be trusted in their environment. Great!\n\nHuh? Hosting providers are the ones that choose what gets installed on\nthe filesystem, certainly not developers, so I am baffled how you came\nto the conclusion that I'm suggesting administrators are trusting the\njudgement of developers. That's just not at all the case.\n\n> Evidently you disagree, and that's fine, even if I don't understand\n> why. Given some of the development projects you've done in the past, I\n> find it extremely surprising to here you now taking the position that\n> fine-grained security controls are, in this case, unnecessary and\n> useless, but you don't have to like it everywhere just because you\n> like it for some things.\n\nI'm all for fine-grained control- where it makes sense. I'm still\n*very* much of the opinion that we should be able to let DB owners and\nschema owners control what kind of objects users are allowed to create\nin their DBs/schemas. I want a \"GRANT CREATE FUNCTION ON SCHEMA mine TO\nyou;\" ability. I'm not clamouring for a way to say \"GRANT CREATE\nTHISSPECIFICFUNCTION ON SCHEMA mine TO you;\" or something like \"GRANT\nCREATE FUNCTION MATCHING REGEXP 'abc_*' ON SCHEMA mine TO you;\".\n\nIn the end, superusers are, in fact, the ones who grant out ALL access,\nthe question is what level of access they want to grant out and to whom.\nWhen it comes to trusted objects, we've historically said that it's the\nDB owner who gets to say who can grant out that access and all I'm\ntrying to argue for is that we continue with that.\n\nThanks,\n\nStephen", "msg_date": "Thu, 9 Jan 2020 11:30:14 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Thu, Jan 9, 2020 at 11:30 AM Stephen Frost <sfrost@snowman.net> wrote:\n> * Robert Haas (robertmhaas@gmail.com) wrote:\n> > On Thu, Jan 9, 2020 at 10:09 AM Stephen Frost <sfrost@snowman.net> wrote:\n> > > [ wall of text ]\n>\n> This really isn't helpful.\n\nSorry.\n\nThat being said, I'm pretty tired of writing emails that say the same\nthing over and over again and having you write long responses that\ndon't seem to actually respond to the points being raised in the\nemail.\n\nLike:\n\n> > I don't see anything in here I really disagree with, but nor do I\n> > understand why any of it means that giving superusers the ability to\n> > customize which extensions are database-owner-installable would be a\n> > bad thing.\n>\n> Alright, I think there's definitely something we need to sort through.\n>\n> If you agree that the approach I advocated means less code for hosting\n> providers to have to change in their fork, and that they don't want to\n> give users superuser, and that they want non-superusers to be able to\n> install extensions, and that they really don't want to modify things\n> post-install, then I don't get why you're against the DB-level privilege\n> that I've been advocating for except that it's \"not as customizable.\"\n\nWhat I was writing about in the quoted paragraph and what you are\nwriting about in the response are two different things. I said\n*nothing* about a DB-level privilege in the paragraph I wrote, and yet\nsomehow your response to that paragraph says that I'm opposing a\nDB-level privilege.\n\n> Are you saying that in order to have something here that we must make it\n> so that a superuser is able to specifiy, individually, which extensions\n> can be installed by which users? You keep coming back to this point of\n> saying that you want this to be 'customizable' but I really don't see\n> any justification for the level of customization you're asking for- but\n> I see an awful lot of work involved. When there's a lot of work\n> involved for a use-case that no one is actually asking for, I'm really\n> skeptical. The use-cases that you've presented, at least thus far,\n> certainly haven't swayed me into thinking that you're right that there's\n> a justifiable use-case here for this level of complicated privileges.\n\nI set forth my exact views in\nhttp://postgr.es/m/CA+TgmoZK=5EC2O13J3sfOUCvYtvjGtxUKg=wQ11Q-wy4sc4b+g@mail.gmail.com\n\nEverything since then has been trying to somehow clarify what I wrote\nin that email, which has resulted in me repeating everything I said\nthere several times in different words. I would like to stop doing\nthat now. It appears to be clarifying nothing, failing to advance the\npatch, and irritating you.\n\n> I'm also not convinced that such a design would even be practical- ...\n\nAgain, as I said upthread, Tom had the exact feature about which I am\ntalking in the first version of the patch. That is a strong argument\nin favor of it being practical. It's also a pretty good argument that\nit is at least potentially useful, because Tom doesn't usually do\nuseless things for no reason.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 9 Jan 2020 12:55:04 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> Again, as I said upthread, Tom had the exact feature about which I am\n> talking in the first version of the patch. That is a strong argument\n> in favor of it being practical. It's also a pretty good argument that\n> it is at least potentially useful, because Tom doesn't usually do\n> useless things for no reason.\n\nTo try to clarify that a bit: I think there is certainly some value\nin allowing superusers to control which extensions could be installed\nby non-superusers, further restricting what we may think is trustworthy.\n\nHowever, I felt at the time that my GUC-based implementation of that\nwas ugly, and then Peter raised some concrete points against it,\nso I took it out. I don't want to put it back in the same form.\nI think we could leave designing a replacement for later, because it's\npretty optional, especially if we aren't aggressive about promoting\ncontrib modules to \"trusted\" status. I don't agree that the lack of\nsuch a feature is a reason not to commit what I've got.\n\nIn any case, AFAICT most of the heat-vs-light in this thread has not\nbeen about which extensions are trustworthy, but about which users\nshould be allowed to install extensions, which seems like a totally\nindependent discussion. And controlling that is also a feature that\nwe don't have today, so I'd rather get a minimal feature committed\nfor v13 and then later consider whether we need more functionality.\n\nThe idea of a DB-level INSTALL privilege addresses the second\npoint not the first, unless I'm totally misunderstanding it. As\nI said before, I'm not terribly comfortable with handing control\nof that over to non-superuser DB owners, and I sure don't see why\ndoing so should be a required part of the minimal feature.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 09 Jan 2020 13:35:07 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Thu, Jan 9, 2020 at 1:35 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Robert Haas <robertmhaas@gmail.com> writes:\n> > Again, as I said upthread, Tom had the exact feature about which I am\n> > talking in the first version of the patch. That is a strong argument\n> > in favor of it being practical. It's also a pretty good argument that\n> > it is at least potentially useful, because Tom doesn't usually do\n> > useless things for no reason.\n>\n> To try to clarify that a bit: I think there is certainly some value\n> in allowing superusers to control which extensions could be installed\n> by non-superusers, further restricting what we may think is trustworthy.\n\nCool.\n\n> However, I felt at the time that my GUC-based implementation of that\n> was ugly, and then Peter raised some concrete points against it,\n> so I took it out. I don't want to put it back in the same form.\n> I think we could leave designing a replacement for later, because it's\n> pretty optional, especially if we aren't aggressive about promoting\n> contrib modules to \"trusted\" status.\n\nAgreed.\n\n> I don't agree that the lack of\n> such a feature is a reason not to commit what I've got.\n\nI said the same in\nhttp://postgr.es/m/CA+TgmoYgwgS_RnMOooczZCgrZFqtfngshAq2Gu7LM5SKxrf_xQ@mail.gmail.com\n- penultimate paragraph, last sentence.\n\n> In any case, AFAICT most of the heat-vs-light in this thread has not\n> been about which extensions are trustworthy, but about which users\n> should be allowed to install extensions, which seems like a totally\n> independent discussion.\n\nI agree it's independent. It wasn't really the main point of what *I*\nwas trying to talk about, but the heat-vs-light problem seems to have\ntotally obscured what I *was* trying to talk about.\n\n> And controlling that is also a feature that\n> we don't have today, so I'd rather get a minimal feature committed\n> for v13 and then later consider whether we need more functionality.\n>\n> The idea of a DB-level INSTALL privilege addresses the second\n> point not the first, unless I'm totally misunderstanding it. As\n> I said before, I'm not terribly comfortable with handing control\n> of that over to non-superuser DB owners, and I sure don't see why\n> doing so should be a required part of the minimal feature.\n\nSo, if I understand correctly, the patch you are proposing to commit\nhas a new system role, and if you've got that system role, then you\ncan install extensions. I thought that part of the earlier debate was\nwhether DB owners should also be able to install trusted extensions\neven without that role, and I thought it would be cleaner if the\nanswer was \"no,\" because then the superuser could decide whether to\ngrant that role or not in particular cases. But I'm not clear whether\nyou agreed with that, what Stephen thought about it, or whether that's\nstill what you are proposing to commit.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 9 Jan 2020 14:06:03 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> So, if I understand correctly, the patch you are proposing to commit\n> has a new system role, and if you've got that system role, then you\n> can install extensions.\n\nInstall *trusted* extensions, correct. The patch as it stands also\nallows DB owners to install trusted extensions.\n\n> I thought that part of the earlier debate was\n> whether DB owners should also be able to install trusted extensions\n> even without that role, and I thought it would be cleaner if the\n> answer was \"no,\" because then the superuser could decide whether to\n> grant that role or not in particular cases. But I'm not clear whether\n> you agreed with that, what Stephen thought about it, or whether that's\n> still what you are proposing to commit.\n\nI agree that if we dropped the proviso about DB owners, it would be\na cleaner design. I included that only for backwards compatibility\nwith the existing behavior that DB owners can install trusted PLs.\nIf we can agree that we're willing to lose that behavior, I'd be\nperfectly fine with removing the special case for DB owners.\nHowever, I'm unsure whether that compatibility cost is acceptable.\nIt's definitely likely that it would cause an upgrade headache\nfor some installations.\n\nOne idea for working around the upgrade problem would be to teach\npg_dumpall to automatically issue \"GRANT pg_install_trusted_extension\"\nto each DB-owner role, when dumping from a pre-v13 database. There's\nroom to object to that, because it would end with more privilege than\nbefore (that is, an owner of some DB could now install extensions\neven in DBs she doesn't own, as long as she can connect to them).\nSo maybe it's a bad idea. But it would probably reduce the number\nof complaints --- and I think a lot of installations would end up\nmaking such grants anyway, because otherwise their DB owners can't\ndo things they expect to be able to do.\n\nI should not put words into Stephen's mouth, but perhaps his\nconcern about having some DB-level privilege here is to alleviate\nthe problem that there's no exact equivalent to the old level of\nprivilege that DB ownership afforded, ie you can install in your\nown DB but not others. It's not clear to me whether that behavior\nis critical to preserve.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 09 Jan 2020 14:48:40 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Robert Haas (robertmhaas@gmail.com) wrote:\n> On Thu, Jan 9, 2020 at 1:35 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > Robert Haas <robertmhaas@gmail.com> writes:\n> > > Again, as I said upthread, Tom had the exact feature about which I am\n> > > talking in the first version of the patch. That is a strong argument\n> > > in favor of it being practical. It's also a pretty good argument that\n> > > it is at least potentially useful, because Tom doesn't usually do\n> > > useless things for no reason.\n> >\n> > To try to clarify that a bit: I think there is certainly some value\n> > in allowing superusers to control which extensions could be installed\n> > by non-superusers, further restricting what we may think is trustworthy.\n> \n> Cool.\n\nI'm arguing for the position that superusers/admins have the ability to\ncontrol which extensions exist on the filesystem, and that plus the\n'trusted' marking is sufficient flexibility.\n\n> > However, I felt at the time that my GUC-based implementation of that\n> > was ugly, and then Peter raised some concrete points against it,\n> > so I took it out. I don't want to put it back in the same form.\n> > I think we could leave designing a replacement for later, because it's\n> > pretty optional, especially if we aren't aggressive about promoting\n> > contrib modules to \"trusted\" status.\n> \n> Agreed.\n\nAlso agreed- which is why I figured we weren't really discussing that\nany more.\n\n> > I don't agree that the lack of\n> > such a feature is a reason not to commit what I've got.\n> \n> I said the same in\n> http://postgr.es/m/CA+TgmoYgwgS_RnMOooczZCgrZFqtfngshAq2Gu7LM5SKxrf_xQ@mail.gmail.com\n> - penultimate paragraph, last sentence.\n\nI also agree that we don't need the \"who can install what extension\"\nflexibility that the original GUC-based approach contemplated, but\nthat's because I don't think we are likely to ever need it. If we do\nand someone comes up with a good design for it, that'd be fine too.\n\n> > In any case, AFAICT most of the heat-vs-light in this thread has not\n> > been about which extensions are trustworthy, but about which users\n> > should be allowed to install extensions, which seems like a totally\n> > independent discussion.\n> \n> I agree it's independent. It wasn't really the main point of what *I*\n> was trying to talk about, but the heat-vs-light problem seems to have\n> totally obscured what I *was* trying to talk about.\n\nI'm entirely confused about what you were trying to talk about then.\n\nMost of the back-and-forth, as I saw it anyway, were points being raised\nto say \"we can't let the right of installing extensions be allowed to DB\nowners\", which I don't agree with and which I've yet to see an actual\njustification for beyond \"well, we think it should require some explicit\nsuperuser privilege-granting, beyond the granting that the superuser\ndoes when they create a database owned by a given user.\"\n\n> > And controlling that is also a feature that\n> > we don't have today, so I'd rather get a minimal feature committed\n> > for v13 and then later consider whether we need more functionality.\n> >\n> > The idea of a DB-level INSTALL privilege addresses the second\n> > point not the first, unless I'm totally misunderstanding it. As\n> > I said before, I'm not terribly comfortable with handing control\n> > of that over to non-superuser DB owners, and I sure don't see why\n> > doing so should be a required part of the minimal feature.\n> \n> So, if I understand correctly, the patch you are proposing to commit\n> has a new system role, and if you've got that system role, then you\n> can install extensions. I thought that part of the earlier debate was\n> whether DB owners should also be able to install trusted extensions\n> even without that role, and I thought it would be cleaner if the\n> answer was \"no,\" because then the superuser could decide whether to\n> grant that role or not in particular cases. But I'm not clear whether\n> you agreed with that, what Stephen thought about it, or whether that's\n> still what you are proposing to commit.\n\nI do *not* agree with having a default role for this, at all. This\nlooks just like the right to CREATE tables or functions inside a schema,\nexcept with a DB-level object (an extension) instead of a schema-level\nobject, and that is the purview of the DB owner.\n\nThe arguments raised about $SCARYEXTENSION and security concerns make a\nlot of sense- I agree that those are things we should discuss and make\nsure that allowing a DB owner this privilege won't pave a way for them\nto get superuser access, but, imv anyway, we discussed those and didn't\nactually come up with any cases where it'd be an issue, in part thanks\nto Tom's design where the objects end up owned by the bootstrap\nsuperuser except in specific cases.\n\nSo I'm at a loss for why there is this insistence on a default role and\na superuser-explicit-granting based approach that goes beyond \"is it\ninstalled on the filesystem?\" and \"is it marked as trusted?\".\n\nThanks,\n\nStephen", "msg_date": "Thu, 9 Jan 2020 15:00:28 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Thu, Jan 9, 2020 at 2:48 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> I agree that if we dropped the proviso about DB owners, it would be\n> a cleaner design. I included that only for backwards compatibility\n> with the existing behavior that DB owners can install trusted PLs.\n> If we can agree that we're willing to lose that behavior, I'd be\n> perfectly fine with removing the special case for DB owners.\n> However, I'm unsure whether that compatibility cost is acceptable.\n> It's definitely likely that it would cause an upgrade headache\n> for some installations.\n\nI was assuming that installing extensions was fairly infrequent and\nthat it probably gets done mostly by superusers anyway, so probably\nmost people won't care if, after upgrading, they needed an extra GRANT\nto get things working again. That might be wrong, though.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 9 Jan 2020 15:06:26 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\nOn Thu, Jan 9, 2020 at 14:48 Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Robert Haas <robertmhaas@gmail.com> writes:\n> > So, if I understand correctly, the patch you are proposing to commit\n> > has a new system role, and if you've got that system role, then you\n> > can install extensions.\n>\n> Install *trusted* extensions, correct. The patch as it stands also\n> allows DB owners to install trusted extensions.\n>\n> > I thought that part of the earlier debate was\n> > whether DB owners should also be able to install trusted extensions\n> > even without that role, and I thought it would be cleaner if the\n> > answer was \"no,\" because then the superuser could decide whether to\n> > grant that role or not in particular cases. But I'm not clear whether\n> > you agreed with that, what Stephen thought about it, or whether that's\n> > still what you are proposing to commit.\n>\n> I agree that if we dropped the proviso about DB owners, it would be\n> a cleaner design. I included that only for backwards compatibility\n> with the existing behavior that DB owners can install trusted PLs.\n> If we can agree that we're willing to lose that behavior, I'd be\n> perfectly fine with removing the special case for DB owners.\n> However, I'm unsure whether that compatibility cost is acceptable.\n> It's definitely likely that it would cause an upgrade headache\n> for some installations.\n>\n> One idea for working around the upgrade problem would be to teach\n> pg_dumpall to automatically issue \"GRANT pg_install_trusted_extension\"\n> to each DB-owner role, when dumping from a pre-v13 database. There's\n> room to object to that, because it would end with more privilege than\n> before (that is, an owner of some DB could now install extensions\n> even in DBs she doesn't own, as long as she can connect to them).\n> So maybe it's a bad idea. But it would probably reduce the number\n> of complaints --- and I think a lot of installations would end up\n> making such grants anyway, because otherwise their DB owners can't\n> do things they expect to be able to do.\n>\n> I should not put words into Stephen's mouth, but perhaps his\n> concern about having some DB-level privilege here is to alleviate\n> the problem that there's no exact equivalent to the old level of\n> privilege that DB ownership afforded, ie you can install in your\n> own DB but not others. It's not clear to me whether that behavior\n> is critical to preserve.\n\n\nI am not particularly concerned about that backwards compatibility issue\nand I don’t intend to base my argument on it, but I would use that case to\npoint out that we have long had the ability to install trusted C functions\ninto the backend as a DB owner, without complaint from either users or\nsecurity pedants, and that backs up my position that we are setting up this\nprivilege at the wrong level by using a default role which a superuser must\ngrant independently from DB ownership.\n\nThanks,\n\nStephen\n\n>\n\nGreetings,On Thu, Jan 9, 2020 at 14:48 Tom Lane <tgl@sss.pgh.pa.us> wrote:Robert Haas <robertmhaas@gmail.com> writes:\n> So, if I understand correctly, the patch you are proposing to commit\n> has a new system role, and if you've got that system role, then you\n> can install extensions.\n\nInstall *trusted* extensions, correct.  The patch as it stands also\nallows DB owners to install trusted extensions.\n\n> I thought that part of the earlier debate was\n> whether DB owners should also be able to install trusted extensions\n> even without that role, and I thought it would be cleaner if the\n> answer was \"no,\" because then the superuser could decide whether to\n> grant that role or not in particular cases. But I'm not clear whether\n> you agreed with that, what Stephen thought about it, or whether that's\n> still what you are proposing to commit.\n\nI agree that if we dropped the proviso about DB owners, it would be\na cleaner design.  I included that only for backwards compatibility\nwith the existing behavior that DB owners can install trusted PLs.\nIf we can agree that we're willing to lose that behavior, I'd be\nperfectly fine with removing the special case for DB owners.\nHowever, I'm unsure whether that compatibility cost is acceptable.\nIt's definitely likely that it would cause an upgrade headache\nfor some installations.\n\nOne idea for working around the upgrade problem would be to teach\npg_dumpall to automatically issue \"GRANT pg_install_trusted_extension\"\nto each DB-owner role, when dumping from a pre-v13 database.  There's\nroom to object to that, because it would end with more privilege than\nbefore (that is, an owner of some DB could now install extensions\neven in DBs she doesn't own, as long as she can connect to them).\nSo maybe it's a bad idea.  But it would probably reduce the number\nof complaints --- and I think a lot of installations would end up\nmaking such grants anyway, because otherwise their DB owners can't\ndo things they expect to be able to do.\n\nI should not put words into Stephen's mouth, but perhaps his\nconcern about having some DB-level privilege here is to alleviate\nthe problem that there's no exact equivalent to the old level of\nprivilege that DB ownership afforded, ie you can install in your\nown DB but not others.  It's not clear to me whether that behavior\nis critical to preserve.I am not particularly concerned about that backwards compatibility issue and I don’t intend to base my argument on it, but I would use that case to point out that we have long had the ability to install trusted C functions into the backend as a DB owner, without complaint from either users or security pedants, and that backs up my position that we are setting up this privilege at the wrong level by using a default role which a superuser must grant independently from DB ownership. Thanks,Stephen", "msg_date": "Thu, 9 Jan 2020 15:18:19 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> So I'm at a loss for why there is this insistence on a default role and\n> a superuser-explicit-granting based approach that goes beyond \"is it\n> installed on the filesystem?\" and \"is it marked as trusted?\".\n\nOkay, so it seems like we're down to just this one point of contention.\nYou feel that the superuser can control what is in the extension library\ndirectory and that that ought to be sufficient control. I disagree\nwith that, for two reasons:\n\n* ISTM that that's assuming that the DBA and the sysadmin are the same\nperson (or at least hold identical views on this subject). In many\ninstallations it'd only be root who has control over what's in that\ndirectory, and I don't think it's unreasonable for the DBA to wish\nto be able to exercise additional filtering.\n\n* The point of a default role would be for the DBA to be able to\ncontrol which database users can install extensions. Even if the\nDBA has full authority over the extension library, that would not\nprovide control over who can install, only over what is available\nfor any of them to install.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 09 Jan 2020 15:18:30 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> I am not particularly concerned about that backwards compatibility issue\n> and I don’t intend to base my argument on it, but I would use that case to\n> point out that we have long had the ability to install trusted C functions\n> into the backend as a DB owner, without complaint from either users or\n> security pedants,\n\nRight, which is why my patch proposes generalizing that feature for\ntrusted PLs into a general feature for other extensions. I'd be\nmuch leerier of that if we'd had any pushback on it for trusted PLs.\n\n> ... and that backs up my position that we are setting up this\n> privilege at the wrong level by using a default role which a superuser must\n> grant independently from DB ownership.\n\nDon't see how this follows. It's somewhat accidental I think that\nthe existing behavior is tied to DB ownership. That's just because\nat the time, that's the only sort of privilege we had that seemed\nintermediate between superuser and Joe User. If we were designing\nthe behavior today, with default roles already a done deal for\nhanding out possibly-dangerous privileges, I think there's no\nquestion that we'd be setting up this privilege as a default role\nrather than tying it to DB ownership. We don't make DB ownership\na prerequisite to creating other sorts of functions, yet other\nfunctions can be just as dangerous in some cases as C functions.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 09 Jan 2020 15:33:41 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Thu, Jan 9, 2020 at 3:18 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> * ISTM that that's assuming that the DBA and the sysadmin are the same\n> person (or at least hold identical views on this subject). In many\n> installations it'd only be root who has control over what's in that\n> directory, and I don't think it's unreasonable for the DBA to wish\n> to be able to exercise additional filtering.\n\nAn emphatic +1 from me. This is what I've been trying to argue over\nand over, apparently rather unclearly.\n\n> * The point of a default role would be for the DBA to be able to\n> control which database users can install extensions. Even if the\n> DBA has full authority over the extension library, that would not\n> provide control over who can install, only over what is available\n> for any of them to install.\n\nI agree with that, too. I guess you could decide that the answer to\nthe question \"who can install extensions?\" must be the same as the\nanswer to the question \"who owns a database?\" but having the\nflexibility to make the answers to those questions different seems\nbetter than forcing them to always be the same.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 9 Jan 2020 15:35:23 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> Stephen Frost <sfrost@snowman.net> writes:\n> > So I'm at a loss for why there is this insistence on a default role and\n> > a superuser-explicit-granting based approach that goes beyond \"is it\n> > installed on the filesystem?\" and \"is it marked as trusted?\".\n> \n> Okay, so it seems like we're down to just this one point of contention.\n\nI agree that this seems to be the crux of the contention- though I need\nto revisit what I wrote above because I didn't cover everything\nrelevant. I'm suggesting that having:\n\n- Extension installed on the filesystem\n- Extension is marked as trusted\n- Calling user has been made a DB owner (which, from a bare initdb,\n requires a superuser to take action to make happen)\n\nis what would be needed to install a trusted extension.\n\n> You feel that the superuser can control what is in the extension library\n> directory and that that ought to be sufficient control. I disagree\n> with that, for two reasons:\n> \n> * ISTM that that's assuming that the DBA and the sysadmin are the same\n> person (or at least hold identical views on this subject). In many\n> installations it'd only be root who has control over what's in that\n> directory, and I don't think it's unreasonable for the DBA to wish\n> to be able to exercise additional filtering.\n\nI don't think we should start conflating roles by saying things like\n\"DBA\" because it's not clear if that's \"PG superuser\" or \"DB owner\" or\n\"DB user\". In many, many, many installations the DBA is *not* the\nsuperuser- in fact, pretty much every cloud-provider installation of PG\nis that way.\n\nEven so though, I don't agree with this particular rationale as, at\nleast largely in my experience, the sysadmin isn't going to go\ninstalling things on their own- they're going to install what they've\nbeen asked to, and it'll be a PG superuser or DB owner or DB user\ndoing the asking (and hopefully they'll consult with whomever is\nappropriate before installing anything anyway). The idea that\nadditional filtering on that is needed strikes me as highly unlikely.\n\nNow, that said, I'm not strictly against the idea of allowing a\nsuperuser, if they wish, to do additional filtering of what's allowed\n(though I think there's a fair bit of complication in coming up with a\nsensible way for them to do so, but that's an independent discussion).\nI still don't think that the privilege to install a trusted extension\nshould be done through a default role though, or that it needs to be\nindependent from the DB owner role.\n\n> * The point of a default role would be for the DBA to be able to\n> control which database users can install extensions. Even if the\n> DBA has full authority over the extension library, that would not\n> provide control over who can install, only over what is available\n> for any of them to install.\n\nIn my approach, a superuser absolutely still has control over which\ndatabase users can install extensions, by virtue of being in control\nover which users are DB owners, and further by being able to GRANT out\nthe right to install extensions, in specific databases, to specific\nusers. If we want to have a mechanism where superusers can further\nwhitelist or blacklist extensions across the cluster, that's fine, but,\nagain, that's largely orthogonal to what I'm talking about.\n\nAlso, consider this- with the default role approach, is a user granted\nthat role allowed to create extensions in *every* database they can\nconnect to, or do they need some additional privilege, like CREATE\nrights on the database, which is then under the purview of the database\nowner? What if the superuser wishes to allow a given role the ability\nto install extensions only in a specific database? That strikes me as\nhighly likely use-case (\"you can install extensions in this other\ndatabase, but not in the 'postgres' database that I use for my\nmonitoring and other stuff\") that isn't addressed at all with this\ndefault role approach (looking at the patch, it seems to switch to the\nsuperuser role to actually create objects, of course, so the caller\ndoesn't need create rights in the database), but is with mine- and\ndone so in a natural, intuitive, way that works just like the rest of\nour privilege system.\n\nI've always viewed the privilege system in PG to be a hierarchchy of\nprivileges-\n\nsuperuser - ultimate owner, able to do everything\nDB owner - controls create/use/modify for objects in the database,\n and altering of the database itself\nschema owner- controls create/use/modify for objects in a schema, and\n altering of the schema itself\ntable owner - controls access/use/modify for the table, and altering of\n table itself\n\nNow we're moving outside of that to start using default roles to control\nwho can create objects in a database, and that's what I don't agree\nwith. If the superuser doesn't feel that a particular role should be\nable to create extensions in a given database, there is a simple and\nwell understood solution- don't have that role own that database. None\nof what I've been talking about has ever taken away anything from the\nsuperuser or made it such that the superuser wouldn't have any say in\nwho can install extensions. I'll accept that if a superuser wished for\na given role to be able to run ALTER DATABASE but not install extensions\nthen that would present an issue in this model, but that feels like a\nreally tenuous argument and isn't one that anyone here has actually been\nmaking, instead it seems to be a bunch of hand-wringing about how this\nmight be giving DB owners too much power, when they're already the ones\nwho control who is allowed to create objects in the database, or not.\n\nThanks,\n\nStephen", "msg_date": "Fri, 10 Jan 2020 14:18:59 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> > ... and that backs up my position that we are setting up this\n> > privilege at the wrong level by using a default role which a superuser must\n> > grant independently from DB ownership.\n> \n> Don't see how this follows. It's somewhat accidental I think that\n> the existing behavior is tied to DB ownership. That's just because\n> at the time, that's the only sort of privilege we had that seemed\n> intermediate between superuser and Joe User. If we were designing\n> the behavior today, with default roles already a done deal for\n> handing out possibly-dangerous privileges, I think there's no\n> question that we'd be setting up this privilege as a default role\n> rather than tying it to DB ownership. We don't make DB ownership\n> a prerequisite to creating other sorts of functions, yet other\n> functions can be just as dangerous in some cases as C functions.\n\nI suppose I'll just have to say that I disagree. I see a lot of value\nin having a level between superuser and Joe User, and DB owner looks\npretty natural as exactly that, particularly for creating database-level\nobjects like extensions.\n\nIf anything, I tend to think we need more levels, not less- like a level\nthat's \"cluster owner\" or something along those lines, that's also\nindependent from \"superuser\" but would allow creating of cluster-level\nobjects like databases and roles (with the right to then GRANT the\nability to create those objects to other roles, if they wish).\n\nI don't really see default roles as a better alternative to a privilege\nhierarchy, but rather as a way for controlling access to things that\ndon't really fall into the hierarchy. Maybe for cluster-level things\nlike what I hint at above they'd be better, but for database-level\nobjects, where you might decide you want to give a user access to create\nsomething in database X but not in database Y? Doesn't seem to fit very\nwell to me.\n\nThanks,\n\nStephen", "msg_date": "Fri, 10 Jan 2020 14:26:46 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> * Tom Lane (tgl@sss.pgh.pa.us) wrote:\n>> Don't see how this follows. It's somewhat accidental I think that\n>> the existing behavior is tied to DB ownership. That's just because\n>> at the time, that's the only sort of privilege we had that seemed\n>> intermediate between superuser and Joe User. If we were designing\n>> the behavior today, with default roles already a done deal for\n>> handing out possibly-dangerous privileges, I think there's no\n>> question that we'd be setting up this privilege as a default role\n>> rather than tying it to DB ownership. We don't make DB ownership\n>> a prerequisite to creating other sorts of functions, yet other\n>> functions can be just as dangerous in some cases as C functions.\n\n> I suppose I'll just have to say that I disagree. I see a lot of value\n> in having a level between superuser and Joe User, and DB owner looks\n> pretty natural as exactly that, particularly for creating database-level\n> objects like extensions.\n\nWell, the other direction we could go here, which I guess is what\nyou are arguing for, is to forget the new default role and just\nsay that marking an extension trusted allows it to be installed by\nDB owners, full stop. That's nice and simple and creates no\nbackwards-compatibility issues. If we later decide that we want\na default role, or any other rules about who-can-install, we might\nfeel like this was a mistake --- but the backwards-compatibility issues\nwe'd incur by changing it later are exactly the same as what we'd have\ntoday if we do something different from this. The only difference\nis that there'd be more extensions affected later (assuming we mark\nmore things trusted).\n\nI'm willing to go with this solution if it'll end the argument.\nRobert, Peter, what do you think?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 10 Jan 2020 14:39:58 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Fri, Jan 10, 2020 at 2:40 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Well, the other direction we could go here, which I guess is what\n> you are arguing for, is to forget the new default role and just\n> say that marking an extension trusted allows it to be installed by\n> DB owners, full stop. That's nice and simple and creates no\n> backwards-compatibility issues. If we later decide that we want\n> a default role, or any other rules about who-can-install, we might\n> feel like this was a mistake --- but the backwards-compatibility issues\n> we'd incur by changing it later are exactly the same as what we'd have\n> today if we do something different from this. The only difference\n> is that there'd be more extensions affected later (assuming we mark\n> more things trusted).\n\nI agree with your analysis, but I'm still inclined to feel that the\nnew pre-defined roll is a win.\n\nGenerally, decoupled permissions are better. Being able to grant\nsomeone either A or B or both or neither is usually superior to having\nto grant either both permissions or neither.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 10 Jan 2020 15:23:48 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Robert Haas (robertmhaas@gmail.com) wrote:\n> On Fri, Jan 10, 2020 at 2:40 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > Well, the other direction we could go here, which I guess is what\n> > you are arguing for, is to forget the new default role and just\n> > say that marking an extension trusted allows it to be installed by\n> > DB owners, full stop. That's nice and simple and creates no\n> > backwards-compatibility issues. If we later decide that we want\n> > a default role, or any other rules about who-can-install, we might\n> > feel like this was a mistake --- but the backwards-compatibility issues\n> > we'd incur by changing it later are exactly the same as what we'd have\n> > today if we do something different from this. The only difference\n> > is that there'd be more extensions affected later (assuming we mark\n> > more things trusted).\n> \n> I agree with your analysis, but I'm still inclined to feel that the\n> new pre-defined roll is a win.\n> \n> Generally, decoupled permissions are better. Being able to grant\n> someone either A or B or both or neither is usually superior to having\n> to grant either both permissions or neither.\n\nRight- I like the idea of decoupled permissions too.\n\nTo be clear, I was advocating for a NEW DB-level privilege ('INSTALL' or\n'CREATE EXTENSION' if we could make that work), so that we have it be\ndistinct from CREATE (which, today, really means 'CREATE SCHEMA').\n\nI'd be willing to accept making this part of DB-level 'CREATE' rights if\nthere is a huge amount of push-back about burning a privilege bit for\nit, but, as discussed up-thread, I don't think we should really be\nstressing ourselves about that.\n\nI do like the idea of having it be decoupled from explicit DB ownership,\nso that a DB owner (or superuser) could say \"I want this role to be able\nto install extensions, but NOT run ALTER DATABASE\", and optionally even\ninclude ADMIN so that it could be further delegated (and also because\nthen it'd be just like the rest of our GRANT privilege system, and I\nlike that..).\n\nThanks,\n\nStephen", "msg_date": "Fri, 10 Jan 2020 15:50:03 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> To be clear, I was advocating for a NEW DB-level privilege ('INSTALL' or\n> 'CREATE EXTENSION' if we could make that work), so that we have it be\n> distinct from CREATE (which, today, really means 'CREATE SCHEMA').\n\nI still say this is wrong, or at least pointless, because it'd be a\nright that any DB owner could grant to himself. If we're to have any\nmeaningful access control on extension installation, the privilege\nwould have to be attached to some other object ... and there's no clear\ncandidate for what. As someone noted awhile back, if we could somehow\nattach ACLs to potentially-installable extensions, that might be an\ninteresting avenue to pursue. That's well beyond what I'm willing\nto pursue for v13, though.\n\nIn the meantime, though, this idea as stated doesn't do anything except\nlet a DB owner grant install privileges to someone else. I'm not even\nconvinced that we want that, or that anyone needs it (I can recall zero\nsuch requests related to PLs in the past). And for sure it does not\nbelong in a minimal implementation of this feature.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 10 Jan 2020 17:53:10 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> Stephen Frost <sfrost@snowman.net> writes:\n> > To be clear, I was advocating for a NEW DB-level privilege ('INSTALL' or\n> > 'CREATE EXTENSION' if we could make that work), so that we have it be\n> > distinct from CREATE (which, today, really means 'CREATE SCHEMA').\n> \n> I still say this is wrong, or at least pointless, because it'd be a\n> right that any DB owner could grant to himself.\n\nYes, of course it is, that the DB owner would have this privilege was\nsomething you agreed to in the prior email- I'd rather not just have a\n\"if (DBOwner())\" check, I'd rather use our actual privilege system and\nhave this be a right that the DB owner has but can then GRANT out to\nothers if they wish to.\n\nI'm certainly not suggesting that such a privilege wouldn't be\ncontrolled by the DB owner. Forcing it to only be allowed for the DB\nowner and not be something that the DB owner can GRANT out isn't much\nbetter than \"if (superuser())\"-style checks.\n\n> If we're to have any\n> meaningful access control on extension installation, the privilege\n> would have to be attached to some other object ... and there's no clear\n> candidate for what.\n\nExtensions are installed at the DB level, not at any other level, and\ntherefore that's the appropriate place to attach them, which is exactly\nwhat I'm suggesting we do here.\n\n> As someone noted awhile back, if we could somehow\n> attach ACLs to potentially-installable extensions, that might be an\n> interesting avenue to pursue. That's well beyond what I'm willing\n> to pursue for v13, though.\n\nSure, having some catalog of installable extensions where someone (in my\nthinking, the DB owner) could GRANT out access to install certain\nextensions to others might be interesting, but it's not what I'm\nsuggesting here.\n\n> In the meantime, though, this idea as stated doesn't do anything except\n> let a DB owner grant install privileges to someone else. I'm not even\n> convinced that we want that, or that anyone needs it (I can recall zero\n> such requests related to PLs in the past). And for sure it does not\n> belong in a minimal implementation of this feature.\n\nYes, that's what this approach would do. I suppose an alternative would\nbe to lump it in with \"CREATE\" rights on the DB, but I've advocated and\nwill continue to advocate for splitting up of such broad rights.\nDB-level CREATE rights currently cover both schemas and publications,\nfor example, even though the two have rather little to do with each\nother.\n\nIf the only agreeable option is a if (DBOwner())-type check, or lumping\nthe privilege to CREATE (trusted) EXTENSION in with other DB-level\nCREATE rights, then I'll go along with one of those. I'll be happy\nenough with that, since it avoids having an additional default role that\nhas to be GRANT'd by a superuser. Ideally, down the road, we'll split\nout the CREATE privilege (both at DB and at schema level) to be more\nfine grained, but that can certainly be done later.\n\nThanks,\n\nStephen", "msg_date": "Mon, 13 Jan 2020 13:40:19 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> * Tom Lane (tgl@sss.pgh.pa.us) wrote:\n>> In the meantime, though, this idea as stated doesn't do anything except\n>> let a DB owner grant install privileges to someone else. I'm not even\n>> convinced that we want that, or that anyone needs it (I can recall zero\n>> such requests related to PLs in the past). And for sure it does not\n>> belong in a minimal implementation of this feature.\n\n> Yes, that's what this approach would do. I suppose an alternative would\n> be to lump it in with \"CREATE\" rights on the DB, but I've advocated and\n> will continue to advocate for splitting up of such broad rights.\n> DB-level CREATE rights currently cover both schemas and publications,\n> for example, even though the two have rather little to do with each\n> other.\n\nThe patch as I'm proposing it has nothing to do with \"CREATE\" rights.\nYou're attacking something different from what I actually want to do.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 13 Jan 2020 15:38:59 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> Stephen Frost <sfrost@snowman.net> writes:\n> > * Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> >> In the meantime, though, this idea as stated doesn't do anything except\n> >> let a DB owner grant install privileges to someone else. I'm not even\n> >> convinced that we want that, or that anyone needs it (I can recall zero\n> >> such requests related to PLs in the past). And for sure it does not\n> >> belong in a minimal implementation of this feature.\n> \n> > Yes, that's what this approach would do. I suppose an alternative would\n> > be to lump it in with \"CREATE\" rights on the DB, but I've advocated and\n> > will continue to advocate for splitting up of such broad rights.\n> > DB-level CREATE rights currently cover both schemas and publications,\n> > for example, even though the two have rather little to do with each\n> > other.\n> \n> The patch as I'm proposing it has nothing to do with \"CREATE\" rights.\n> You're attacking something different from what I actually want to do.\n\nYes, as an aside, I'm argueing that we should split up the general\nCREATE privileges, but I also said that's not required for this.\n\nYou're asking \"what's the best way to add this privilege to PG?\". I'm\nsaying that it should be done through the privilege system, similar to\npublications. I'd prefer it not be lumped into CREATE, but that at\nleast makes sense to me- adding a default role for this doesn't. I\nsuppose making it akin to ALTER DATABASE and having it be limited to the\nDB owner is also alright (as I said in my last email) but it means that\nsomeone has to be given DB ownership rights in order to install\nextensions. I don't really see CREATE EXTENSION as being like ALTER\nDATABASE from a privilege perspective, but having it be DB owner still\nmakes more sense than a default role for this.\n\nThanks,\n\nStephen", "msg_date": "Mon, 13 Jan 2020 15:57:57 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> * Tom Lane (tgl@sss.pgh.pa.us) wrote:\n>> The patch as I'm proposing it has nothing to do with \"CREATE\" rights.\n>> You're attacking something different from what I actually want to do.\n\n> Yes, as an aside, I'm argueing that we should split up the general\n> CREATE privileges, but I also said that's not required for this.\n\nSo how do we move this forward? I really don't want this patch to be\nblocked by what's fundamentally a side point about permissions.\n\nThe minimum committable patch seems like it would just grant the\n\"can install trusted extensions\" ability to DB owners, full stop.\nThis is small, it's exactly the same as our historical behavior for\ntrusted PLs, and it's upward compatible with either of two possible\nfuture extensions:\n\n* adding a predefined role (which'd let superusers give out the install\nprivilege, in addition to DB owners having it)\n\n* converting DB owners' hard-wired privilege to a grantable privilege\n(which'd let DB owners give out the install privilege, if the privilege\nis attached to the DBs themselves; but maybe there's some other way?)\n\nGiven the lack of consensus about either of those being what we want,\nit doesn't seem like we're going to come to an agreement in a\nreasonable timeframe on a patch that includes either. So I'd like\nto get this done and move on to the next problem (ie, what is it\nwe're actually going to do about the python 2/3 mess).\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 21 Jan 2020 12:40:12 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Tue, Jan 21, 2020 at 12:40 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Given the lack of consensus about either of those being what we want,\n> it doesn't seem like we're going to come to an agreement in a\n> reasonable timeframe on a patch that includes either. So I'd like\n> to get this done and move on to the next problem (ie, what is it\n> we're actually going to do about the python 2/3 mess).\n\nI'm fine with that.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 21 Jan 2020 16:55:20 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> Stephen Frost <sfrost@snowman.net> writes:\n> > * Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> >> The patch as I'm proposing it has nothing to do with \"CREATE\" rights.\n> >> You're attacking something different from what I actually want to do.\n> \n> > Yes, as an aside, I'm argueing that we should split up the general\n> > CREATE privileges, but I also said that's not required for this.\n> \n> So how do we move this forward? I really don't want this patch to be\n> blocked by what's fundamentally a side point about permissions.\n> \n> The minimum committable patch seems like it would just grant the\n> \"can install trusted extensions\" ability to DB owners, full stop.\n\nIf you're alright with making it something a DB owner can do, what is\nthe issue with making it part of the CREATE right on the database? That\ndoesn't require any additional permission bits, in a default setup\ndoesn't change who is able to create extensions (in either your proposal\nor mine, it's the DB owner), and in either proposal means that people\nwho couldn't create extensions with PG12 will be able to create them in\nPG13.\n\nWe've added other things to the DB-level CREATE rights rather recently\ntoo, so it's not like we've historically avoided that.\n\nThe argument you presented previously against that idea was because it\nwould mean the DB owner would still be able to exercise that right,\nwhich is what you're now proposing anyway and which I was always\nadvocating for and wasn't trying to say wouldn't be the case with that\napproach.\n\nSo I'm at a loss for what the actual argument is against making it part\nof DB-level CREATE.\n\n> This is small, it's exactly the same as our historical behavior for\n> trusted PLs, and it's upward compatible with either of two possible\n> future extensions:\n> \n> * adding a predefined role (which'd let superusers give out the install\n> privilege, in addition to DB owners having it)\n\nUh, just to be clear, even with your approach, a DB owner could 'GRANT'\nthe necessary right for another user to install extensions by simply\nGRANT'ing their own role to that user. Obviously, that conveys other\nprivileges with it, but we have that problem at any level as long as we\nconstrain ourselves to a single set of 32 bits for representing\nprivileges. I see it as being manifestly better to lump it in with the\nDB-level CREATE privilege though.\n\n> * converting DB owners' hard-wired privilege to a grantable privilege\n> (which'd let DB owners give out the install privilege, if the privilege\n> is attached to the DBs themselves; but maybe there's some other way?)\n\nIn either of these proposals, we could split up the bounded-together\nprivileges down the road, and, sure, there might be more than one way to\ndo that, but I really don't want to go down a road where every privilege\nends up being split up into a seperate default-role (or predefined role\nor whatever we want to call those things today).\n\n> Given the lack of consensus about either of those being what we want,\n> it doesn't seem like we're going to come to an agreement in a\n> reasonable timeframe on a patch that includes either. So I'd like\n> to get this done and move on to the next problem (ie, what is it\n> we're actually going to do about the python 2/3 mess).\n\nI get that you want to push forward with making this part of the DB\nowner, and I said up-thread that I'd be able to live with that, but I\nstill don't understand what the argument is against making it part of\nCREATE instead.\n\nThanks,\n\nStephen", "msg_date": "Tue, 28 Jan 2020 15:29:18 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Tue, Jan 28, 2020 at 3:29 PM Stephen Frost <sfrost@snowman.net> wrote:\n> I get that you want to push forward with making this part of the DB\n> owner, and I said up-thread that I'd be able to live with that, but I\n> still don't understand what the argument is against making it part of\n> CREATE instead.\n\nIt's a change from the status quo. If we're going to how it works, we\nshould try to agree on how it ought to work. Tom's proposal dodges\nthat by leaving things exactly as they are, deferring any actual\nmodifications to who can do what to a future patch.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 28 Jan 2020 15:45:33 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> * Tom Lane (tgl@sss.pgh.pa.us) wrote:\n>> The minimum committable patch seems like it would just grant the\n>> \"can install trusted extensions\" ability to DB owners, full stop.\n\n> If you're alright with making it something a DB owner can do, what is\n> the issue with making it part of the CREATE right on the database?\n\nUm, well, people were complaining that it should be a distinct privilege,\nwhich I for one wasn't sold on.\n\nI continue to think that allowing DB owners to decide this is, if not\nfundamentally the wrong thing, at least not a feature that anybody has\nasked for in the past. The feature *I* want in this area is for the\nsuperuser to be able to decide who's got install privilege. Making\nit a DB-level privilege doesn't serve that goal, more the opposite.\n\nStill, if we can compromise by making this part of DB \"CREATE\" privilege\nfor the time being, I'm willing to take that compromise. It's certainly\nbetter than failing to get rid of pg_pltemplate.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 28 Jan 2020 15:52:36 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "On Tue, Jan 28, 2020 at 3:52 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> I continue to think that allowing DB owners to decide this is, if not\n> fundamentally the wrong thing, at least not a feature that anybody has\n> asked for in the past. The feature *I* want in this area is for the\n> superuser to be able to decide who's got install privilege. Making\n> it a DB-level privilege doesn't serve that goal, more the opposite.\n\nI agree.\n\n> Still, if we can compromise by making this part of DB \"CREATE\" privilege\n> for the time being, I'm willing to take that compromise. It's certainly\n> better than failing to get rid of pg_pltemplate.\n\nDoesn't that have exactly the issue you describe above?\n\nbob=> grant create on database bob to fred;\nGRANT\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 28 Jan 2020 15:58:28 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> On Tue, Jan 28, 2020 at 3:52 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I continue to think that allowing DB owners to decide this is, if not\n>> fundamentally the wrong thing, at least not a feature that anybody has\n>> asked for in the past. The feature *I* want in this area is for the\n>> superuser to be able to decide who's got install privilege. Making\n>> it a DB-level privilege doesn't serve that goal, more the opposite.\n\n> I agree.\n\n>> Still, if we can compromise by making this part of DB \"CREATE\" privilege\n>> for the time being, I'm willing to take that compromise. It's certainly\n>> better than failing to get rid of pg_pltemplate.\n\n> Doesn't that have exactly the issue you describe above?\n> bob=> grant create on database bob to fred;\n> GRANT\n\nEither of them do, in that a DB owner can always grant his whole role;\n\"grant bob to fred\" will give fred install privileges (in bob's DBs)\nregardless of which of these choices we adopt. And that was true before\n(with respect to trusted PLs), too. Attaching the ability to the CREATE\nbit would at least allow DB owners to be a bit more selective about how\nthey give it out.\n\nThe reason I'm happier about doing this with CREATE than inventing\na separate INSTALL bit is that once we do the latter, we're more or\nless bound to keep supporting that ability forever. If we extend\nthe definition of CREATE in v13, and then narrow it again in some\nfuture release, that seems less likely to cause problems than taking\naway a named privilege bit would do.\n\nOn the other hand, there's the point that lots of people have probably\ngiven out schema-CREATE privilege to users whom they wouldn't necessarily\nwish to trust with INSTALL privilege. Schema-CREATE is a pretty harmless\nprivilege, INSTALL much less so.\n\nI do like your point about how maybe we shouldn't change the status quo\nwithout more consensus than we've got ... but in the end I just want\nto get this done and move on.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 28 Jan 2020 16:16:56 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Greetings,\n\nOn Tue, Jan 28, 2020 at 16:17 Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Robert Haas <robertmhaas@gmail.com> writes:\n> > On Tue, Jan 28, 2020 at 3:52 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> I continue to think that allowing DB owners to decide this is, if not\n> >> fundamentally the wrong thing, at least not a feature that anybody has\n> >> asked for in the past. The feature *I* want in this area is for the\n> >> superuser to be able to decide who's got install privilege. Making\n> >> it a DB-level privilege doesn't serve that goal, more the opposite.\n>\n> > I agree.\n>\n> >> Still, if we can compromise by making this part of DB \"CREATE\" privilege\n> >> for the time being, I'm willing to take that compromise. It's certainly\n> >> better than failing to get rid of pg_pltemplate.\n>\n> > Doesn't that have exactly the issue you describe above?\n> > bob=> grant create on database bob to fred;\n> > GRANT\n>\n> Either of them do, in that a DB owner can always grant his whole role;\n> \"grant bob to fred\" will give fred install privileges (in bob's DBs)\n> regardless of which of these choices we adopt. And that was true before\n> (with respect to trusted PLs), too. Attaching the ability to the CREATE\n> bit would at least allow DB owners to be a bit more selective about how\n> they give it out.\n\n\nRight.\n\nThe reason I'm happier about doing this with CREATE than inventing\n> a separate INSTALL bit is that once we do the latter, we're more or\n> less bound to keep supporting that ability forever. If we extend\n> the definition of CREATE in v13, and then narrow it again in some\n> future release, that seems less likely to cause problems than taking\n> away a named privilege bit would do.\n\n\nI would like to segregate these privileges more than just “install” vs\n“other stuff” in the future anyway, so mixing it with the existing CREATE\nisn’t that big of a deal in my view.\n\nOn the other hand, there's the point that lots of people have probably\n> given out schema-CREATE privilege to users whom they wouldn't necessarily\n> wish to trust with INSTALL privilege. Schema-CREATE is a pretty harmless\n> privilege, INSTALL much less so.\n\n\nCREATE doesn’t just control the ability to create schemas these days- it\nwas extended to cover publications also not that long ago. We never said\nwe wouldn’t extend CREATE to cover more objects and we’ve already extended\nit recently, without anyone being up in arms about it that I can recall, so\nthis doesn’t feel like a huge issue or concern to me. Note that, again,\nthese are trusted extensions which means, in their regular install, they\nshouldn’t be able to “break outside the box” any more than a plpgsql\nfunction is able to.\n\nThanks,\n\nStephen\n\nGreetings,On Tue, Jan 28, 2020 at 16:17 Tom Lane <tgl@sss.pgh.pa.us> wrote:Robert Haas <robertmhaas@gmail.com> writes:\n> On Tue, Jan 28, 2020 at 3:52 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I continue to think that allowing DB owners to decide this is, if not\n>> fundamentally the wrong thing, at least not a feature that anybody has\n>> asked for in the past.  The feature *I* want in this area is for the\n>> superuser to be able to decide who's got install privilege.  Making\n>> it a DB-level privilege doesn't serve that goal, more the opposite.\n\n> I agree.\n\n>> Still, if we can compromise by making this part of DB \"CREATE\" privilege\n>> for the time being, I'm willing to take that compromise.  It's certainly\n>> better than failing to get rid of pg_pltemplate.\n\n> Doesn't that have exactly the issue you describe above?\n> bob=> grant create on database bob to fred;\n> GRANT\n\nEither of them do, in that a DB owner can always grant his whole role;\n\"grant bob to fred\" will give fred install privileges (in bob's DBs)\nregardless of which of these choices we adopt.  And that was true before\n(with respect to trusted PLs), too.  Attaching the ability to the CREATE\nbit would at least allow DB owners to be a bit more selective about how\nthey give it out.Right.\nThe reason I'm happier about doing this with CREATE than inventing\na separate INSTALL bit is that once we do the latter, we're more or\nless bound to keep supporting that ability forever.  If we extend\nthe definition of CREATE in v13, and then narrow it again in some\nfuture release, that seems less likely to cause problems than taking\naway a named privilege bit would do.I would like to segregate these privileges more than just “install” vs “other stuff” in the future anyway, so mixing it with the existing CREATE isn’t that big of a deal in my view. \nOn the other hand, there's the point that lots of people have probably\ngiven out schema-CREATE privilege to users whom they wouldn't necessarily\nwish to trust with INSTALL privilege.  Schema-CREATE is a pretty harmless\nprivilege, INSTALL much less so.CREATE doesn’t just control the ability to create schemas these days- it was extended to cover publications also not that long ago.  We never said we wouldn’t extend CREATE to cover more objects and we’ve already extended it recently, without anyone being up in arms about it that I can recall, so this doesn’t feel like a huge issue or concern to me.  Note that, again, these are trusted extensions which means, in their regular install, they shouldn’t be able to “break outside the box” any more than a plpgsql function is able to.Thanks,Stephen", "msg_date": "Tue, 28 Jan 2020 16:58:32 -0500", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> On Tue, Jan 28, 2020 at 16:17 Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> On the other hand, there's the point that lots of people have probably\n>> given out schema-CREATE privilege to users whom they wouldn't necessarily\n>> wish to trust with INSTALL privilege. Schema-CREATE is a pretty harmless\n>> privilege, INSTALL much less so.\n\n> CREATE doesn’t just control the ability to create schemas these days- it\n> was extended to cover publications also not that long ago.\n\nOh really ... hm, that does make it a much bigger deal than I was\nthinking. Given that, I don't think there's any huge objection to\nattaching this to CREATE, at least till we get around to a more\nsignificant redesign.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 28 Jan 2020 17:35:00 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" }, { "msg_contents": "I wrote:\n> Stephen Frost <sfrost@snowman.net> writes:\n>> On Tue, Jan 28, 2020 at 16:17 Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>>> On the other hand, there's the point that lots of people have probably\n>>> given out schema-CREATE privilege to users whom they wouldn't necessarily\n>>> wish to trust with INSTALL privilege. Schema-CREATE is a pretty harmless\n>>> privilege, INSTALL much less so.\n\n>> CREATE doesn't just control the ability to create schemas these days- it\n>> was extended to cover publications also not that long ago.\n\n> Oh really ... hm, that does make it a much bigger deal than I was\n> thinking. Given that, I don't think there's any huge objection to\n> attaching this to CREATE, at least till we get around to a more\n> significant redesign.\n\nHere's a v5 that drops the new predefined role and allows\ntrusted-extension installation when you have CREATE on the current\ndatabase. There's no other changes except a bit of documentation\nwordsmithing.\n\nBarring further complaints, I'm going to push this fairly soon.\n\n\t\t\tregards, tom lane", "msg_date": "Wed, 29 Jan 2020 13:19:25 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: Removing pg_pltemplate and creating \"trustable\" extensions" } ]
[ { "msg_contents": "Hello,\n\nAfter rereading some old papers recently, I wanted to share some\nthoughts about XPRS and modern PostgreSQL. XPRS stood for \"eXtended\nPostgres on RAID and Sprite\", and was a research project done nearly\nthree decades ago at Berkeley by the POSTGRES group working with\noperating system researchers, on a shared memory machine with a lot of\nCPUs for the time (12).\n\nAs far as I can tell (and if anyone knows how to find out, I'd love to\nknow), the parallel query parts of the XPRS system described in\nvarious writings by Wei Hong and Michael Stonebraker are actually\npresent in the POSTGRES 4.2 tarball and were removed in Postgres95.\nEvidence: 4.2's parallel code is all wrapped in #ifdef sequent, and we\nknow that XPRS ran on a Sequent Symmetry; the parallel hash join\nalgorithm matches the description given in Hong's doctoral thesis; the\npage and range based parallel scans seen in various places also seem\nto match.\n\nHong's thesis covers a lot of material and I certainly haven't\nunderstood all of it, but basically it's about how to share CPU, IO\nbandwidth and memory out fairly and dynamically at execution time so\nyou're using the whole system efficiently. Facets of this problem\nobviously keep coming up on this mailing list (see practically any\ndiscussion of parallel degree, admission control, prefetch or\nwork_mem, all of which we punt on by deferring to user supplied GUCs\nand scan size-based heuristics).\n\nHere are three things I wanted to highlight from Hong's 1991 paper[1]\n(later writings elaborate greatly but this one is short and much\neasier to read than the thesis and sets the scene):\n\n1. \"The overall performance goal of a multiprocessor database system\nis to obtain increased throughput as well as reduced response time in\na multiuser environment. The objective function that XPRS uses for\nquery optimization is a combination of resource consumption and\nresponse time as follows: cost = resource_consumption + w *\nresponse_time, where w is a system-specific weighting factor.\"\n\n2. The \"Buffer-Size-Independent Hypothesis\" (here meaning work_mem):\n\"The choice of the best sequential plan is insensitive to the amount\nof buffer space available as long as the buffer size is above the hash\njoin threshold\" (with a caveat about localised special cases that can\nbe handled by choosing alternative subplans at runtime).\n\n3. The \"Two-Phase Hypothesis\": \"The best parallel plan is a\nparallelization of the best sequential plan.\"\n\nI read all of that a while back while working on bits of parallel\nquery machinery (though I only realised after the fact that I'd\nimplemented parallel hash the same way as Hong did 27 years earlier,\nthat is, shared no-partition, which is now apparently back in vogue\ndue to the recent ubiquity of high core count shared memory systems,\nso that every server looks a bit like a Sequent Symmetry; for example\nOracle is rumoured to have a \"parallel shared hash join\" like ours in\nthe pipeline). I didn't understand the context or importance of XPRS,\nthough, until I read this bit of Hellerstein's \"Looking Back at\nPostgres\"[2]:\n\n\"In principle, parallelism “blows up” the plan space for a query\noptimizer by making it multiply the traditional choices made during\nquery optimization (data access, join algorithms, join orders) against\nall possible ways of parallelizing each choice. The basic idea of what\nStonebraker called “The Wei Hong Optimizer” was to cut the problem in\ntwo: run a traditional single-node query optimizer in the style of\nSystem R, and then “parallelize” the resulting single-node query plan\nby scheduling the degree of parallelism and placement of each operator\nbased on data layouts and system configuration. This approach is\nheuristic, but it makes parallelism an additive cost to traditional\nquery optimization, rather than a multiplicative cost.\n\nAlthough “The Wei Hong Optimizer” was designed in the context of\nPostgres, it became the standard approach for many of the parallel\nquery optimizers in industry.\"\n\nI don't know what to think about the buffer-size-independent\nhypothesis, but the two-phase hypothesis and the claim that is is the\nstandard approach caught my attention. Firstly, I don't think the\nhypothesis holds on our system currently, because (for example) we\nlack parallel merge joins and sorts, so you couldn't parallelise such\nserial plans, and yet we'd already have thrown away a hash join based\nplan that would be vastly better in parallel. That might be just an\nimplementation completeness problem. I wonder what fundamental\nproblems lurk here. (Perhaps the non-availability of globally unique\npartial paths?) Anyway, AFAICS we do the exact thing Hong wanted to\navoid: we plan parallel queries as extra paths at planning time. We\ndon't really suffer too much of a planning explosion though, because\nwe don't consider different parallel degrees. If we did, because our\ncost model doesn't include any penalty for resource usage, I suspect\nwe'd always go for the maximum number of workers because they're\n'free', which creates a perverse incentive to burn resource (CPU +\ncopies of work_mem). Those are all problems Hong solved with\nexecution time resource allocation, as part of a bigger picture.\n\nI have no idea what to do about any of this but thought that was an\ninteresting bit of our project's history worth sharing. It's really\nhumbling to read these old papers. I wonder if we're missing a chance\nto stand on the shoulders of giants.\n\n[1] http://db.cs.berkeley.edu/jmh/tmp/pdis91-xprs.pdf\n[2] https://arxiv.org/pdf/1901.01973.pdf\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Thu, 22 Aug 2019 11:41:45 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "XPRS" }, { "msg_contents": "On Thu, Aug 22, 2019 at 11:41:45AM +1200, Thomas Munro wrote:\n>Hello,\n>\n>After rereading some old papers recently, I wanted to share some\n>thoughts about XPRS and modern PostgreSQL. XPRS stood for \"eXtended\n>Postgres on RAID and Sprite\", and was a research project done nearly\n>three decades ago at Berkeley by the POSTGRES group working with\n>operating system researchers, on a shared memory machine with a lot of\n>CPUs for the time (12).\n>\n>As far as I can tell (and if anyone knows how to find out, I'd love to\n>know), the parallel query parts of the XPRS system described in\n>various writings by Wei Hong and Michael Stonebraker are actually\n>present in the POSTGRES 4.2 tarball and were removed in Postgres95.\n>Evidence: 4.2's parallel code is all wrapped in #ifdef sequent, and we\n>know that XPRS ran on a Sequent Symmetry; the parallel hash join\n>algorithm matches the description given in Hong's doctoral thesis; the\n>page and range based parallel scans seen in various places also seem\n>to match.\n>\n>Hong's thesis covers a lot of material and I certainly haven't\n>understood all of it, but basically it's about how to share CPU, IO\n>bandwidth and memory out fairly and dynamically at execution time so\n>you're using the whole system efficiently. Facets of this problem\n>obviously keep coming up on this mailing list (see practically any\n>discussion of parallel degree, admission control, prefetch or\n>work_mem, all of which we punt on by deferring to user supplied GUCs\n>and scan size-based heuristics).\n>\n>Here are three things I wanted to highlight from Hong's 1991 paper[1]\n>(later writings elaborate greatly but this one is short and much\n>easier to read than the thesis and sets the scene):\n>\n>1. \"The overall performance goal of a multiprocessor database system\n>is to obtain increased throughput as well as reduced response time in\n>a multiuser environment. The objective function that XPRS uses for\n>query optimization is a combination of resource consumption and\n>response time as follows: cost = resource_consumption + w *\n>response_time, where w is a system-specific weighting factor.\"\n>\n>2. The \"Buffer-Size-Independent Hypothesis\" (here meaning work_mem):\n>\"The choice of the best sequential plan is insensitive to the amount\n>of buffer space available as long as the buffer size is above the hash\n>join threshold\" (with a caveat about localised special cases that can\n>be handled by choosing alternative subplans at runtime).\n>\n>3. The \"Two-Phase Hypothesis\": \"The best parallel plan is a\n>parallelization of the best sequential plan.\"\n>\n>I read all of that a while back while working on bits of parallel\n>query machinery (though I only realised after the fact that I'd\n>implemented parallel hash the same way as Hong did 27 years earlier,\n>that is, shared no-partition, which is now apparently back in vogue\n>due to the recent ubiquity of high core count shared memory systems,\n>so that every server looks a bit like a Sequent Symmetry; for example\n>Oracle is rumoured to have a \"parallel shared hash join\" like ours in\n>the pipeline). I didn't understand the context or importance of XPRS,\n>though, until I read this bit of Hellerstein's \"Looking Back at\n>Postgres\"[2]:\n>\n>\"In principle, parallelism “blows up” the plan space for a query\n>optimizer by making it multiply the traditional choices made during\n>query optimization (data access, join algorithms, join orders) against\n>all possible ways of parallelizing each choice. The basic idea of what\n>Stonebraker called “The Wei Hong Optimizer” was to cut the problem in\n>two: run a traditional single-node query optimizer in the style of\n>System R, and then “parallelize” the resulting single-node query plan\n>by scheduling the degree of parallelism and placement of each operator\n>based on data layouts and system configuration. This approach is\n>heuristic, but it makes parallelism an additive cost to traditional\n>query optimization, rather than a multiplicative cost.\n>\n\nI think this relies on a huge assumption that all steps in any sequential\nplan can be parallelized. Which certainly is not true for PostgreSQL - as\nyou point out later on the join example. That means the optimal join order\nmay be different for parallel plan, and so on.\n\nThe other thing is that \"parallelizations\" of different sequential plans\nmay have different requirements for resources (say, work_mem), so I'd\nexpect cases when a parallel version of a \"worse\" sequential plan may end\nup being superior thanks to allowing larger number of workers.\n\n>Although “The Wei Hong Optimizer” was designed in the context of\n>Postgres, it became the standard approach for many of the parallel\n>query optimizers in industry.\"\n>\n\nI assume this quote is from 30 years ago. I wonder if the claim is still\ntrue, on current hardware (including e.g. distributed databases).\n\n>I don't know what to think about the buffer-size-independent\n>hypothesis, but the two-phase hypothesis and the claim that is is the\n>standard approach caught my attention. Firstly, I don't think the\n>hypothesis holds on our system currently, because (for example) we\n>lack parallel merge joins and sorts, so you couldn't parallelise such\n>serial plans, and yet we'd already have thrown away a hash join based\n>plan that would be vastly better in parallel. That might be just an\n>implementation completeness problem. I wonder what fundamental\n>problems lurk here. (Perhaps the non-availability of globally unique\n>partial paths?) Anyway, AFAICS we do the exact thing Hong wanted to\n>avoid: we plan parallel queries as extra paths at planning time. We\n>don't really suffer too much of a planning explosion though, because\n>we don't consider different parallel degrees. If we did, because our\n>cost model doesn't include any penalty for resource usage, I suspect\n>we'd always go for the maximum number of workers because they're\n>'free', which creates a perverse incentive to burn resource (CPU +\n>copies of work_mem). Those are all problems Hong solved with\n>execution time resource allocation, as part of a bigger picture.\n>\n\nI don't know. I'd guess the hardware changed quite a bit, so maybe some of\nthe assumptions from the paper are too simplistic nowadays? Consider for\nexample the memory hierarchy - 30 years ago the amount of on-CPU cache was\nminiscule, while now we have L1/L2/L3 caches that are tens of megabytes.\nIt's usually much faster to do sorts that fit into L3, for example.\n\nFWIW I think we'll have to do something about resource acquisition, sooner\nor later. It was always quite annoying that we don't really consider\nmemory consumption of the query as a whole during planning, and parallel\nquery made it a bit more painful.\n\n>I have no idea what to do about any of this but thought that was an\n>interesting bit of our project's history worth sharing. It's really\n>humbling to read these old papers. I wonder if we're missing a chance\n>to stand on the shoulders of giants.\n>\n\nThanks, I think it's always useful / interesting to look at papers like\nthis. I don't know if we can use the stuff described in those papers\ndirectly, but maybe we can build on those ideas and see which of the\nassumptions are no longer true.\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Fri, 23 Aug 2019 17:19:00 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: XPRS" }, { "msg_contents": "On Sat, Aug 24, 2019 at 3:19 AM Tomas Vondra\n<tomas.vondra@2ndquadrant.com> wrote:\n> > Although “The Wei Hong Optimizer” was designed in the context of\n> > Postgres, it became the standard approach for many of the parallel\n> > query optimizers in industry.\"\n>\n> I assume this quote is from 30 years ago. I wonder if the claim is still\n> true, on current hardware (including e.g. distributed databases).\n\nThe quote is from 2018, and appears in the article I linked (it's a\nchapter from the book Making Databases Work: The Wisdom of Michael\nStonebraker), but I'm not sure which systems it's referring to.\n\nSpeculation: Many other systems have what we call parallel-oblivious\noperators only, and then insert various exchange operators to make a\nparallel plan. That is, they don't necessarily have a direct\nequivalent of our \"Parallel Sequential Scan\", \"Parallel Index Scan\",\n\"Parallel Foreign Scan\": they just use their regular scans, possibly\nwith the addition of some kind of \"Parallel Scatter\" node (that's my\nmade up name, it's the opposite of Gather, called various things like\n\"page supplier\" or \"block iterator\") or \"Parallel Repartition\"\ninserted in the right places. Perhaps they create a serial plan\nfirst, and then try to parallelise it by inserting various parallel\noperators and then recomputing the costs? Rather than considering the\nseparate paths in the first phase of the optimiser, as we do. The\ncases where Hong's best-parallel-plan hypothesis isn't true for us now\nmight go away if we had Parallel Repartition, so that each 'stream'\nwould be the complete set of tuples for some known partition.\n\nTo be clear, I'm not suggesting we do that necessarily, just pointing\nout some interesting claims about ancient POSTGRES wisdom, in a highly\nspeculative water cooler thread. Actually, this isn't the first time\nit's occurred to me that elements of our design were falling out of\nthe order that we chose to implement things in. Another example is\nthe \"Shared Hash\" that I had in an early version of my work on\nParallel Hash Join, where just one process would run a parallel-safe\nbut non-parallel-oblivious plan to build a shared hash table while\nother workers twiddled their thumbs; I dropped it because our cost\nmodel has no penalty for running N copies of the same plan rather than\njust one so there was no way to pick that plan, and that's because we\ndon't have a cost model like Hong's that considers resource usage too.\nAnother more speculative observation: maybe no-partition/shared\nParallel Hash Join is only obvious if you already have the general\nconcept of parallel-aware executor nodes. AFAIK Robert and Amit\ninvented those to be able to coordinate parallel scans between\nprocesses, where thread-based systems might be able to share a single\nscan state somehow under a Scatter-like operator. If you had threads,\nyou might not need that concept that allows arbitrary executor nodes\nto communicate with each other between workers, and then it might be\nmore obvious and natural to use repartitioning for parallelising hash\njoins.\n\n> FWIW I think we'll have to do something about resource acquisition, sooner\n> or later. It was always quite annoying that we don't really consider\n> memory consumption of the query as a whole during planning, and parallel\n> query made it a bit more painful.\n\nAgreed.\n\nHere's an approach I have been wondering about to cap total executor\nmemory usage, which is a much more down-to-Earth idea than any of the\nabove space cadet planner problems. Let's start at the other end of\nthe problem, by introducing admission control and memory quotas. That\nis, keep using work_mem with its current per-node-copy meaning at\nplanning time, for now, and then:\n\n1. Compute the peak amount of memory each plan thinks it will need.\nInitially that could be done by by summing estimates from all nodes\nand considering workers. A later refinement could deal with nodes\nthat give back memory early, if we get around to doing that. The\nestimate could be shown by EXPLAIN. (Some details to work out: worst\ncase vs expected etc.)\n\n2. Introduce a new GUC global_work_mem, which limits the total plan\nthat are allowed to run concurrently, according to their memory\nestimates. Introduce a shared memory counter of currently allocated\nquota.\n\n3. Introduce a new GUC session_work_mem, which is the amount of quota\nthat every session tries to acquire when it connects or perhaps first\nruns a query, and that it won't give back until the end of the\nsession. Or perhaps they acquire less than that if they need less,\nbut that's the amount they never give back once they've got that much.\nThe idea is to allow queries with estimates under that limit, for\nexample high frequency OLTP queries, to avoid any extra communication\noverhead from this scheme.\n\n4. To run queries that have estimates higher than the session's\ncurrent allocated quota, the session must acquire more quota for the\nduration of the query. If it can't be acquired right now without\nexceeding global_work_mem, it has to join a queue and wait. A\nrefinement could be that you are allowed to run with fewer workers\nthan planned to reduce the requirement.\n\n5. While executing, executor nodes could opportunistically ask for\nmore quota than was planned for, up to some limit, to avoid having to\nspill to disk. If the request is unsuccessful, that's OK, they can\ndeal with that.\n\n6. So long as we have nodes that have no escape mechanism in certain\nedge cases (hash aggregates and joins with bad stats and extreme\nskew), you could perhaps have the option of raising an error or\nforcing the total to exceed global_work_mem temporarily with a warning\n(which would at least prevent other large queries from running and\nmaking it worse).\n\n7. Regular heap memory and DSM memory should be counted together,\nsince it makes no difference to the operating system, it's all memory\nand we should count it against the same quota. You'd probably want to\nconsider hidden allocator fragmentation too, as well as other hidden\noverheads, to get decent accuracy.\n\nThis is sort of fudging together of ideas from conversations with\nKevin Grittner (who talked about admission control a few years back),\nPeter Geoghegan (who mentioned opportunistically asking for more), and\nthings I've heard of on SQL Server (\"memory grants\"). I think it\nwould provide some relief from the problems we see today: it's hard to\nset work_mem so that you never get OOM but you can still use a decent\namount of your precious memory, especially with mixed parallel and\nnon-parallel query workloads thanks to our current\nwork_mem-multiplying design.\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Mon, 2 Sep 2019 14:19:15 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: XPRS" }, { "msg_contents": "On Mon, Sep 02, 2019 at 02:19:15PM +1200, Thomas Munro wrote:\n>On Sat, Aug 24, 2019 at 3:19 AM Tomas Vondra\n><tomas.vondra@2ndquadrant.com> wrote:\n>> > Although “The Wei Hong Optimizer” was designed in the context of\n>> > Postgres, it became the standard approach for many of the parallel\n>> > query optimizers in industry.\"\n>>\n>> I assume this quote is from 30 years ago. I wonder if the claim is still\n>> true, on current hardware (including e.g. distributed databases).\n>\n>The quote is from 2018, and appears in the article I linked (it's a\n>chapter from the book Making Databases Work: The Wisdom of Michael\n>Stonebraker), but I'm not sure which systems it's referring to.\n>\n\nHmm, that's unfortunate - it'd be quite interesting to know which\ndatabases it's referring to. I suspect no optimizer is ideal in this\nregard, i.e. each database has some \"gaps\" where some nodes don't have a\nstraightforward parallel version.\n\n>Speculation: Many other systems have what we call parallel-oblivious\n>operators only, and then insert various exchange operators to make a\n>parallel plan. That is, they don't necessarily have a direct\n>equivalent of our \"Parallel Sequential Scan\", \"Parallel Index Scan\",\n>\"Parallel Foreign Scan\": they just use their regular scans, possibly\n>with the addition of some kind of \"Parallel Scatter\" node (that's my\n>made up name, it's the opposite of Gather, called various things like\n>\"page supplier\" or \"block iterator\") or \"Parallel Repartition\"\n>inserted in the right places. Perhaps they create a serial plan\n>first, and then try to parallelise it by inserting various parallel\n>operators and then recomputing the costs? Rather than considering the\n>separate paths in the first phase of the optimiser, as we do. The\n>cases where Hong's best-parallel-plan hypothesis isn't true for us now\n>might go away if we had Parallel Repartition, so that each 'stream'\n>would be the complete set of tuples for some known partition.\n>\n\nI don't know. It kinda reminds me planning with distributed databases,\nwhich also need exchange data between nodes in various cases - say, when\njoining two relations distributed in different ways. The redistribution is\nhowever pretty costly (network I/O, bandwidth etc.) to the extent that\nit's often much better to pick a very different join to reduce the amount\nof data to exchange, or eliminate the redistribution altogether. For\nparallelism the costs are much lower, of course, but I don't think we can\njust ignore those.\n\nFWIW it's not clear to me why the cost would need to be recomputed after\nconstructing the parallel version of the plan? My understanding is that\nthe idea is to do cost-based planning for the serial plan, and then just\n\"mechanically\" construct a parallel plan. Although, maybe there could be\nmultiple parallel alternatives ...\n\n>To be clear, I'm not suggesting we do that necessarily, just pointing\n>out some interesting claims about ancient POSTGRES wisdom, in a highly\n>speculative water cooler thread. Actually, this isn't the first time\n>it's occurred to me that elements of our design were falling out of\n>the order that we chose to implement things in. Another example is\n>the \"Shared Hash\" that I had in an early version of my work on\n>Parallel Hash Join, where just one process would run a parallel-safe\n>but non-parallel-oblivious plan to build a shared hash table while\n>other workers twiddled their thumbs; I dropped it because our cost\n>model has no penalty for running N copies of the same plan rather than\n>just one so there was no way to pick that plan, and that's because we\n>don't have a cost model like Hong's that considers resource usage too.\n>Another more speculative observation: maybe no-partition/shared\n>Parallel Hash Join is only obvious if you already have the general\n>concept of parallel-aware executor nodes. AFAIK Robert and Amit\n>invented those to be able to coordinate parallel scans between\n>processes, where thread-based systems might be able to share a single\n>scan state somehow under a Scatter-like operator. If you had threads,\n>you might not need that concept that allows arbitrary executor nodes\n>to communicate with each other between workers, and then it might be\n>more obvious and natural to use repartitioning for parallelising hash\n>joins.\n>\n>> FWIW I think we'll have to do something about resource acquisition, sooner\n>> or later. It was always quite annoying that we don't really consider\n>> memory consumption of the query as a whole during planning, and parallel\n>> query made it a bit more painful.\n>\n>Agreed.\n>\n>Here's an approach I have been wondering about to cap total executor\n>memory usage, which is a much more down-to-Earth idea than any of the\n>above space cadet planner problems. Let's start at the other end of\n>the problem, by introducing admission control and memory quotas. That\n>is, keep using work_mem with its current per-node-copy meaning at\n>planning time, for now, and then:\n>\n>1. Compute the peak amount of memory each plan thinks it will need.\n>Initially that could be done by by summing estimates from all nodes\n>and considering workers. A later refinement could deal with nodes\n>that give back memory early, if we get around to doing that. The\n>estimate could be shown by EXPLAIN. (Some details to work out: worst\n>case vs expected etc.)\n>\n>2. Introduce a new GUC global_work_mem, which limits the total plan\n>that are allowed to run concurrently, according to their memory\n>estimates. Introduce a shared memory counter of currently allocated\n>quota.\n>\n>3. Introduce a new GUC session_work_mem, which is the amount of quota\n>that every session tries to acquire when it connects or perhaps first\n>runs a query, and that it won't give back until the end of the\n>session. Or perhaps they acquire less than that if they need less,\n>but that's the amount they never give back once they've got that much.\n>The idea is to allow queries with estimates under that limit, for\n>example high frequency OLTP queries, to avoid any extra communication\n>overhead from this scheme.\n>\n>4. To run queries that have estimates higher than the session's\n>current allocated quota, the session must acquire more quota for the\n>duration of the query. If it can't be acquired right now without\n>exceeding global_work_mem, it has to join a queue and wait. A\n>refinement could be that you are allowed to run with fewer workers\n>than planned to reduce the requirement.\n>\n>5. While executing, executor nodes could opportunistically ask for\n>more quota than was planned for, up to some limit, to avoid having to\n>spill to disk. If the request is unsuccessful, that's OK, they can\n>deal with that.\n>\n>6. So long as we have nodes that have no escape mechanism in certain\n>edge cases (hash aggregates and joins with bad stats and extreme\n>skew), you could perhaps have the option of raising an error or\n>forcing the total to exceed global_work_mem temporarily with a warning\n>(which would at least prevent other large queries from running and\n>making it worse).\n>\n>7. Regular heap memory and DSM memory should be counted together,\n>since it makes no difference to the operating system, it's all memory\n>and we should count it against the same quota. You'd probably want to\n>consider hidden allocator fragmentation too, as well as other hidden\n>overheads, to get decent accuracy.\n>\n>This is sort of fudging together of ideas from conversations with\n>Kevin Grittner (who talked about admission control a few years back),\n>Peter Geoghegan (who mentioned opportunistically asking for more), and\n>things I've heard of on SQL Server (\"memory grants\"). I think it\n>would provide some relief from the problems we see today: it's hard to\n>set work_mem so that you never get OOM but you can still use a decent\n>amount of your precious memory, especially with mixed parallel and\n>non-parallel query workloads thanks to our current\n>work_mem-multiplying design.\n>\n\nI think this is probably the simplest and most realistic first step.\n\nWhenever I was thinking about memory acquisition, I've assumed we'd\nmonitor how much memory the plan is expected to use while we're\nconstructing it. My main problem was what to do when we reach the\nper-query limit - whether to (a) simply reject the plan, (b) go back and\nsee if we can replan with lower work_mem (but how much and for which\nnodes?), or (c) just continue.\n\nThe proposed plan deals with this by not limiting the per-query (or rather\nper-session) budget directly, and instead requesting requesting additional\nbudget. Which is nice.\n\nI suspect we should also keep an additional plan that is expected to meet\nthe session_work_mem limit, aside from the regular cheapest plan, and use\nit if it's not much worse. Imagine you have a plan with cost 1000 that\nneeds (global_work_mem/2 + 1kB) memory, essentially serializing executions\nof this query. And then there's an alternative plan with cost 1100 that\ncan run with session_work_mem. It seems better to just accept the second\nplan, because it won't need to wait.\n\nAnother challenge with work_mem is that anyone can modify it arbitrarily,\ni.e. a user can do\n\n SET work_mem = '1TB';\n\nand use as much memory as they wist, or even crash the system. I wonder if\nwe could define the new GUCs (session_work_mem and global_work_mem) in a\nway to prevent this. We probably don't want to make them PGC_POSTMASTER\n(it seems useful to allow overriding them in ALTER USER/DATABASE), but I\ndon't think we have a good way to do that at the moment. Any ideas in this\ndirection?\n\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Mon, 2 Sep 2019 19:20:30 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: XPRS" }, { "msg_contents": "On Tue, Sep 3, 2019 at 5:20 AM Tomas Vondra\n<tomas.vondra@2ndquadrant.com> wrote:\n> FWIW it's not clear to me why the cost would need to be recomputed after\n> constructing the parallel version of the plan? My understanding is that\n> the idea is to do cost-based planning for the serial plan, and then just\n> \"mechanically\" construct a parallel plan. Although, maybe there could be\n> multiple parallel alternatives ...\n\nPresumably you still need to choose between the serial and parallel\nplans by comparing costs. You lose some by adding exchange operators,\nbut you win some by dividing cardinality estimates.\n\n> >This is sort of fudging together of ideas from conversations with\n> >Kevin Grittner (who talked about admission control a few years back),\n> >Peter Geoghegan (who mentioned opportunistically asking for more), and\n> >things I've heard of on SQL Server (\"memory grants\"). I think it\n> >would provide some relief from the problems we see today: it's hard to\n> >set work_mem so that you never get OOM but you can still use a decent\n> >amount of your precious memory, especially with mixed parallel and\n> >non-parallel query workloads thanks to our current\n> >work_mem-multiplying design.\n>\n> I think this is probably the simplest and most realistic first step.\n>\n> Whenever I was thinking about memory acquisition, I've assumed we'd\n> monitor how much memory the plan is expected to use while we're\n> constructing it. My main problem was what to do when we reach the\n> per-query limit - whether to (a) simply reject the plan, (b) go back and\n> see if we can replan with lower work_mem (but how much and for which\n> nodes?), or (c) just continue.\n\nYeah, it's all quite tricky and circular. But I'm pretty sure that we\nneed caps at execution time, anyway, so I think it's OK to start at\nthat end of the problem and then later try to improve the way the\nplanner.\n\n> The proposed plan deals with this by not limiting the per-query (or rather\n> per-session) budget directly, and instead requesting requesting additional\n> budget. Which is nice.\n>\n> I suspect we should also keep an additional plan that is expected to meet\n> the session_work_mem limit, aside from the regular cheapest plan, and use\n> it if it's not much worse. Imagine you have a plan with cost 1000 that\n> needs (global_work_mem/2 + 1kB) memory, essentially serializing executions\n> of this query. And then there's an alternative plan with cost 1100 that\n> can run with session_work_mem. It seems better to just accept the second\n> plan, because it won't need to wait.\n\nHmm. I wonder if it's worth it. You could also just replan as you\nsaid, but I'm wondering if just rejecting the query would be OK.\n\n> Another challenge with work_mem is that anyone can modify it arbitrarily,\n> i.e. a user can do\n>\n> SET work_mem = '1TB';\n>\n> and use as much memory as they wist, or even crash the system. I wonder if\n> we could define the new GUCs (session_work_mem and global_work_mem) in a\n> way to prevent this. We probably don't want to make them PGC_POSTMASTER\n> (it seems useful to allow overriding them in ALTER USER/DATABASE), but I\n> don't think we have a good way to do that at the moment. Any ideas in this\n> direction?\n\nHow about something giving the superuser the following GUCs:\n\nglobal_work_mem = 16GB\nsession_min_work_mem = 0.5% -- the amount of quota sessions keep, for\nfast small queries\nsession_max_work_mem = 20% -- the maximum quota any one session is allowed\nsession_extra_work_mem = 5% -- opportunistic execution-time boost\n\nUsers are free to plan queries with work_mem = 1TB, and if you do that\nand it estimates that it wants 512GB, it will be rejected if you try\nto execute it because it exceeds session_max_work_mem, with a hint\ntelling you to turn down work_mem. Otherwise it either runs or joins\nthe queue if it can't get the quota it needs immediately.\n\nEventually we could try to figure out how to set work_mem to automatic\n(I don't want to propose a concrete rule, but maybe something based on\nsession_max_work_mem / njoins, with various fudge factors, and some\naccounting for parallel workers; it's probably good to low-ball it and\nrely on session_extra_work_mem).\n\nYeah, I think you'd want to be able to set session_XXX on databases\nand roles so that you can say your regular users can't eat more than\n10% of memory each, but a big reporting thing is allowed more.\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Tue, 3 Sep 2019 11:04:43 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: XPRS" }, { "msg_contents": "On Tue, Sep 03, 2019 at 11:04:43AM +1200, Thomas Munro wrote:\n>On Tue, Sep 3, 2019 at 5:20 AM Tomas Vondra\n><tomas.vondra@2ndquadrant.com> wrote:\n>> FWIW it's not clear to me why the cost would need to be recomputed after\n>> constructing the parallel version of the plan? My understanding is that\n>> the idea is to do cost-based planning for the serial plan, and then just\n>> \"mechanically\" construct a parallel plan. Although, maybe there could be\n>> multiple parallel alternatives ...\n>\n>Presumably you still need to choose between the serial and parallel\n>plans by comparing costs. You lose some by adding exchange operators,\n>but you win some by dividing cardinality estimates.\n>\n\nOh, right. Silly me.\n\n>> >This is sort of fudging together of ideas from conversations with\n>> >Kevin Grittner (who talked about admission control a few years back),\n>> >Peter Geoghegan (who mentioned opportunistically asking for more), and\n>> >things I've heard of on SQL Server (\"memory grants\"). I think it\n>> >would provide some relief from the problems we see today: it's hard to\n>> >set work_mem so that you never get OOM but you can still use a decent\n>> >amount of your precious memory, especially with mixed parallel and\n>> >non-parallel query workloads thanks to our current\n>> >work_mem-multiplying design.\n>>\n>> I think this is probably the simplest and most realistic first step.\n>>\n>> Whenever I was thinking about memory acquisition, I've assumed we'd\n>> monitor how much memory the plan is expected to use while we're\n>> constructing it. My main problem was what to do when we reach the\n>> per-query limit - whether to (a) simply reject the plan, (b) go back and\n>> see if we can replan with lower work_mem (but how much and for which\n>> nodes?), or (c) just continue.\n>\n>Yeah, it's all quite tricky and circular. But I'm pretty sure that we\n>need caps at execution time, anyway, so I think it's OK to start at\n>that end of the problem and then later try to improve the way the\n>planner.\n>\n\nTrue.\n\n>> The proposed plan deals with this by not limiting the per-query (or rather\n>> per-session) budget directly, and instead requesting requesting additional\n>> budget. Which is nice.\n>>\n>> I suspect we should also keep an additional plan that is expected to meet\n>> the session_work_mem limit, aside from the regular cheapest plan, and use\n>> it if it's not much worse. Imagine you have a plan with cost 1000 that\n>> needs (global_work_mem/2 + 1kB) memory, essentially serializing executions\n>> of this query. And then there's an alternative plan with cost 1100 that\n>> can run with session_work_mem. It seems better to just accept the second\n>> plan, because it won't need to wait.\n>\n>Hmm. I wonder if it's worth it. You could also just replan as you\n>said, but I'm wondering if just rejecting the query would be OK.\n>\n\nI think we should not reject queries unnecessarily, if there's a workable\nexecution plan. It's just another optimization criteria, and erroring out\nright after planning is essentially \"can't find a plan\". But when there is\na plan that we could use, that seems like a bad idea. \n\n>> Another challenge with work_mem is that anyone can modify it arbitrarily,\n>> i.e. a user can do\n>>\n>> SET work_mem = '1TB';\n>>\n>> and use as much memory as they wist, or even crash the system. I wonder if\n>> we could define the new GUCs (session_work_mem and global_work_mem) in a\n>> way to prevent this. We probably don't want to make them PGC_POSTMASTER\n>> (it seems useful to allow overriding them in ALTER USER/DATABASE), but I\n>> don't think we have a good way to do that at the moment. Any ideas in this\n>> direction?\n>\n>How about something giving the superuser the following GUCs:\n>\n>global_work_mem = 16GB\n>session_min_work_mem = 0.5% -- the amount of quota sessions keep, for\n>fast small queries\n>session_max_work_mem = 20% -- the maximum quota any one session is allowed\n>session_extra_work_mem = 5% -- opportunistic execution-time boost\n>\n>Users are free to plan queries with work_mem = 1TB, and if you do that\n>and it estimates that it wants 512GB, it will be rejected if you try\n>to execute it because it exceeds session_max_work_mem, with a hint\n>telling you to turn down work_mem. Otherwise it either runs or joins\n>the queue if it can't get the quota it needs immediately.\n>\n\nSeems reasonable, certainly for v1. I'd keep it as simple as possible.\n\n>Eventually we could try to figure out how to set work_mem to automatic\n>(I don't want to propose a concrete rule, but maybe something based on\n>session_max_work_mem / njoins, with various fudge factors, and some\n>accounting for parallel workers; it's probably good to low-ball it and\n>rely on session_extra_work_mem).\n>\n\nHmm, so you'd tweak work_mem for individual queries? Not sure that's\nsomething I'd do at this point - it may seem simple, but I think it's\nactually way harder to get right.\n\nFor example let's say you have two views that are planned nicely, then you\njoin then and suddenly the plan is much worse because the actual work_mem\ngot much lower suddenly. That's not great.\n\nOf course, if it's just optional behavior, and the current with explicit\nwork_mem value is the default, then this is not an issue.\n\nAnyway, I'd focus on MVP doing the bare minimum with simply enforcing a\nsession limit, and leave this for the future.\n\n>Yeah, I think you'd want to be able to set session_XXX on databases\n>and roles so that you can say your regular users can't eat more than\n>10% of memory each, but a big reporting thing is allowed more.\n>\n\nYeah, something like that.\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Tue, 3 Sep 2019 12:31:05 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: XPRS" } ]
[ { "msg_contents": "Hi,\n\nA comment in tqueue.c says that the bytes return by shm_mq_receive()\n\"had better be sufficiently aligned\", before assigning the pointer to\nhtup.t_data. Then it copies htup and returns the copy (and it did so\nin the earlier version that had all the remapping stuff, too, but\nsometimes it deformed it directly so it really did need to be suitably\naligned in that case IIUC).\n\nGiven that shm_mq.c proudly documents that it avoids copying the data\non the receiving side (unless it has to reconstruct a message that was\nsplit up), and given that it promises that the pointed-to data remains\nvalid until your next call, it seems that it should be safe to return\na pointer to the same HeapTupleData object every time (perhaps a\nmember of the TupleQueueReader struct) and just adjust its t_data and\nt_len members every time, so that the gather node emits tuples\ndirectly from the shared memory queue (and then of course tell the\nslot not to pfree()). Alternatively, if the value returned by\nshm_mq_receive() is not really suitably aligned, then the comment is a\nbit misleading.\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Thu, 22 Aug 2019 12:08:10 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Does TupleQueueReaderNext() really need to copy its result?" }, { "msg_contents": "On Thu, Aug 22, 2019 at 12:08 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> Given that shm_mq.c proudly documents that it avoids copying the data\n> on the receiving side (unless it has to reconstruct a message that was\n> split up), and given that it promises that the pointed-to data remains\n> valid until your next call, it seems that it should be safe to return\n> a pointer to the same HeapTupleData object every time (perhaps a\n> member of the TupleQueueReader struct) and just adjust its t_data and\n> t_len members every time, so that the gather node emits tuples\n> directly from the shared memory queue (and then of course tell the\n> slot not to pfree()). Alternatively, if the value returned by\n> shm_mq_receive() is not really suitably aligned, then the comment is a\n> bit misleading.\n\nCouldn't resist trying this, and it seems to work. Based on the\ncomment \"the buffer size is a multiple of MAXIMUM_ALIGNOF, and each\nread and write is as well\", it should always work (though I wish\nshm_mq_receive_bytes()'s documentation would discuss message alignment\nexplicitly if that's true). On the other hand, I doubt it makes a\ndifference, so this is more of a question: is this the way it was\nsupposed to work?\n\n(It was ~40% faster at shunting a large SELECT * through the queue\nwith asserts enabled, which made me happy for moment, but it was only\nan illusion and not measurable in the noise without asserts).\n\n-- \nThomas Munro\nhttps://enterprisedb.com", "msg_date": "Sat, 24 Aug 2019 14:15:34 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Does TupleQueueReaderNext() really need to copy its result?" }, { "msg_contents": "On Fri, Aug 23, 2019 at 10:22 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> Couldn't resist trying this, and it seems to work. Based on the\n> comment \"the buffer size is a multiple of MAXIMUM_ALIGNOF, and each\n> read and write is as well\", it should always work (though I wish\n> shm_mq_receive_bytes()'s documentation would discuss message alignment\n> explicitly if that's true). On the other hand, I doubt it makes a\n> difference, so this is more of a question: is this the way it was\n> supposed to work?\n\nThere's a comment in htup.h which says:\n\n * * Separately allocated tuple: t_data points to a palloc'd chunk that\n * is not adjacent to the HeapTupleData. (This case is deprecated since\n * it's difficult to tell apart from case #1. It should be used only in\n * limited contexts where the code knows that case #1 will never apply.)\n\nI got scared and ran away.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Mon, 26 Aug 2019 14:09:45 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Does TupleQueueReaderNext() really need to copy its result?" }, { "msg_contents": "Hi,\n\nOn 2019-08-26 14:09:45 -0400, Robert Haas wrote:\n> On Fri, Aug 23, 2019 at 10:22 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> > Couldn't resist trying this, and it seems to work. Based on the\n> > comment \"the buffer size is a multiple of MAXIMUM_ALIGNOF, and each\n> > read and write is as well\", it should always work (though I wish\n> > shm_mq_receive_bytes()'s documentation would discuss message alignment\n> > explicitly if that's true). On the other hand, I doubt it makes a\n> > difference, so this is more of a question: is this the way it was\n> > supposed to work?\n> \n> There's a comment in htup.h which says:\n> \n> * * Separately allocated tuple: t_data points to a palloc'd chunk that\n> * is not adjacent to the HeapTupleData. (This case is deprecated since\n> * it's difficult to tell apart from case #1. It should be used only in\n> * limited contexts where the code knows that case #1 will never apply.)\n> \n> I got scared and ran away.\n\nPerhaps this'd could be sidestepped by funneling through MinimalTuples\ninstead of HeapTuples. Afaict that should always be sufficient, because\nall system column accesses ought to happen below (including being\nprojected into a separate column, if needed above). With the added\nbenefit of needing less space, of course.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 26 Aug 2019 11:35:10 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Does TupleQueueReaderNext() really need to copy its result?" }, { "msg_contents": "On Tue, Aug 27, 2019 at 6:35 AM Andres Freund <andres@anarazel.de> wrote:\n> On 2019-08-26 14:09:45 -0400, Robert Haas wrote:\n> > There's a comment in htup.h which says:\n> >\n> > * * Separately allocated tuple: t_data points to a palloc'd chunk that\n> > * is not adjacent to the HeapTupleData. (This case is deprecated since\n> > * it's difficult to tell apart from case #1. It should be used only in\n> > * limited contexts where the code knows that case #1 will never apply.)\n> >\n> > I got scared and ran away.\n>\n> Perhaps this'd could be sidestepped by funneling through MinimalTuples\n> instead of HeapTuples. Afaict that should always be sufficient, because\n> all system column accesses ought to happen below (including being\n> projected into a separate column, if needed above). With the added\n> benefit of needing less space, of course.\n\nI tried that out (attached). That makes various simple tests like\nthis to go 10%+ faster on my development machine:\n\n create table s as select generate_series(1, 50000000)::int i,\n 'hello world' a,\n 'this is a message' b,\n 42 c;\n select pg_prewarm('s');\n set force_parallel_mode = on;\n\n explain analyze select * from s;\n\nPS It looks like the following load of mq_ring_size might be running\na little hot due to false sharing with the atomic counters:\n\n if (mqh->mqh_consume_pending > mq->mq_ring_size / 4)", "msg_date": "Thu, 14 May 2020 22:55:15 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Does TupleQueueReaderNext() really need to copy its result?" }, { "msg_contents": "On Thu, May 14, 2020 at 10:55 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> On Tue, Aug 27, 2019 at 6:35 AM Andres Freund <andres@anarazel.de> wrote:\n> > Perhaps this'd could be sidestepped by funneling through MinimalTuples\n> > instead of HeapTuples. Afaict that should always be sufficient, because\n> > all system column accesses ought to happen below (including being\n> > projected into a separate column, if needed above). With the added\n> > benefit of needing less space, of course.\n\nRight, create_gather[_merge]_plan() does create_plan_recurse(...,\nCP_EXACT_TLIST). Here's a new version that updates the comment there\nto note that this is not merely a good idea but a requirement, due to\nthe MinimalTuple conveyance. (I think there may be another reason the\nsystem columns are projected away even without that, but saying so\nexplicitly and documenting it seems useful either way).\n\n> I tried that out (attached). That makes various simple tests like\n> this to go 10%+ faster on my development machine:\n\nI registered this patch as https://commitfest.postgresql.org/28/2560/\nin case someone would like to review it.", "msg_date": "Wed, 17 Jun 2020 16:47:23 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Does TupleQueueReaderNext() really need to copy its result?" }, { "msg_contents": "Hi Thomas,\n\n+1 to the idea! I ran some experiments on both of your patches.\n\nI could reproduce the speed gain that you saw for a plan with a simple\nparallel sequential scan. However, I got no gain at all for a parallel\nhash join and parallel agg query.\n\n-----------------------------------------------------------------------\n\nselect pg_prewarm('lineitem');\n-- lineitem is 17G. (TPCH scale = 20). shared_buffers = 30G\nexplain analyze select * from lineitem;\n\n[w/o any patch] 99s\n[w/ first patch] 89s\n[w/ last minimal tuple patch] 79s\n\n-----------------------------------------------------------------------\n\nselect pg_prewarm('lineitem');\n-- lineitem is 17G. (TPCH scale = 20). shared_buffers = 30G\nexplain analyze select count(*) from lineitem;\n\n[w/o any patch] 10s\n[w/ first patch] 10s\n[w/ last minimal tuple patch] 10s\n\n-----------------------------------------------------------------------\n\nselect pg_prewarm('lineitem');\nselect pg_prewarm('orders');\n-- lineitem is 17G, orders is 4G. (TPCH scale = 20). shared_buffers = 30G\n\nexplain analyze select count(*)\n from lineitem\n join orders on l_orderkey = o_orderkey\n where o_totalprice > 5.00;\n\n[w/o any patch] 54s\n[w/ first patch] 53s\n[w/ last minimal tuple patch] 56s\n\n-----------------------------------------------------------------------\n\nMaybe I'm missing something, since there should be improvements with\nanything that has a gather?\n\nAs for gather merge, is it possible to have a situation where the slot\ninput to tqueueReceiveSlot() is a heap slot (as would be the case for a\nsimple select *)? If yes, in those scenarios, we would be incurring an\nextra call to minimal_tuple_from_heap_tuple() because of the extra call\nto ExecFetchSlotMinimalTuple() inside tqueueReceiveSlot() in your patch.\nAnd since, in a gather merge, we can't avoid the copy on the leader side\n(heap_copy_minimal_tuple() inside gm_readnext_tuple()), we would be\ndoing extra work in that scenario. I couldn't come up with a plan that\ncreates a scenario like this however.\n\nRegards,\nSoumyadeep (VMware)\n\n\n", "msg_date": "Fri, 10 Jul 2020 18:36:31 -0700", "msg_from": "Soumyadeep Chakraborty <soumyadeep2007@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Does TupleQueueReaderNext() really need to copy its result?" }, { "msg_contents": "On Sat, Jul 11, 2020 at 1:37 PM Soumyadeep Chakraborty\n<soumyadeep2007@gmail.com> wrote:\n> +1 to the idea! I ran some experiments on both of your patches.\n\nHi Soumyadeep,\n\nThanks for testing!\n\n> I could reproduce the speed gain that you saw for a plan with a simple\n> parallel sequential scan. However, I got no gain at all for a parallel\n> hash join and parallel agg query.\n\nRight, it's not going to make a difference when you only send one\ntuple through the queue, like COUNT(*) does.\n\n> As for gather merge, is it possible to have a situation where the slot\n> input to tqueueReceiveSlot() is a heap slot (as would be the case for a\n> simple select *)? If yes, in those scenarios, we would be incurring an\n> extra call to minimal_tuple_from_heap_tuple() because of the extra call\n> to ExecFetchSlotMinimalTuple() inside tqueueReceiveSlot() in your patch.\n> And since, in a gather merge, we can't avoid the copy on the leader side\n> (heap_copy_minimal_tuple() inside gm_readnext_tuple()), we would be\n> doing extra work in that scenario. I couldn't come up with a plan that\n> creates a scenario like this however.\n\nHmm. I wish we had a way to do an \"in-place\" copy-to-minimal-tuple\nwhere the caller supplies the memory, with some fast protocol to get\nthe size right. We could use that for copying tuples into shm queues,\nhash join tables etc without an extra palloc()/pfree() and double\ncopy.\n\n\n", "msg_date": "Sat, 11 Jul 2020 14:29:26 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Does TupleQueueReaderNext() really need to copy its result?" }, { "msg_contents": "Hey Thomas,\n\nOn Fri, Jul 10, 2020 at 7:30 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n>\n> > I could reproduce the speed gain that you saw for a plan with a simple\n> > parallel sequential scan. However, I got no gain at all for a parallel\n> > hash join and parallel agg query.\n>\n> Right, it's not going to make a difference when you only send one\n> tuple through the queue, like COUNT(*) does.\n\nHow silly of me! I should have paid more attention to the rows output\nfrom each worker and that there was a select count(*) on the join query.\nAnyway, these are a new set of results:\n\n-----------------------------------------------------------------------\n\nselect pg_prewarm('lineitem');\nselect pg_prewarm('orders');\n-- lineitem is 17G, orders is 4G. (TPCH scale = 20). shared_buffers = 30G\n\nexplain analyze select *\n from lineitem\n join orders on l_orderkey = o_orderkey\n where o_totalprice > 5.00;\n\n[w/o any patch] 637s\n[w/ first patch] 635s\n[w/ last minimal tuple patch] 568s\n\n-----------------------------------------------------------------------\n\nWe do indeed get the speedup.\n\n> > As for gather merge, is it possible to have a situation where the slot\n> > input to tqueueReceiveSlot() is a heap slot (as would be the case for a\n> > simple select *)? If yes, in those scenarios, we would be incurring an\n> > extra call to minimal_tuple_from_heap_tuple() because of the extra call\n> > to ExecFetchSlotMinimalTuple() inside tqueueReceiveSlot() in your patch.\n> > And since, in a gather merge, we can't avoid the copy on the leader side\n> > (heap_copy_minimal_tuple() inside gm_readnext_tuple()), we would be\n> > doing extra work in that scenario. I couldn't come up with a plan that\n> > creates a scenario like this however.\n>\n> Hmm. I wish we had a way to do an \"in-place\" copy-to-minimal-tuple\n> where the caller supplies the memory, with some fast protocol to get\n> the size right. We could use that for copying tuples into shm queues,\n> hash join tables etc without an extra palloc()/pfree() and double\n> copy.\n\nDo you mean that we should have an implementation for\nget_minimal_tuple() for the heap AM and have it return a pointer to the\nminimal tuple from the MINIMAL_TUPLE_OFFSET? And then a caller such as\ntqueueReceiveSlot() will ensure that the heap tuple from which it wants\nto extract the minimal tuple was allocated in the tuple queue in the\nfirst place? If we consider that the node directly below a gather is a\nSeqScan, then we could possibly, in ExecInitSeqScan() set-up the\nss_ScanTupleSlot to point to memory in the shared tuple queue?\nSimilarly, other ExecInit*() methods can do the same for other executor\nnodes that involve parallelism? Of course, things would be slightly\ndifferent for\nthe other use cases you mentioned (such as hash table population)\n\nAll things considered, I think the patch in its current form should go\nin. Having the in-place copy, could be done as a separate patch? Do you\nagree?\n\nRegards,\nSoumyadeep (VMware)\n\n\n", "msg_date": "Sat, 11 Jul 2020 12:25:08 -0700", "msg_from": "Soumyadeep Chakraborty <soumyadeep2007@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Does TupleQueueReaderNext() really need to copy its result?" }, { "msg_contents": "On Sun, Jul 12, 2020 at 7:25 AM Soumyadeep Chakraborty\n<soumyadeep2007@gmail.com> wrote:\n> Do you mean that we should have an implementation for\n> get_minimal_tuple() for the heap AM and have it return a pointer to the\n> minimal tuple from the MINIMAL_TUPLE_OFFSET? And then a caller such as\n> tqueueReceiveSlot() will ensure that the heap tuple from which it wants\n> to extract the minimal tuple was allocated in the tuple queue in the\n> first place? If we consider that the node directly below a gather is a\n> SeqScan, then we could possibly, in ExecInitSeqScan() set-up the\n> ss_ScanTupleSlot to point to memory in the shared tuple queue?\n> Similarly, other ExecInit*() methods can do the same for other executor\n> nodes that involve parallelism? Of course, things would be slightly\n> different for\n> the other use cases you mentioned (such as hash table population)\n\nWhat I mean is that where ExecHashTableInsert() and\ntqueueReceiveSlot() do ExecFetchSlotMinimalTuple(), you usually get a\nfreshly allocated copy, and then you copy that again, and free it.\nThere may be something similar going on in tuplestore and sort code.\nPerhaps we could have something like\nExecFetchSlotMinimalTupleInPlace(slot, output_buffer,\noutput_buffer_size) that returns a value that indicates either success\nor hey-that-buffer's-too-small-I-need-N-bytes, or something like that.\nThat silly extra copy is something Andres pointed out to me in some\nperf results involving TPCH hash joins, a couple of years ago.\n\n> All things considered, I think the patch in its current form should go\n> in.\n\nThanks for the testing and review! Pushed.\n\n> Having the in-place copy, could be done as a separate patch? Do you\n> agree?\n\nYeah.\n\n\n", "msg_date": "Fri, 17 Jul 2020 15:34:50 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Does TupleQueueReaderNext() really need to copy its result?" }, { "msg_contents": "Hi,\n\nI am starting a new thread that continues with the following point\nthat was discussed in [1] ....\n\nOn Fri, 17 Jul 2020 at 09:05, Thomas Munro <thomas.munro@gmail.com> wrote:\n>\n> On Sun, Jul 12, 2020 at 7:25 AM Soumyadeep Chakraborty\n> <soumyadeep2007@gmail.com> wrote:\n> > Do you mean that we should have an implementation for\n> > get_minimal_tuple() for the heap AM and have it return a pointer to the\n> > minimal tuple from the MINIMAL_TUPLE_OFFSET? And then a caller such as\n> > tqueueReceiveSlot() will ensure that the heap tuple from which it wants\n> > to extract the minimal tuple was allocated in the tuple queue in the\n> > first place? If we consider that the node directly below a gather is a\n> > SeqScan, then we could possibly, in ExecInitSeqScan() set-up the\n> > ss_ScanTupleSlot to point to memory in the shared tuple queue?\n> > Similarly, other ExecInit*() methods can do the same for other executor\n> > nodes that involve parallelism? Of course, things would be slightly\n> > different for\n> > the other use cases you mentioned (such as hash table population)\n>\n> What I mean is that where ExecHashTableInsert() and\n> tqueueReceiveSlot() do ExecFetchSlotMinimalTuple(), you usually get a\n> freshly allocated copy, and then you copy that again, and free it.\n> There may be something similar going on in tuplestore and sort code.\n> Perhaps we could have something like\n> ExecFetchSlotMinimalTupleInPlace(slot, output_buffer,\n> output_buffer_size) that returns a value that indicates either success\n> or hey-that-buffer's-too-small-I-need-N-bytes, or something like that.\n> That silly extra copy is something Andres pointed out to me in some\n> perf results involving TPCH hash joins, a couple of years ago.\n\nI went ahead and tried doing this. I chose an approach where we can\nreturn the pointer to the in-place minimal tuple data if it's a\nheap/buffer/minimal tuple slot. A new function\nExecFetchSlotMinimalTupleData() returns in-place minimal tuple data.\nIf it's neither heap, buffer or minimal tuple, it returns a copy as\nusual. The receiver should not assume the data is directly taken from\nMinimalTupleData, so it should set it's t_len to the number of bytes\nreturned. Patch attached\n(0001-Avoid-redundant-tuple-copy-while-sending-tuples-to-G.patch)\n\nThomas, I guess you had a different approach in mind when you said\nabout \"returning either success or\nhey-that-buffer's-too-small-I-need-N-bytes\". But what looks clear to\nme is that avoiding the copy shows consistent improvement of 4 to 10%\nfor simple parallel table scans. I tried my patch on both x86_64 and\narm64, and observed this speedup on both.\n\ncreate table tab as select generate_series(1, 20000000) id,\n'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz' v;\nselect pg_prewarm('tab'::regclass);\nexplain analyze select * from tab where id %2 = 0;\nTimes in milli-secs :\nHEAD : 1833.119 1816.522 1875.648 1872.153 1834.383\nPatch'ed : 1763.786 1721.160 1714.665 1719.738 1704.478\nThis was with the default 2 parallel workers. With 3 or 4 workers, for\nthe above testcase I didn't see a noticeable difference. I think, if I\ndouble the number of rows, the difference will be noticeable. In any\ncase, the gain would go on reducing with the number of workers,\nbecause the tuple copy also gets parallelized. In some scenarios,\nparallel_leader_participation=off causes the difference to amplify.\n\nHaven't had a chance to see if this helps any of the TPC-H queries.\n\nAlso attached is a patch guc_for_testing.patch that I used for testing\nthe gain. This patch is only for testing. Without this, in order to\ncompare the performance figures it requires server restart, and the\nfigures anyway shift back and forth by 5-15 percent after each\nrestart, which creates lot of noise when comparing figures with and\nwithout fix. Use this GUC enable_fix to enable/disable the fix.\n\n[1] https://www.postgresql.org/message-id/CA%2BhUKGLrN2M18-hACEJbNoj2sn_WoUj9rkkBeoPK7SY427pAnA%40mail.gmail.com\n\n-- \nThanks,\n-Amit Khandekar\nHuawei Technologies", "msg_date": "Wed, 9 Sep 2020 10:52:47 +0530", "msg_from": "Amit Khandekar <amitdkhan.pg@gmail.com>", "msg_from_op": false, "msg_subject": "Redundant tuple copy in tqueueReceiveSlot()" }, { "msg_contents": "On Wed, Sep 9, 2020 at 5:23 PM Amit Khandekar <amitdkhan.pg@gmail.com> wrote:\n> I went ahead and tried doing this. I chose an approach where we can\n> return the pointer to the in-place minimal tuple data if it's a\n> heap/buffer/minimal tuple slot. A new function\n> ExecFetchSlotMinimalTupleData() returns in-place minimal tuple data.\n> If it's neither heap, buffer or minimal tuple, it returns a copy as\n> usual. The receiver should not assume the data is directly taken from\n> MinimalTupleData, so it should set it's t_len to the number of bytes\n> returned. Patch attached\n> (0001-Avoid-redundant-tuple-copy-while-sending-tuples-to-G.patch)\n\n+char *\n+ExecFetchSlotMinimalTupleData(TupleTableSlot *slot, uint32 *len,\n+ bool *shouldFree)\n\nInteresting approach. It's a bit of a weird interface, returning a\npointer to a non-valid MinimalTuple that requires extra tweaking after\nyou copy it to make it a valid one and that you're not allowed to\ntweak in-place. I'd probably make that return \"const void *\" just for\na bit of extra documentation. I wonder if there is a way we could\nmake \"Minimal Tuples but with the length travelling separately (and\nperhaps chopped off?)\" into a first-class concept... It's also a\nshame to be schlepping a bunch of padding bytes around.\n\n tuple = (MinimalTuple) data;\n- Assert(tuple->t_len == nbytes);\n+ tuple->t_len = nbytes;\n\nHmm, so you have to scribble on shared memory on the receiving side.\nI wondered about a couple of different ways to share the length field\nwith the shm_mq envelope, but that all seems a bit too weird...\n\n> Thomas, I guess you had a different approach in mind when you said\n> about \"returning either success or\n> hey-that-buffer's-too-small-I-need-N-bytes\". But what looks clear to\n\nYeah I tried some things like that, but I wasn't satisfied with any of\nthem; basically the extra work involved in negotiating the size was a\nbit too high. On the other hand, because my interface was \"please\nwrite a MinimalTuple here!\", it had the option to *form* a\nMinimalTuple directly in place, whereas your approach can only avoid\ncreating and destroying a temporary tuple when the source is a heap\ntuple.\n\n> me is that avoiding the copy shows consistent improvement of 4 to 10%\n> for simple parallel table scans. I tried my patch on both x86_64 and\n> arm64, and observed this speedup on both.\n\nI think that's a great validation of the goal but I hope we can figure\nout a way that avoids the temporary tuple for more cases. FWIW I saw\nhash self joins running a couple of percent faster with one of my\nabandoned patches.\n\n\n", "msg_date": "Thu, 17 Sep 2020 14:20:50 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Redundant tuple copy in tqueueReceiveSlot()" }, { "msg_contents": "Hi,\n\nOn 2020-09-17 14:20:50 +1200, Thomas Munro wrote:\n> I wonder if there is a way we could make \"Minimal Tuples but with the\n> length travelling separately (and perhaps chopped off?)\" into a\n> first-class concept... It's also a shame to be schlepping a bunch of\n> padding bytes around.\n\nThere really is no justification for having MinimalTuples, as we have\nthem today at least, anymore. We used to rely on being able to construct\npointers to MinimalTuples that are mostly compatible with HeapTuple. But\nI think there's none of those left since PG 12.\n\nI think it'd make a bit more sense to do some steps towards having a\nmore suitable \"minimal\" tuple representation, rather than doing this\nlocal, pretty ugly, hacks. A good way would be to just starting to\nremove the padding, unnecessary fields etc from MinimalTuple.\n\nI also think that it'd be good to look at a few of the other places that\nare heavily bottlenecked by MinimalTuple overhead before designing new\nAPI around this. IIRC it's e.g. very easy to see hash joins spending a\nlot of time doing MinimalTuple copies & conversions.\n\n> \n> tuple = (MinimalTuple) data;\n> - Assert(tuple->t_len == nbytes);\n> + tuple->t_len = nbytes;\n> \n> Hmm, so you have to scribble on shared memory on the receiving side.\n\nIck, I would really like to avoid this.\n\n\n> > Thomas, I guess you had a different approach in mind when you said\n> > about \"returning either success or\n> > hey-that-buffer's-too-small-I-need-N-bytes\". But what looks clear to\n> \n> Yeah I tried some things like that, but I wasn't satisfied with any of\n> them; basically the extra work involved in negotiating the size was a\n> bit too high. On the other hand, because my interface was \"please\n> write a MinimalTuple here!\", it had the option to *form* a\n> MinimalTuple directly in place, whereas your approach can only avoid\n> creating and destroying a temporary tuple when the source is a heap\n> tuple.\n\nThere's a lot of cases where the source is a virtual slot (since we'll\noften project stuff below Gather). So it'd be quite advantageous to\navoid building an unnecessary HeapTuple in those cases.\n\nI wonder if it would be sensible to build minimal tuples using\ntts_values/isnull in some cases. This might even be advantageous in\ncase of heap / minimal tuples, because IIRC right now the code will\nmaterialize the slot unnecessarily. Not sure how common that is.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 16 Sep 2020 20:25:02 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Redundant tuple copy in tqueueReceiveSlot()" }, { "msg_contents": "On Thu, 17 Sep 2020 at 08:55, Andres Freund <andres@anarazel.de> wrote:\n>\n> Hi,\n>\n> On 2020-09-17 14:20:50 +1200, Thomas Munro wrote:\n> > I wonder if there is a way we could make \"Minimal Tuples but with the\n> > length travelling separately (and perhaps chopped off?)\" into a\n> > first-class concept... It's also a shame to be schlepping a bunch of\n> > padding bytes around.\n\nYeah, I think we can pass a \"length\" data separately, but since the\nreceiver end already is assuming that it knows the received data is a\nminimal tuple, I thought why not skip passing this redundant\ncomponent. But anyways, if you and Andres are suggesting that being\nable to skip the copy is important for virtual tuples as well, then I\nthink the approach you suggested (supplying an allocated memory to the\ntuple API for conversion) would be one of the better options with us,\nif not the only good option. Maybe I will try looking into the shm_mq\nworking to see if we can come up with a good solution.\n\n>\n> There really is no justification for having MinimalTuples, as we have\n> them today at least, anymore. We used to rely on being able to construct\n> pointers to MinimalTuples that are mostly compatible with HeapTuple. But\n> I think there's none of those left since PG 12.\n\nAh ok.\n\n>\n> I think it'd make a bit more sense to do some steps towards having a\n> more suitable \"minimal\" tuple representation, rather than doing this\n> local, pretty ugly, hacks. A good way would be to just starting to\n> remove the padding, unnecessary fields etc from MinimalTuple.\n\nSo there are two things we wish to do :\n1. Prevent an extra tuple forming step before sending minimal tuple\ndata. Possibly device an shm_mq API to get memory to write tuple of a\ngiven length, and device something like\nFormMinimalTupleDataInHere(memory_allocated_by_shm_mq) which will\nwrite minimal tuple data.\n2. Shrink the MinimalTupleData structure because it no longer needs\nthe current padding etc and we can substitute this new MinimalTuple\nstructure with the current one all over the code wherever it is\ncurrently being used.\n\nIf we remove the unnecessary fields from the tuple data being sent to\nGather node, then we need to again form a MinimalTuple at the\nreceiving end, which again adds an extra tuple forming. So I\nunderstand, that's the reason why you are saying we should shrink the\nMinimalTupleData structure itself, in which case we will continue to\nuse the received new MinimalTupledata as an already-formed tuple, like\nhow we are doing now.\n\nNow, the above two things (1. and 2.) look independent to me. Suppose\nwe first do 1. i.e. we come up with a good way to form an in-place\nMinimalTuple at the sender's end, without any change to the\nMinimalTupleData. And then when we do 2. i.e. shrink the\nMinimalTupleData; but for that, we won't require any change in the\nin-place-tuple-forming API we wrote in 1. . Just the existing\nunderlying function heap_form_minimal_tuple() or something similar\nmight need to be changed. At least that's what I feel right now.\n\n>\n> I also think that it'd be good to look at a few of the other places that\n> are heavily bottlenecked by MinimalTuple overhead before designing new\n> API around this. IIRC it's e.g. very easy to see hash joins spending a\n> lot of time doing MinimalTuple copies & conversions.\n\nYeah, makes sense. The above FormMinimalTupleDataInHere() should be\nable to be used for these other places as well. Will keep that in\nmind.\n\n>\n> > > Thomas, I guess you had a different approach in mind when you said\n> > > about \"returning either success or\n> > > hey-that-buffer's-too-small-I-need-N-bytes\". But what looks clear to\n> >\n> > Yeah I tried some things like that, but I wasn't satisfied with any of\n> > them; basically the extra work involved in negotiating the size was a\n> > bit too high.\n\nHmm, ok. Let me see if there is any way around this.\n\n>> On the other hand, because my interface was \"please\n> > write a MinimalTuple here!\", it had the option to *form* a\n> > MinimalTuple directly in place, whereas your approach can only avoid\n> > creating and destroying a temporary tuple when the source is a heap\n> > tuple.\nTrue.\n>\n> There's a lot of cases where the source is a virtual slot (since we'll\n> often project stuff below Gather). So it'd be quite advantageous to\n> avoid building an unnecessary HeapTuple in those cases.\n\nYeah right.\n\n\n", "msg_date": "Fri, 18 Sep 2020 16:16:59 +0530", "msg_from": "Amit Khandekar <amitdkhan.pg@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Redundant tuple copy in tqueueReceiveSlot()" } ]
[ { "msg_contents": "Hello, hackers:\n\nI created a patch about tab completion for command CREATE OR REPLACE in psql\nincludes:\n\tCREATE [ OR REPLACE ] FUNCTION\n\tCREATE [ OR REPLACE ] PROCEDURE\n\tCREATE [ OR REPLACE ] LANGUAGE\n\tCREATE [ OR REPLACE ] RULE name AS ON event\n\tCREATE [ OR REPLACE ] VIEW AS SELECT\n\tCREATE [ OR REPLACE ] AGGREGATE\n\tCREATE [ OR REPLACE ] TRANSFORM\n\n------------------------------------------------------------------------------------------\nRegards\nShenhao Wang", "msg_date": "Thu, 22 Aug 2019 06:05:44 +0000", "msg_from": "\"Wang, Shenhao\" <wangsh.fnst@cn.fujitsu.com>", "msg_from_op": true, "msg_subject": "[PATCH] Tab completion for CREATE OR REPLACE" }, { "msg_contents": "On Thu, 22 Aug 2019 at 15:05, Wang, Shenhao <wangsh.fnst@cn.fujitsu.com> wrote:\n>\n> Hello, hackers:\n>\n> I created a patch about tab completion for command CREATE OR REPLACE in psql\n> includes:\n> CREATE [ OR REPLACE ] FUNCTION\n> CREATE [ OR REPLACE ] PROCEDURE\n> CREATE [ OR REPLACE ] LANGUAGE\n> CREATE [ OR REPLACE ] RULE name AS ON event\n> CREATE [ OR REPLACE ] VIEW AS SELECT\n> CREATE [ OR REPLACE ] AGGREGATE\n> CREATE [ OR REPLACE ] TRANSFORM\n>\n> ------------------------------------------------------------------------------------------\n\nCould you add this to the next commitfest?\n\n https://commitfest.postgresql.org/24/\n\nRegards\n\nIan Barwick\n\n--\n Ian Barwick https://www.2ndQuadrant.com/\n PostgreSQL Development, 24x7 Support, Training & Services\n\n\n", "msg_date": "Thu, 22 Aug 2019 15:28:19 +0900", "msg_from": "Ian Barwick <ian.barwick@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Tab completion for CREATE OR REPLACE" }, { "msg_contents": "On Thu, Aug 22, 2019 at 3:06 PM Wang, Shenhao\n<wangsh.fnst@cn.fujitsu.com> wrote:\n>\n> Hello, hackers:\n>\n> I created a patch about tab completion for command CREATE OR REPLACE in psql\n> includes:\n> CREATE [ OR REPLACE ] FUNCTION\n> CREATE [ OR REPLACE ] PROCEDURE\n> CREATE [ OR REPLACE ] LANGUAGE\n> CREATE [ OR REPLACE ] RULE name AS ON event\n> CREATE [ OR REPLACE ] VIEW AS SELECT\n> CREATE [ OR REPLACE ] AGGREGATE\n> CREATE [ OR REPLACE ] TRANSFORM\n\nThanks for the patch! The patch looks good to me.\nBarring no objection, I will commit this.\n\nRegards,\n\n-- \nFujii Masao\n\n\n", "msg_date": "Tue, 3 Sep 2019 23:04:49 +0900", "msg_from": "Fujii Masao <masao.fujii@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Tab completion for CREATE OR REPLACE" }, { "msg_contents": "On Tue, Sep 3, 2019 at 11:04 PM Fujii Masao <masao.fujii@gmail.com> wrote:\n>\n> On Thu, Aug 22, 2019 at 3:06 PM Wang, Shenhao\n> <wangsh.fnst@cn.fujitsu.com> wrote:\n> >\n> > Hello, hackers:\n> >\n> > I created a patch about tab completion for command CREATE OR REPLACE in psql\n> > includes:\n> > CREATE [ OR REPLACE ] FUNCTION\n> > CREATE [ OR REPLACE ] PROCEDURE\n> > CREATE [ OR REPLACE ] LANGUAGE\n> > CREATE [ OR REPLACE ] RULE name AS ON event\n> > CREATE [ OR REPLACE ] VIEW AS SELECT\n> > CREATE [ OR REPLACE ] AGGREGATE\n> > CREATE [ OR REPLACE ] TRANSFORM\n>\n> Thanks for the patch! The patch looks good to me.\n\nCommitted. Thanks!\n\nRegards,\n\n-- \nFujii Masao\n\n\n", "msg_date": "Fri, 13 Sep 2019 18:21:59 +0900", "msg_from": "Fujii Masao <masao.fujii@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Tab completion for CREATE OR REPLACE" } ]
[ { "msg_contents": "Hi all,\n\nIn six places of the code tree (+ one in psql which is a bit\ndifferent), we have the following pattern for frontend tools to\nconnect to a backend with a password prompt, roughly like that:\ndo\n{\n [...]\n conn = PQconnectdbParams(keywords, values, true);\n\n [...]\n\n if (PQstatus(conn) == CONNECTION_BAD &&\n PQconnectionNeedsPassword(conn) &&\n\t!have_password)\n {\n PQfinish(conn);\n simple_prompt(\"Password: \", password, sizeof(password), false);\n have_password = true;\n new_pass = true;\n }\n} while (new_pass);\n\nAttached is a tentative of patch to consolidate this logic across the\ntree. The patch is far from being in a committable state, and there\nare a couple of gotchas:\n- pg_dumpall merges connection string parameters, so it is much harder\nto plugin that the others, and I left it out on purpose.\n- Some code paths spawn a password prompt before the first connection\nattempt. For now I have left this first attempt out of the refactored\nlogic, but I think that it is possible to consolidate that a bit more\nby enforcing a password prompt before doing the first connection\nattempt (somewhat related to the XXX portion in the patch). At the\nend it would be nice to not have to have a 100-byte-long field for the\npassword buffer we have here and there. Unfortunately this comes with\nits limitations in pg_dump as savedPassword needs to be moved around\nand may be reused in the context.\n- I don't like the routine name connect_with_password_prompt() I\nintroduced. Suggestions of better names are welcome :)\n- This also brings the point that some of our tools are not able to\nhandle tri-values for passwords, so we may want to consolidate that as\nwell.\n\nAmong the positive points, this brings a lot of consolidation in terms\nof error handling, and this shaves a bit of code:\n13 files changed, 190 insertions(+), 280 deletions(-) \n\nThis moves the logic into src/fe_utils, which is natural as that's\naimed only for frontends and because this also links to libpq.\n\nPlease note that this links a bit with the refactoring of vacuumlo and\noid2name logging I proposed a couple of days back (applying one patch\nor the other results in conflicts) because we need to have frontends\ninitialized for logging in order to be able to log errors in the\nrefactored routine:\nhttps://www.postgresql.org/message-id/20190820012819.GA8326@paquier.xyz\nThis one should be merged first IMO, but that's a story for the other\nthread.\n\nThis compiles, and passes all regression tests so it is possible to\nplay with it easily, still it needs much more testing and love.\n\nAny thoughts? I am adding that to the next commit fest.\n\nThanks,\n--\nMichael", "msg_date": "Thu, 22 Aug 2019 16:45:58 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Refactoring of connection with password prompt loop for frontends" }, { "msg_contents": "This patch has been absolutely overlooked by reviewers. Euler, you're\nregistered as a reviewer for it. Will you submit a review soon? :-)\n\nIt does not currently apply, so if we get a rebase, that'd be good too.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 25 Sep 2019 17:47:39 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Refactoring of connection with password prompt loop for frontends" }, { "msg_contents": "On Wed, Sep 25, 2019 at 05:47:39PM -0300, Alvaro Herrera wrote:\n> This patch has been absolutely overlooked by reviewers. Euler, you're\n> registered as a reviewer for it. Will you submit a review soon? :-)\n> \n> It does not currently apply, so if we get a rebase, that'd be good too.\n\nHere you go. There were four conflicts in total caused by the switch\nto the central logging infra for vacuumlo/oid2name and the\nintroduction of recovery_gen.c. No actual changes except the rebase.\n--\nMichael", "msg_date": "Thu, 26 Sep 2019 16:23:51 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Refactoring of connection with password prompt loop for frontends" }, { "msg_contents": "On 2019-Sep-26, Michael Paquier wrote:\n\n> On Wed, Sep 25, 2019 at 05:47:39PM -0300, Alvaro Herrera wrote:\n> > This patch has been absolutely overlooked by reviewers. Euler, you're\n> > registered as a reviewer for it. Will you submit a review soon? :-)\n> > \n> > It does not currently apply, so if we get a rebase, that'd be good too.\n> \n> Here you go. There were four conflicts in total caused by the switch\n> to the central logging infra for vacuumlo/oid2name and the\n> introduction of recovery_gen.c. No actual changes except the rebase.\n\nHmm, you have an XXX comment that appears to need addressing; and I'd\nadd an explanation about the looping behavior to the comment atop the\nnew function.\n\nI see that vacuumlo and scripts/common retain their \"have_password\"\nvariables. That seems to be so that they can reuse one for other\ndatabases. But how does that work with the new routine?\n\nI notice you changed the historical error message \n\n> -\t\t\tpg_log_error(\"connection to database \\\"%s\\\" failed\", database);\n\nto\n\n> +\t\tpg_log_error(\"could not connect to database \\\"%s\\\": %s\",\n\nThe change seems appropriate to me.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 26 Sep 2019 10:06:27 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Refactoring of connection with password prompt loop for frontends" }, { "msg_contents": "On Thu, Sep 26, 2019 at 10:06:27AM -0300, Alvaro Herrera wrote:\n> Hmm, you have an XXX comment that appears to need addressing; and I'd\n> add an explanation about the looping behavior to the comment atop the\n> new function.\n> \n> I see that vacuumlo and scripts/common retain their \"have_password\"\n> variables. That seems to be so that they can reuse one for other\n> databases. But how does that work with the new routine?\n\nThat's the second bullet point I mentioned at the top of the thread\n(https://www.postgresql.org/message-id/20190822074558.GG1683@paquier.xyz),\nand something I wanted to discuss for this patch:\n\"Some code paths spawn a password prompt before the first connection\nattempt...\"\n\nHistorically, vacuumlo, scripts/common.c and pg_backup_db.c ask for a\npassword before doing the first connection attempt, which is different\nthan any other code paths. That's the reason why have_password is\nstill there in the case of the first one. scripts/common.c and\npg_dump are different issues as we don't want to repeat the password\nfor multiple database connections. That point is also related to the\nXXX comment, because if we make the logic more consistent with the\nrest (aka ask for the password the first time after the first\nconnection attempt), then we could remove completely the extra\nhandling with saved_password (meaning no more XXX). That would be\nalso nicer as we want to keep a fixed size for the password buffer of\n100 bytes.\n\nThinking more about it, keeping connect_with_password_prompt() a\nmaximum simple would be nicer for future maintenance, and it looks\nthat we may actually be able to remove allow_password_reuse from\nconnectDatabase() in common.c, but this needs a rather close lookup as\nwe should not create any password exposure hazards.\n\nFor now I am switching the patch as returned with feedback as there is\nmuch more to consider. And it did not attract much attention either.\n--\nMichael", "msg_date": "Fri, 27 Sep 2019 16:14:01 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Refactoring of connection with password prompt loop for frontends" } ]
[ { "msg_contents": "Hi,\n\nWhile merging Greenplum with 9.4, we ran into problems with the GIN \nposting list encoding, because Greenplum sometimes uses ItemPointers \nwith offset numbers up to 32768. The GIN posting list code was written \nwith the assumption that the maximum is MaxHeapTuplesPerPage, and it \nuses only 11 bits for the offset number. The fix was simple, we just \nmodified ginpostinglist.c to use full 16 bits instead of 11.\n\nHowever, I noticed that this comment in ginpostinglist.c that explains \nthe encoding doesn't match the code:\n\n> * These 43-bit integers are encoded using varbyte encoding. In each byte,\n> * the 7 low bits contain data, while the highest bit is a continuation bit.\n> * When the continuation bit is set, the next byte is part of the same\n> * integer, otherwise this is the last byte of this integer. 43 bits fit\n> * conveniently in at most 6 bytes when varbyte encoded (the 6th byte does\n> * not need a continuation bit, because we know the max size to be 43 bits):\n> *\n> * 0XXXXXXX\n> * 1XXXXXXX 0XXXXYYY\n> * 1XXXXXXX 1XXXXYYY 0YYYYYYY\n> * 1XXXXXXX 1XXXXYYY 1YYYYYYY 0YYYYYYY\n> * 1XXXXXXX 1XXXXYYY 1YYYYYYY 1YYYYYYY 0YYYYYYY\n> * 1XXXXXXX 1XXXXYYY 1YYYYYYY 1YYYYYYY 1YYYYYYY YYYYYYYY\n> *\n> * X = bits used for offset number\n> * Y = bits used for block number\n\nThe code doesn't actually give the 6th byte any special treatment. If \nthe input integer has the 43rd bit set, the encoding function will put a \ncontinuation bit on the 6th byte, and generate a 7th byte. And the \ndecoding function will correctly decode that, too. So to my surprise, \nthe implementation actually works for integers up 49 bits wide. However, \nthere is an overflow check in the encoding function that assumes max 6 \nbytes per integer. That needs to be fixed, along with the comment.\n\nFitting any item pointer into 6 bytes was an important property when \nthis was written, because in the old pre-9.4 format, posting lists were \nas arrays, with 6 bytes per item pointer. The maximum of 6 bytes per \ninteger in the new format guaranteed that we could convert any page from \nthe old format to the new format, after pg_upgrade, so that the new \nformat was never larger than the old format. But I don't think we need \nto worry much about that anymore. Luckily, no one has ran into this \nwhile trying to upgrade. It would require having a 9.3 cluster with a \ntable larger than 16 TB (with 8k block size), with a GIN index on it, \nand a posting list with TIDs more than 2^31 blocks distance, on a full \npage. So, not a problem in practice.\n\nIn summary, the comment in ginpostinglist.c is wrong, and the overflow \ncheck needs to be fixed. Patch attached.\n\nThe patch also includes a little unit test module to test this without \ncreating a 16 TB table. A whole new test module seems a bit like \noverkill just for this, but clearly we were missing test coverage here. \nAnd it will come handy, if we want to invent a new better posting list \nformat in the future. Thoughts on whether to include the test module or not?\n\n- Heikki", "msg_date": "Thu, 22 Aug 2019 11:14:39 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": true, "msg_subject": "Comment in ginpostinglist.c doesn't match code" }, { "msg_contents": "On Thu, Aug 22, 2019 at 1:14 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n\n>\n> The patch also includes a little unit test module to test this without\n> creating a 16 TB table. A whole new test module seems a bit like\n> overkill just for this, but clearly we were missing test coverage here.\n> And it will come handy, if we want to invent a new better posting list\n> format in the future. Thoughts on whether to include the test module or\n> not?\n>\n\nI like the test as importantly adds missing coverage. Also, really\nsimplifies validation effort if required to make change in this area\nanytime in future. So, I would +1 keeping the same.\n\nOn Thu, Aug 22, 2019 at 1:14 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\nThe patch also includes a little unit test module to test this without \ncreating a 16 TB table. A whole new test module seems a bit like \noverkill just for this, but clearly we were missing test coverage here. \nAnd it will come handy, if we want to invent a new better posting list \nformat in the future. Thoughts on whether to include the test module or not?I like the test as importantly adds missing coverage. Also, really simplifies validation effort if required to make change in this area anytime in future. So, I would +1 keeping the same.", "msg_date": "Thu, 22 Aug 2019 15:05:08 -0700", "msg_from": "Ashwin Agrawal <aagrawal@pivotal.io>", "msg_from_op": false, "msg_subject": "Re: Comment in ginpostinglist.c doesn't match code" }, { "msg_contents": "On Fri, Aug 23, 2019 at 7:05 AM Ashwin Agrawal <aagrawal@pivotal.io> wrote:\n>\n> On Thu, Aug 22, 2019 at 1:14 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>>\n>>\n>> The patch also includes a little unit test module to test this without\n>> creating a 16 TB table. A whole new test module seems a bit like\n>> overkill just for this, but clearly we were missing test coverage here.\n>> And it will come handy, if we want to invent a new better posting list\n>> format in the future. Thoughts on whether to include the test module or not?\n>\n>\n> I like the test as importantly adds missing coverage. Also, really simplifies validation effort if required to make change in this area anytime in future. So, I would +1 keeping the same.\n\nI'd +1 too. It's valuable to test hard-to-reproduce case. I often want\nto do such unit tests with more cheaper costs, though.\n\nBTW it's not related to this patch but I got confused that where \"17\nbits\" of the following paragraph in ginpostinglist.c comes from. If we\nuse only 43 bit out of 64-bit unsigned integer we have 21 bits left.\n\n * For encoding purposes, item pointers are represented as 64-bit unsigned\n * integers. The lowest 11 bits represent the offset number, and the next\n * lowest 32 bits are the block number. That leaves 17 bits unused, i.e.\n * only 43 low bits are used.\n\nRegards,\n\n--\nMasahiko Sawada\nNIPPON TELEGRAPH AND TELEPHONE CORPORATION\nNTT Open Source Software Center\n\n\n", "msg_date": "Fri, 23 Aug 2019 17:44:01 +0900", "msg_from": "Masahiko Sawada <sawada.mshk@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Comment in ginpostinglist.c doesn't match code" }, { "msg_contents": "On Thu, Aug 22, 2019 at 11:14 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> While merging Greenplum with 9.4, we ran into problems with the GIN\n> posting list encoding, because Greenplum sometimes uses ItemPointers\n> with offset numbers up to 32768. The GIN posting list code was written\n> with the assumption that the maximum is MaxHeapTuplesPerPage, and it\n> uses only 11 bits for the offset number. The fix was simple, we just\n> modified ginpostinglist.c to use full 16 bits instead of 11.\n>\n> However, I noticed that this comment in ginpostinglist.c that explains\n> the encoding doesn't match the code:\n>\n> > * These 43-bit integers are encoded using varbyte encoding. In each byte,\n> > * the 7 low bits contain data, while the highest bit is a continuation bit.\n> > * When the continuation bit is set, the next byte is part of the same\n> > * integer, otherwise this is the last byte of this integer. 43 bits fit\n> > * conveniently in at most 6 bytes when varbyte encoded (the 6th byte does\n> > * not need a continuation bit, because we know the max size to be 43 bits):\n> > *\n> > * 0XXXXXXX\n> > * 1XXXXXXX 0XXXXYYY\n> > * 1XXXXXXX 1XXXXYYY 0YYYYYYY\n> > * 1XXXXXXX 1XXXXYYY 1YYYYYYY 0YYYYYYY\n> > * 1XXXXXXX 1XXXXYYY 1YYYYYYY 1YYYYYYY 0YYYYYYY\n> > * 1XXXXXXX 1XXXXYYY 1YYYYYYY 1YYYYYYY 1YYYYYYY YYYYYYYY\n> > *\n> > * X = bits used for offset number\n> > * Y = bits used for block number\n>\n> The code doesn't actually give the 6th byte any special treatment. If\n> the input integer has the 43rd bit set, the encoding function will put a\n> continuation bit on the 6th byte, and generate a 7th byte. And the\n> decoding function will correctly decode that, too. So to my surprise,\n> the implementation actually works for integers up 49 bits wide. However,\n> there is an overflow check in the encoding function that assumes max 6\n> bytes per integer. That needs to be fixed, along with the comment.\n\nGood catch!\n\n> Fitting any item pointer into 6 bytes was an important property when\n> this was written, because in the old pre-9.4 format, posting lists were\n> as arrays, with 6 bytes per item pointer. The maximum of 6 bytes per\n> integer in the new format guaranteed that we could convert any page from\n> the old format to the new format, after pg_upgrade, so that the new\n> format was never larger than the old format. But I don't think we need\n> to worry much about that anymore. Luckily, no one has ran into this\n> while trying to upgrade. It would require having a 9.3 cluster with a\n> table larger than 16 TB (with 8k block size), with a GIN index on it,\n> and a posting list with TIDs more than 2^31 blocks distance, on a full\n> page. So, not a problem in practice.\n\nI agree, this doesn't seem to be a problem assuming nobody reported\nthis till end of support for 9.3. It seems that nobody tried to\nupgrade such a huge table with GIN index.\n\n> In summary, the comment in ginpostinglist.c is wrong, and the overflow\n> check needs to be fixed. Patch attached.\n>\n> The patch also includes a little unit test module to test this without\n> creating a 16 TB table. A whole new test module seems a bit like\n> overkill just for this, but clearly we were missing test coverage here.\n> And it will come handy, if we want to invent a new better posting list\n> format in the future. Thoughts on whether to include the test module or not?\n\nFor me test module looks valuable. Many times I've felt uneasy about\nour test suite, because it doesn't cover many situations, which\nnaturally happens only on large datasets. It's good that you've found\nthe way to reproduce this particular case without creating enormous\ntable.\n\nI didn't review this module yet, but +1 for idea.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Sat, 24 Aug 2019 05:03:38 +0300", "msg_from": "Alexander Korotkov <aekorotkov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Comment in ginpostinglist.c doesn't match code" }, { "msg_contents": "On 23/08/2019 11:44, Masahiko Sawada wrote:\n> On Fri, Aug 23, 2019 at 7:05 AM Ashwin Agrawal <aagrawal@pivotal.io> wrote:\n>>\n>> On Thu, Aug 22, 2019 at 1:14 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>>> The patch also includes a little unit test module to test this without\n>>> creating a 16 TB table. A whole new test module seems a bit like\n>>> overkill just for this, but clearly we were missing test coverage here.\n>>> And it will come handy, if we want to invent a new better posting list\n>>> format in the future. Thoughts on whether to include the test module or not?\n>>\n>>\n>> I like the test as importantly adds missing coverage. Also, really simplifies validation effort if required to make change in this area anytime in future. So, I would +1 keeping the same.\n> \n> I'd +1 too. It's valuable to test hard-to-reproduce case. I often want\n> to do such unit tests with more cheaper costs, though.\n\nOk, including it seems to be the consensus.\n\n> BTW it's not related to this patch but I got confused that where \"17\n> bits\" of the following paragraph in ginpostinglist.c comes from. If we\n> use only 43 bit out of 64-bit unsigned integer we have 21 bits left.\n> \n> * For encoding purposes, item pointers are represented as 64-bit unsigned\n> * integers. The lowest 11 bits represent the offset number, and the next\n> * lowest 32 bits are the block number. That leaves 17 bits unused, i.e.\n> * only 43 low bits are used.\n\nHuh, you're right. I think it should be \"leaves 21 bits unused\". I \nsuspect the patch used 15 bits for the offset number early in the \ndevelopment, which would've left 17 bits unused, and when it was later \nchanged to use only 11 bits, that comment was neglected.\n\nFixed that comment, too, and pushed. Thanks!\n\n- Heikki\n\n\n", "msg_date": "Wed, 28 Aug 2019 13:39:13 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": true, "msg_subject": "Re: Comment in ginpostinglist.c doesn't match code" } ]
[ { "msg_contents": "Hello,\n\nEven if skipping header is done only once its checked and skipped in a\nloop. If I don’t miss something it can be done out side a loop like\nattached patch\n\nregards\n\nSurafel", "msg_date": "Thu, 22 Aug 2019 11:31:14 +0300", "msg_from": "Surafel Temesgen <surafel3000@gmail.com>", "msg_from_op": true, "msg_subject": "Take skip header out of a loop in COPY FROM" }, { "msg_contents": "On 22/08/2019 11:31, Surafel Temesgen wrote:\n> Hello,\n> \n> Even if skipping header is done only once its checked and skipped in a \n> loop. If I don’t miss something it can be done out side a loop like \n> attached patch\n\nYou may be on to something, but if we move it to CopyFrom(), as in your \npatch, then it won't get executed e.g. from the calls in file_fdw. \nfile_fdw calls BeginCopyFrom(), followed by NextCopyFrom(); it doesn't \nuse CopyFrom().\n\n- Heikki\n\n\n", "msg_date": "Thu, 22 Aug 2019 11:48:31 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Take skip header out of a loop in COPY FROM" }, { "msg_contents": "On Thu, Aug 22, 2019 at 11:48:31AM +0300, Heikki Linnakangas wrote:\n> On 22/08/2019 11:31, Surafel Temesgen wrote:\n> > Hello,\n> > \n> > Even if skipping header is done only once its checked and skipped in a\n> > loop. If I don’t miss something it can be done out side a loop like\n> > attached patch\n> \n> You may be on to something, but if we move it to CopyFrom(), as in your\n> patch, then it won't get executed e.g. from the calls in file_fdw. file_fdw\n> calls BeginCopyFrom(), followed by NextCopyFrom(); it doesn't use\n> CopyFrom().\n> \n> - Heikki\n\nYes.\n\nMy next thought is to call unlikely() here, but we don't have it...\nhttps://www.postgresql.org/message-id/CABRT9RC-AUuQL6txxsoOkLxjK1iTpyexpbizRF4Zxny1GXASGg%40mail.gmail.com\n\n-- \nAdam Lee\n\n\n", "msg_date": "Thu, 22 Aug 2019 17:54:47 +0800", "msg_from": "Adam Lee <ali@pivotal.io>", "msg_from_op": false, "msg_subject": "Re: Take skip header out of a loop in COPY FROM" }, { "msg_contents": "On 22/08/2019 12:54, Adam Lee wrote:\n> My next thought is to call unlikely() here, but we don't have it...\n> https://www.postgresql.org/message-id/CABRT9RC-AUuQL6txxsoOkLxjK1iTpyexpbizRF4Zxny1GXASGg%40mail.gmail.com\n\nWe do, actually, since commit aa3ca5e3dd in v10.\n\nNot sure it's worth the trouble here. Optimizing COPY in general would \nbe good, even small speedups there are helpful because everyone uses \nCOPY, but without some evidence I don't believe particular branch is \neven measurable.\n\n- Heikki\n\n\n", "msg_date": "Thu, 22 Aug 2019 13:04:14 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Take skip header out of a loop in COPY FROM" }, { "msg_contents": "Heikki Linnakangas <hlinnaka@iki.fi> writes:\n> On 22/08/2019 12:54, Adam Lee wrote:\n>> My next thought is to call unlikely() here, but we don't have it...\n\n> We do, actually, since commit aa3ca5e3dd in v10.\n\n> Not sure it's worth the trouble here. Optimizing COPY in general would \n> be good, even small speedups there are helpful because everyone uses \n> COPY, but without some evidence I don't believe particular branch is \n> even measurable.\n\nI concur that there's no reason to think that this if-test has a\nmeasurable performance cost. We're about to do CopyReadLine which\ncertainly has way more than one branch's worth of processing in it.\n\nIf we want to get involved with sprinkling unlikely() calls into\ncopy.c, the inner per-character or per-field loops would be the\nplace to look for wins IMO.\n\nI'm going to mark this CF entry as Returned With Feedback.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 24 Sep 2019 14:04:04 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Take skip header out of a loop in COPY FROM" } ]
[ { "msg_contents": "Hello hackers,\r\n\r\nOne of the area that didn't get much attention in the community\r\nrecently is analysing and increasing the code coverage of \r\nPostgreSQL regession test suite. I have started working on the\r\ncode coverage by running the GCOV code coverage analysis tool in\r\norder to analyse the current code coverage and come up with test\r\ncases to increase the code coverage. This is going to be a long\r\nexercise so my plan is do it incrementaly. I will be analysing\r\nsome area of untested code and then coming up with test cases to\r\ntest those lines of code in regression and then moving on next\r\narea of untested code and so on.\r\n\r\nSo far I have come up with 3 test cases to increase the code\r\ncoverage of PostgreSQL regression test suite.\r\n\r\nI have performed the regression run for this exercise on this commit:\r\n(Commit version 75c1921cd6c868c5995b88113b4463a4830b9a27):\r\n\r\nThe regression is executed with make check-world command and the\r\nresults are gathered using 'make coverage-html' command. \r\n\r\nBelow are the lines of untested code that i have analysed and the\r\ntest cases added to regression to test these as part of regression.\r\n\r\n1. src/include/utils/float.h:140\r\n\r\nAnalyze: \r\nThis is an error report line when converting a big float8 value\r\nwhich a float4 can not storage to float4.\r\n\r\nTest case:\r\nAdd a test case as below in file float4.sql:\r\nselect float4(1234567890123456789012345678901234567890::float8);\r\n\r\n2. src/include/utils/float.h:145\r\n\r\nAnalyze:\r\nThis is an error report line when converting a small float8 value\r\nwhich a float4 can not storage to float4.\r\n\r\nTest case:\r\nAdd a test case as below in file float4.sql:\r\nselect float4(0.0000000000000000000000000000000000000000000001::float8);\r\n\r\n3.src/include/utils/sortsupport.h:264\r\n\r\nAnalyze:\r\nIt is reverse sorting for the data type that has abbreviated for\r\nsort, for example macaddr, uuid, numeric, network and I choose\r\nnumeric to do it.\r\n\r\nTest cast:\r\nAdd a test case as below in file numeric.sql:\r\nINSERT INTO num_input_test(n1) values('99999999999999999999999999.998');\r\nINSERT INTO num_input_test(n1) values('99999999999999999999999999.997');\r\nSELECT * FROM num_input_test ORDER BY n1 DESC;\r\n\r\nResult and patch\r\n\r\nBy adding the test cases, the test coverage of float.h increased from\r\n97.7% to 100% and sortsupport.h increased from 76.7% to 80.0%.\r\n \r\nThe increase in code coverage can be seen in the before and after\r\npictures of GCOV test coverage analysis summary.\r\n\r\nThe attached patch contain the test cases added in regression for\r\nincreasing the coverage.\r\n\r\n\r\n--\r\nMovead Li", "msg_date": "Thu, 22 Aug 2019 17:46:38 +0800", "msg_from": "\"movead.li@highgo.ca\" <movead.li@highgo.ca>", "msg_from_op": true, "msg_subject": "Email to hackers for test coverage" }, { "msg_contents": "The subject of the email may be bit misleading however this is really good\nexercise to analyse the current code of Postgres regression suite using\nGCOV and then adding test cases incrementally to increase the test\ncoverage.\n\nOn Thu, 22 Aug 2019 at 2:46 PM, movead.li@highgo.ca <movead.li@highgo.ca>\nwrote:\n\n> Hello hackers,\n>\n> One of the area that didn't get much attention in the community\n> recently is analysing and increasing the code coverage of\n> PostgreSQL regession test suite. I have started working on the\n> code coverage by running the GCOV code coverage analysis tool in\n> order to analyse the current code coverage and come up with test\n> cases to increase the code coverage. This is going to be a long\n> exercise so my plan is do it incrementaly. I will be analysing\n> some area of untested code and then coming up with test cases to\n> test those lines of code in regression and then moving on next\n> area of untested code and so on.\n>\n> So far I have come up with 3 test cases to increase the code\n> coverage of PostgreSQL regression test suite.\n>\n> I have performed the regression run for this exercise on this commit:\n> (Commit version 75c1921cd6c868c5995b88113b4463a4830b9a27):\n>\n> The regression is executed with make check-world command and the\n> results are gathered using 'make coverage-html' command.\n>\n> Below are the lines of untested code that i have analysed and the\n> test cases added to regression to test these as part of regression.\n>\n> *1. src/include/utils/float.h:140*\n>\n> Analyze:\n> This is an error report line when converting a big float8 value\n> which a float4 can not storage to float4.\n>\n> Test case:\n> Add a test case as below in file float4.sql:\n> select float4(1234567890123456789012345678901234567890::float8);\n>\n> *2. src/include/utils/float.h:145*\n>\n> Analyze:\n> This is an error report line when converting a small float8 value\n> which a float4 can not storage to float4.\n>\n> Test case:\n> Add a test case as below in file float4.sql:\n> select float4(0.0000000000000000000000000000000000000000000001::float8);\n>\n> *3.src/include/utils/sortsupport.h:264*\n>\n> Analyze:\n> It is reverse sorting for the data type that has abbreviated for\n> sort, for example macaddr, uuid, numeric, network and I choose\n> numeric to do it.\n>\n> Test cast:\n> Add a test case as below in file numeric.sql:\n> INSERT INTO num_input_test(n1) values('99999999999999999999999999.998');\n> INSERT INTO num_input_test(n1) values('99999999999999999999999999.997');\n> SELECT * FROM num_input_test ORDER BY n1 DESC;\n>\n> Result and patch\n>\n> By adding the test cases, the test coverage of float.h increased from\n> 97.7% to 100% and sortsupport.h increased from 76.7% to 80.0%.\n>\n> The increase in code coverage can be seen in the before and after\n> pictures of GCOV test coverage analysis summary.\n>\n> The attached patch contain the test cases added in regression for\n> increasing the coverage.\n>\n>\n> --\n> Movead Li\n>\n\nThe subject of the email may be bit misleading however this is really good exercise to analyse the current code of Postgres regression suite using GCOV and then adding test cases incrementally to increase the test coverage. On Thu, 22 Aug 2019 at 2:46 PM, movead.li@highgo.ca <movead.li@highgo.ca> wrote:\nHello hackers,One of the area that didn't get much attention in the communityrecently is analysing and increasing the code coverage of PostgreSQL regession test suite. I have started working on thecode coverage by running the GCOV code coverage analysis tool inorder to analyse the current code coverage and come up with testcases to increase the code coverage. This is going to be a longexercise so my plan is do it incrementaly. I will be analysingsome area of untested code and then coming up with test cases totest those lines of code in regression and then moving on nextarea of untested code and so on.So far I have come up with 3 test cases to increase the codecoverage of PostgreSQL regression test suite.I have performed the regression run for this exercise on this commit:(Commit version 75c1921cd6c868c5995b88113b4463a4830b9a27):The regression is executed with make check-world command and theresults are gathered using  'make coverage-html' command. Below are the lines of untested code that i have analysed and thetest cases added to regression to test these as part of regression.1. src/include/utils/float.h:140Analyze: This is an error report line when converting a big float8 valuewhich a float4 can not storage to float4.Test case:Add a test case as below in file float4.sql:select float4(1234567890123456789012345678901234567890::float8);2. src/include/utils/float.h:145Analyze:This is an error report line when converting a small float8 valuewhich a float4 can not storage to float4.Test case:Add a test case as below in file float4.sql:select float4(0.0000000000000000000000000000000000000000000001::float8);3.src/include/utils/sortsupport.h:264Analyze:It is reverse sorting for the data type that has abbreviated forsort, for example macaddr, uuid, numeric, network and I choosenumeric to do it.Test cast:Add a test case as below in file numeric.sql:INSERT INTO num_input_test(n1) values('99999999999999999999999999.998');INSERT INTO num_input_test(n1) values('99999999999999999999999999.997');SELECT * FROM num_input_test ORDER BY n1 DESC;Result and patchBy adding the test cases, the test coverage of  float.h increased from97.7% to 100% and sortsupport.h increased from 76.7% to 80.0%. The increase in code coverage can be seen in the before and afterpictures of GCOV test coverage analysis summary.The attached patch contain the test cases added in regression forincreasing the coverage.--Movead Li", "msg_date": "Sat, 24 Aug 2019 00:19:52 +0500", "msg_from": "Ahsan Hadi <ahsan.hadi@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Email to hackers for test coverage" }, { "msg_contents": "On Thu, Aug 22, 2019 at 2:46 PM movead.li@highgo.ca <movead.li@highgo.ca>\nwrote:\n\n> Hello hackers,\n>\n> One of the area that didn't get much attention in the community\n> recently is analysing and increasing the code coverage of\n> PostgreSQL regession test suite. I have started working on the\n> code coverage by running the GCOV code coverage analysis tool in\n> order to analyse the current code coverage and come up with test\n> cases to increase the code coverage. This is going to be a long\n> exercise so my plan is do it incrementaly. I will be analysing\n> some area of untested code and then coming up with test cases to\n> test those lines of code in regression and then moving on next\n> area of untested code and so on.\n>\n> So far I have come up with 3 test cases to increase the code\n> coverage of PostgreSQL regression test suite.\n>\n> I have performed the regression run for this exercise on this commit:\n> (Commit version 75c1921cd6c868c5995b88113b4463a4830b9a27):\n>\n> The regression is executed with make check-world command and the\n> results are gathered using 'make coverage-html' command.\n>\n> Below are the lines of untested code that i have analysed and the\n> test cases added to regression to test these as part of regression.\n>\n> *1. src/include/utils/float.h:140*\n>\n> Analyze:\n> This is an error report line when converting a big float8 value\n> which a float4 can not storage to float4.\n>\n> Test case:\n> Add a test case as below in file float4.sql:\n> select float4(1234567890123456789012345678901234567890::float8);\n>\n> *2. src/include/utils/float.h:145*\n>\n> Analyze:\n> This is an error report line when converting a small float8 value\n> which a float4 can not storage to float4.\n>\n> Test case:\n> Add a test case as below in file float4.sql:\n> select float4(0.0000000000000000000000000000000000000000000001::float8);\n>\n> *3.src/include/utils/sortsupport.h:264*\n>\n> Analyze:\n> It is reverse sorting for the data type that has abbreviated for\n> sort, for example macaddr, uuid, numeric, network and I choose\n> numeric to do it.\n>\n> Test cast:\n> Add a test case as below in file numeric.sql:\n> INSERT INTO num_input_test(n1) values('99999999999999999999999999.998');\n> INSERT INTO num_input_test(n1) values('99999999999999999999999999.997');\n> SELECT * FROM num_input_test ORDER BY n1 DESC;\n>\n> Result and patch\n>\n> By adding the test cases, the test coverage of float.h increased from\n> 97.7% to 100% and sortsupport.h increased from 76.7% to 80.0%.\n>\n> The increase in code coverage can be seen in the before and after\n> pictures of GCOV test coverage analysis summary.\n>\n> The attached patch contain the test cases added in regression for\n> increasing the coverage.\n>\n>\n> --\n> Movead Li\n>\n\nHi Movead,\nPlease add that to commitfest.\n\n\n\n-- \nIbrar Ahmed\n\nOn Thu, Aug 22, 2019 at 2:46 PM movead.li@highgo.ca <movead.li@highgo.ca> wrote:\nHello hackers,One of the area that didn't get much attention in the communityrecently is analysing and increasing the code coverage of PostgreSQL regession test suite. I have started working on thecode coverage by running the GCOV code coverage analysis tool inorder to analyse the current code coverage and come up with testcases to increase the code coverage. This is going to be a longexercise so my plan is do it incrementaly. I will be analysingsome area of untested code and then coming up with test cases totest those lines of code in regression and then moving on nextarea of untested code and so on.So far I have come up with 3 test cases to increase the codecoverage of PostgreSQL regression test suite.I have performed the regression run for this exercise on this commit:(Commit version 75c1921cd6c868c5995b88113b4463a4830b9a27):The regression is executed with make check-world command and theresults are gathered using  'make coverage-html' command. Below are the lines of untested code that i have analysed and thetest cases added to regression to test these as part of regression.1. src/include/utils/float.h:140Analyze: This is an error report line when converting a big float8 valuewhich a float4 can not storage to float4.Test case:Add a test case as below in file float4.sql:select float4(1234567890123456789012345678901234567890::float8);2. src/include/utils/float.h:145Analyze:This is an error report line when converting a small float8 valuewhich a float4 can not storage to float4.Test case:Add a test case as below in file float4.sql:select float4(0.0000000000000000000000000000000000000000000001::float8);3.src/include/utils/sortsupport.h:264Analyze:It is reverse sorting for the data type that has abbreviated forsort, for example macaddr, uuid, numeric, network and I choosenumeric to do it.Test cast:Add a test case as below in file numeric.sql:INSERT INTO num_input_test(n1) values('99999999999999999999999999.998');INSERT INTO num_input_test(n1) values('99999999999999999999999999.997');SELECT * FROM num_input_test ORDER BY n1 DESC;Result and patchBy adding the test cases, the test coverage of  float.h increased from97.7% to 100% and sortsupport.h increased from 76.7% to 80.0%. The increase in code coverage can be seen in the before and afterpictures of GCOV test coverage analysis summary.The attached patch contain the test cases added in regression forincreasing the coverage.--Movead LiHi Movead,Please add that to commitfest. -- Ibrar Ahmed", "msg_date": "Sat, 24 Aug 2019 00:43:27 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Email to hackers for test coverage" }, { "msg_contents": ">Hi Movead,\r\n>Please add that to commitfest.\r\n\r\nThanks and I just do it, it is\r\nhttps://commitfest.postgresql.org/24/2258/\r\n\r\n--\r\nMovead Li\r\n\n\n>Hi Movead,>Please add that to commitfest.Thanks and I just do it, it ishttps://commitfest.postgresql.org/24/2258/--Movead Li", "msg_date": "Sat, 24 Aug 2019 23:23:32 +0800", "msg_from": "\"movead.li@highgo.ca\" <movead.li@highgo.ca>", "msg_from_op": true, "msg_subject": "Re: Re: Email to hackers for test coverage" }, { "msg_contents": "On Sat, Aug 24, 2019 at 11:23:32PM +0800, movead.li@highgo.ca wrote:\n> Thanks and I just do it, it is\n> https://commitfest.postgresql.org/24/2258/\n\nYour patch has forgotten to update the alternate output in\nfloat4-misrounded-input.out.\n--\nMichael", "msg_date": "Mon, 26 Aug 2019 13:48:40 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Re: Email to hackers for test coverage" }, { "msg_contents": "On Mon, 26 Aug 2019 12:48:40 +0800 michael@paquier.xyz wrote\r\n>Your patch has forgotten to update the alternate output in\r\n>float4-misrounded-input.out.\r\n\r\nThanks for your remind, I have modified the patch and now it is \r\n'regression_20190826.patch' in attachment, and I have done a successful\r\ntest on Cygwin.\r\n\r\n--\r\nMovead", "msg_date": "Mon, 26 Aug 2019 17:10:59 +0800", "msg_from": "\"movead.li@highgo.ca\" <movead.li@highgo.ca>", "msg_from_op": true, "msg_subject": "Re: Re: Email to hackers for test coverage" }, { "msg_contents": "On Mon, Aug 26, 2019 at 05:10:59PM +0800, movead.li@highgo.ca wrote:\n> Thanks for your remind, I have modified the patch and now it is \n> 'regression_20190826.patch' in attachment, and I have done a successful\n> test on Cygwin.\n\nThere is a section in float4.sql which deals with overflow and\nunderflow, so wouldn't it be better to move the tests there? You\ncould just trigger the failures with that:\n=# insert into float4_tbl values ('-10e-70'::float8);\nERROR: 22003: value out of range: underflow\nLOCATION: check_float4_val, float.h:145\n=# insert into float4_tbl values ('-10e70'::float8);\nERROR: 22003: value out of range: overflow\nLOCATION: check_float4_val, float.h:140\n\nI would also test all four patterns: 10e70, 10e-70, -10e70, -10e-70.\n\nFor the numeric part, this improves the case of\nApplySortAbbrevFullComparator() where both values are not NULL. Could\nthings be done so as the other code paths are fully covered? One\nINSERT is fine by the way to add the extra coverage.\n--\nMichael", "msg_date": "Tue, 27 Aug 2019 15:07:48 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Re: Email to hackers for test coverage" }, { "msg_contents": "On Tue, 27 Aug 2019 14:07:48 +0800 michael@paquier.xyz wrote:\r\n> There is a section in float4.sql which deals with overflow and\r\n> underflow, so wouldn't it be better to move the tests there? You \r\n> could just trigger the failures with that: \r\n> =# insert into float4_tbl values ('-10e-70'::float8); \r\n> ERROR: 22003: value out of range: underflow \r\n> LOCATION: check_float4_val, float.h:145 \r\n> =# insert into float4_tbl values ('-10e70'::float8); \r\n> ERROR: 22003: value out of range: overflow \r\n> LOCATION: check_float4_val, float.h:140 \r\n> I would also test all four patterns: 10e70, 10e-70, -10e70, -10e-70.\r\n \r\nI think your way is much better, so I change the patch and it is \r\n'regression_20190827.patch' now.\r\n\r\n> For the numeric part, this improves the case of\r\n> ApplySortAbbrevFullComparator() where both values are not NULL. Could\r\n> things be done so as the other code paths are fully covered? One\r\n> INSERT is fine by the way to add the extra coverage.\r\nThere are code lines related to NULL values in\r\nApplySortAbbrevFullComparator(), but I think the code lines for\r\ncomparing a NULL and a NOT NULL can be never reached, because it is\r\nhandled in ApplySortComparator() which is called before\r\nApplySortAbbrevFullComparator(). So I think it is no use to INSERT\r\na NULL value.\r\n\r\n--\r\nMovead", "msg_date": "Tue, 27 Aug 2019 15:57:20 +0800", "msg_from": "\"movead.li@highgo.ca\" <movead.li@highgo.ca>", "msg_from_op": true, "msg_subject": "Re: Re: Email to hackers for test coverage" }, { "msg_contents": "On Tue, Aug 27, 2019 at 03:57:20PM +0800, movead.li@highgo.ca wrote:\n> I think your way is much better, so I change the patch and it is \n> 'regression_20190827.patch' now.\n\nThanks for the new patch, I have committed the part for float4.\n\n> There are code lines related to NULL values in\n> ApplySortAbbrevFullComparator(), but I think the code lines for\n> comparing a NULL and a NOT NULL can be never reached, because it is\n> handled in ApplySortComparator() which is called before\n> ApplySortAbbrevFullComparator(). So I think it is no use to INSERT\n> a NULL value.\n\nBut I am not sold to that part yet, for three reasons:\n- numeric is not a test suite designed for sorting, and hijacking it\nto do so it not a good approach.\n- it would be good to get coverage for the two extra code paths while\nwe are on it with NULL datums.\n- There is no need for two INSERT queries, I am getting the same\ncoverage with only one.\n\nPlease note that I have not looked in details where we could put that,\nbut perhaps Robert and Peter G who worked on 4ea51cd to add support\nfor abbreviated keys have some ideas, so I am adding them in CC for\ninput.\n--\nMichael", "msg_date": "Wed, 28 Aug 2019 12:30:23 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Re: Email to hackers for test coverage" }, { "msg_contents": "On Wed, 28 Aug 2019 11:30:23 +0800 michael@paquier.xyz wrote\r\n>- numeric is not a test suite designed for sorting, and hijacking it\r\n>to do so it not a good approach.\r\nAbsolutely agreement. We can wait for repling from\r\nRobert and Peter G.\r\n\r\n>- it would be good to get coverage for the two extra code paths while\r\n>we are on it with NULL datums.\r\nThe remained untested line in ApplySortComparator() can be never\r\nreached I think, and I have explained it on last mail. \r\nOr I don't fully understand what you mean?\r\n \r\n>- There is no need for two INSERT queries, I am getting the same\r\n>coverage with only one.\r\nYes It is my mistake, the key point is 'ORDER BY n1 DESC' not the \r\n'INSERT'. Infact it can run the code line without any of the two INSERT.\r\n\r\n--\r\nMovead\r\n\n\nOn Wed, 28 Aug 2019 11:30:23 +0800 michael@paquier.xyz wrote\n>- numeric is not a test suite designed for sorting, and hijacking it\n>to do so it not a good approach.Absolutely agreement. We can wait for repling fromRobert and Peter G.\n>- it would be good to get coverage for the two extra code paths while\n>we are on it with NULL datums..The remained untested line in ApplySortComparator() can be neverreached I think, and I have explained it on last mail. Or I don't fully understand what you mean? \n>- There is no need for two INSERT queries, I am getting the same\n>coverage with only one.\nYes It is my mistake,  the key point is 'ORDER BY n1 DESC' not the 'INSERT'. Infact it can run the code line without any of the two INSERT.\n--\nMovead", "msg_date": "Wed, 28 Aug 2019 14:48:39 +0800", "msg_from": "\"movead.li@highgo.ca\" <movead.li@highgo.ca>", "msg_from_op": true, "msg_subject": "Re: Re: Email to hackers for test coverage" }, { "msg_contents": "On 2019-08-22 11:46, movead.li@highgo.ca wrote:\n> *1. src/include/utils/float.h:140*\n> \n> Analyze:�\n> This is an error report line when converting a big float8 value\n> which a float4 can not storage to float4.\n> \n> Test case:\n> Add a test case as below in file float4.sql:\n> select float4(1234567890123456789012345678901234567890::float8);\n\n> +-- Add test case for float4() type fonversion function\n\nCheck spelling\n\n> *2. src/include/utils/float.h:145*\n> \n> Analyze:\n> This is an error report line when converting a small float8 value\n> which a float4 can not storage to float4.\n> \n> Test case:\n> Add a test case as below in file float4.sql:\n> select float4(0.0000000000000000000000000000000000000000000001::float8);\n> \n> *3.src/include/utils/sortsupport.h:264*\n> \n> Analyze:\n> It is reverse sorting for the data type that has abbreviated for\n> sort, for example macaddr, uuid, numeric, network and I choose\n> numeric to do it.\n> \n> Test cast:\n> Add a test case as below in file numeric.sql:\n> INSERT INTO num_input_test(n1) values('99999999999999999999999999.998');\n> INSERT INTO num_input_test(n1) values('99999999999999999999999999.997');\n> SELECT * FROM num_input_test ORDER BY n1 DESC;\n\n> INSERT INTO num_input_test(n1) VALUES (' nan');\n> +INSERT INTO num_input_test(n1) values('99999999999999999999999999.998');\n> +INSERT INTO num_input_test(n1) values('99999999999999999999999999.997');\n\nMake spaces and capitalization match surrounding code.\n\n> Result and patch\n> \n> By adding the test cases, the test coverage of �float.h increased from\n> 97.7% to 100% and sortsupport.h increased from 76.7% to 80.0%.\n\nThat's fine, but I suggest that if you really want to make an impact in\ntest coverage, look to increase function coverage rather than line\ncoverage. Or look for files that are not covered at all.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 28 Aug 2019 18:43:10 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Email to hackers for test coverage" }, { "msg_contents": "On Tue, Aug 27, 2019 at 8:30 PM Michael Paquier <michael@paquier.xyz> wrote:\n> Please note that I have not looked in details where we could put that,\n> but perhaps Robert and Peter G who worked on 4ea51cd to add support\n> for abbreviated keys have some ideas, so I am adding them in CC for\n> input.\n\nMovead is correct -- the NULL handling within\nApplySortAbbrevFullComparator() cannot actually be used currently. I\nwouldn't change anything about the code, though, since it's useful to\ndefensively handle NULLs.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Wed, 28 Aug 2019 11:27:15 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Re: Email to hackers for test coverage" }, { "msg_contents": "On 2019-08-29 00:43, peter.eisentraut@2ndquadrant.com wrote:\r\n \r\n \r\n> Make spaces and capitalization match surrounding code.\r\n>That's fine, but I suggest that if you really want to make an impact in\r\n>test coverage, look to increase function coverage rather than line\r\n>coverage. Or look for files that are not covered at all.\r\n \r\nThanks for pointing all the things, I will reconsider my way on\r\ncode coverage work.\r\n\r\n-- \r\nMovead\r\n\n\nOn 2019-08-29 00:43, peter.eisentraut@2ndquadrant.com wrote:\n \n \n> Make spaces and capitalization match surrounding code..\n>That's fine, but I suggest that if you really want to make an impact in\n>test coverage, look to increase function coverage rather than line\n>coverage.  Or look for files that are not covered at all.\n Thanks for pointing all the things, I will reconsider my way oncode coverage work.\n-- \nMovead", "msg_date": "Thu, 29 Aug 2019 09:14:49 +0800", "msg_from": "\"movead.li@highgo.ca\" <movead.li@highgo.ca>", "msg_from_op": true, "msg_subject": "Re: Re: Email to hackers for test coverage" }, { "msg_contents": "On Wed, Aug 28, 2019 at 9:43 PM Peter Eisentraut <\npeter.eisentraut@2ndquadrant.com> wrote:\n\n> On 2019-08-22 11:46, movead.li@highgo.ca wrote:\n> > *1. src/include/utils/float.h:140*\n> >\n> > Analyze:\n> > This is an error report line when converting a big float8 value\n> > which a float4 can not storage to float4.\n> >\n> > Test case:\n> > Add a test case as below in file float4.sql:\n> > select float4(1234567890123456789012345678901234567890::float8);\n>\n> > +-- Add test case for float4() type fonversion function\n>\n> Check spelling\n>\n> > *2. src/include/utils/float.h:145*\n> >\n> > Analyze:\n> > This is an error report line when converting a small float8 value\n> > which a float4 can not storage to float4.\n> >\n> > Test case:\n> > Add a test case as below in file float4.sql:\n> > select float4(0.0000000000000000000000000000000000000000000001::float8);\n> >\n> > *3.src/include/utils/sortsupport.h:264*\n> >\n> > Analyze:\n> > It is reverse sorting for the data type that has abbreviated for\n> > sort, for example macaddr, uuid, numeric, network and I choose\n> > numeric to do it.\n> >\n> > Test cast:\n> > Add a test case as below in file numeric.sql:\n> > INSERT INTO num_input_test(n1) values('99999999999999999999999999.998');\n> > INSERT INTO num_input_test(n1) values('99999999999999999999999999.997');\n> > SELECT * FROM num_input_test ORDER BY n1 DESC;\n>\n> > INSERT INTO num_input_test(n1) VALUES (' nan');\n> > +INSERT INTO num_input_test(n1) values('99999999999999999999999999.998');\n> > +INSERT INTO num_input_test(n1) values('99999999999999999999999999.997');\n>\n> Make spaces and capitalization match surrounding code.\n>\n> > Result and patch\n> >\n> > By adding the test cases, the test coverage of float.h increased from\n> > 97.7% to 100% and sortsupport.h increased from 76.7% to 80.0%.\n>\n> That's fine, but I suggest that if you really want to make an impact in\n> test coverage, look to increase function coverage rather than line\n> coverage. Or look for files that are not covered at all.\n>\n>\n+1\n\n\n> --\n> Peter Eisentraut http://www.2ndQuadrant.com/\n> PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n>\n>\n>\n\nOn Wed, Aug 28, 2019 at 9:43 PM Peter Eisentraut <peter.eisentraut@2ndquadrant.com> wrote:On 2019-08-22 11:46, movead.li@highgo.ca wrote:\n> *1. src/include/utils/float.h:140*\n> \n> Analyze: \n> This is an error report line when converting a big float8 value\n> which a float4 can not storage to float4.\n> \n> Test case:\n> Add a test case as below in file float4.sql:\n> select float4(1234567890123456789012345678901234567890::float8);\n\n> +-- Add test case for float4() type fonversion function\n\nCheck spelling\n\n> *2. src/include/utils/float.h:145*\n> \n> Analyze:\n> This is an error report line when converting a small float8 value\n> which a float4 can not storage to float4.\n> \n> Test case:\n> Add a test case as below in file float4.sql:\n> select float4(0.0000000000000000000000000000000000000000000001::float8);\n> \n> *3.src/include/utils/sortsupport.h:264*\n> \n> Analyze:\n> It is reverse sorting for the data type that has abbreviated for\n> sort, for example macaddr, uuid, numeric, network and I choose\n> numeric to do it.\n> \n> Test cast:\n> Add a test case as below in file numeric.sql:\n> INSERT INTO num_input_test(n1) values('99999999999999999999999999.998');\n> INSERT INTO num_input_test(n1) values('99999999999999999999999999.997');\n> SELECT * FROM num_input_test ORDER BY n1 DESC;\n\n>  INSERT INTO num_input_test(n1) VALUES ('        nan');\n> +INSERT INTO num_input_test(n1) values('99999999999999999999999999.998');\n> +INSERT INTO num_input_test(n1) values('99999999999999999999999999.997');\n\nMake spaces and capitalization match surrounding code.\n\n> Result and patch\n> \n> By adding the test cases, the test coverage of  float.h increased from\n> 97.7% to 100% and sortsupport.h increased from 76.7% to 80.0%.\n\nThat's fine, but I suggest that if you really want to make an impact in\ntest coverage, look to increase function coverage rather than line\ncoverage.  Or look for files that are not covered at all.\n+1  \n-- \nPeter Eisentraut              http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Thu, 29 Aug 2019 16:47:31 +0500", "msg_from": "Ahsan Hadi <ahsan.hadi@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Email to hackers for test coverage" }, { "msg_contents": "On Wed, Aug 28, 2019 at 11:27:15AM -0700, Peter Geoghegan wrote:\n> Movead is correct -- the NULL handling within\n> ApplySortAbbrevFullComparator() cannot actually be used currently. I\n> wouldn't change anything about the code, though, since it's useful to\n> defensively handle NULLs.\n\nNo objections with this line of thoughts. Thanks, Peter. Please note\nthat I have marked the original patch as committed in the CF app. If\nthere are tests to improve the coverage, let's do that on a new\nthread. I am still not sure where I would put tests dedicated to\nabbreviated keys, but let's sort out that if necessary later.\n--\nMichael", "msg_date": "Wed, 4 Sep 2019 13:36:52 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Re: Email to hackers for test coverage" } ]
[ { "msg_contents": "Hello\n\nFault injection was discussed a few months ago at PGCon in Ottawa. At\nleast a few folks showed interest and so I would like to present what we\nhave been using in Greenplum.\n\nThe attached patch set contains the fault injector framework ported to\nPostgreSQL master. It provides ability to define points of interest in\nbackend code and then inject faults at those points from SQL. Also\nincluded is an isolation test to simulate a speculative insert conflict\nscenario that was found to be rather cumbersome to implement using advisory\nlocks, see [1]. The alternative isolation spec using fault injectors seems\nmuch simpler to understand.\n\nAsim\n\n[1] CAAKRu_a7hbyrk=wveHYhr4LbcRnRCG=yPUVoQYB9YO1CdUBE9Q@mail.gmail.com\n<https://www.postgresql.org/message-id/CAAKRu_a7hbyrk%3DwveHYhr4LbcRnRCG%3DyPUVoQYB9YO1CdUBE9Q%40mail.gmail.com>", "msg_date": "Thu, 22 Aug 2019 19:45:09 +0530", "msg_from": "Asim R P <apraveen@pivotal.io>", "msg_from_op": true, "msg_subject": "Fault injection framework" }, { "msg_contents": "On Thu, Aug 22, 2019 at 07:45:09PM +0530, Asim R P wrote:\n> Fault injection was discussed a few months ago at PGCon in Ottawa. At\n> least a few folks showed interest and so I would like to present what we\n> have been using in Greenplum.\n> \n> The attached patch set contains the fault injector framework ported to\n> PostgreSQL master. It provides ability to define points of interest in\n> backend code and then inject faults at those points from SQL. Also\n> included is an isolation test to simulate a speculative insert conflict\n> scenario that was found to be rather cumbersome to implement using advisory\n> locks, see [1]. The alternative isolation spec using fault injectors seems\n> much simpler to understand.\n\nYou may want to double-check whitespaces in your patch set, and 0002\ndoes not apply because of conflicts in isolationtester.h (my fault!).\n\n0002 is an independent feature, so I would keep it out of the fault\nframework for integration. There has been a argument from Alvaro\nmore convincing than mine about the use of a separate keyword, hence\nremoving a dependency with steps:\nhttps://www.postgresql.org/message-id/20190823153825.GA11405@alvherre.pgsql\n\nIt would be good also to have a test case which exercises it, without\nthe need of the fault framework or its dedicated schedule.\n\nPatches 0003, 0004 and 0005 could just be grouped together, they deal\nabout the same thing.\n\nMy first impressions about this patch is that it is very intrusive.\nCould you explain the purpose of am_faultinjector? That's a specific\nconnection string parameter which can be used similarly to replication\nfor WAL senders? Couldn't there be an equivalent with a SUSET GUC?\nIt may be interesting to see which parts of this framework could be\nmoved into an extension loaded with shared_preload_libraries, one\nthing being the shared memory initialization part. At the end it\nwould be interesting to not have a dependency with a compile-time\nflag.\n\nThings like exec_fault_injector_command() need to be more documented.\nIt is hard to guess what it is being used for.\n--\nMichael", "msg_date": "Tue, 27 Aug 2019 16:04:48 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Fault injection framework" }, { "msg_contents": "On Tue, Aug 27, 2019 at 12:35 PM Michael Paquier <michael@paquier.xyz>\nwrote:\n>\n> You may want to double-check whitespaces in your patch set, and 0002\n> does not apply because of conflicts in isolationtester.h (my fault!).\n>\n\nI've rebased the patch set against the latest master and tried to resolve\nwhitespace issues. Apologies for the whitespace conflicts, I tried\nresolving them but there is some trailing whitespace in the answer file of\nthe regress test in v1-0001 that cannot be removed, else the test will fail.\n\n> 0002 is an independent feature, so I would keep it out of the fault\n> framework for integration. There has been a argument from Alvaro\n> more convincing than mine about the use of a separate keyword, hence\n> removing a dependency with steps:\n>\nhttps://www.postgresql.org/message-id/20190823153825.GA11405@alvherre.pgsql\n>\n\nThat is a valid point, thank you Alvaro for the feedback. I've changed\n0002 so that a step within a permutation can be declared as blocking,\nrevised patch set is attached.\n\n> It would be good also to have a test case which exercises it, without\n> the need of the fault framework or its dedicated schedule.\n>\n\nIt is for this reason that I have not separated patch 0002 out from\nfaultinjector patch set because the test to demonstrate the blocking\nfeature uses faults. I need to give more thought to find a test having a\nsession that needs to block for reasons other than locking. Any pointers\nwill be very helpful.\n\n>\n> My first impressions about this patch is that it is very intrusive.\n> Could you explain the purpose of am_faultinjector? That's a specific\n> connection string parameter which can be used similarly to replication\n> for WAL senders? Couldn't there be an equivalent with a SUSET GUC?\n\nThank you for the review. Admittedly, the patch set doesn't include a test\nto demonstrate am_faultinjector. That is used when a fault needs to be\ninjected into a remote server, say a standby. And that standby may be\naccepting connections or not, depending on if it's operating in hot-standby\nmode. Therefore, the am_faultinjector and the connection parameter is used\nto identify fault injection requests and allow those to be handled even\nwhen normal user connections are not allowed. Also, such connections do\nnot need to be associated with a database, they simply need to set the\nfault in the shared memory hash table. In that sense, fault injection\nconnections are treated similar to replication connections.\n\nI was looking into tests under src/test/recovery/t/. Let me write a test\nto demonstrate what I'm trying to explain above.\n\n> It may be interesting to see which parts of this framework could be\n> moved into an extension loaded with shared_preload_libraries, one\n> thing being the shared memory initialization part. At the end it\n> would be interesting to not have a dependency with a compile-time\n> flag.\n\nPatch 0001 includes an extension that provides a SQL UDF as a wrapper over\nthe fault injection interface in backend. Moving the backend part of the\npatch also into an extension seems difficult to me. Getting rid of the\ncompile time dependency is a strong enough advantage to spend more efforts\non this.\n\n>\n> Things like exec_fault_injector_command() need to be more documented.\n> It is hard to guess what it is being used for.\n\nAdded a comment to explain things a bit. Hope that helps. And as\nmentioned above, I'm working on a test case to demonstrate this feature.\n\nAsim", "msg_date": "Tue, 27 Aug 2019 18:57:46 +0530", "msg_from": "Asim R P <apraveen@pivotal.io>", "msg_from_op": true, "msg_subject": "Re: Fault injection framework" }, { "msg_contents": "On Tue, Aug 27, 2019 at 6:57 PM Asim R P <apraveen@pivotal.io> wrote:\n>\n> On Tue, Aug 27, 2019 at 12:35 PM Michael Paquier <michael@paquier.xyz>\nwrote:\n> >\n> > Things like exec_fault_injector_command() need to be more documented.\n> > It is hard to guess what it is being used for.\n>\n> Added a comment to explain things a bit. Hope that helps. And as\nmentioned above, I'm working on a test case to demonstrate this feature.\n>\n\nAfter learning a bit of Perl, I have a TAP test to share. The test\nvalidates that a commit on master waits until a synchronous standby has\nflushed WAL up to or greater than the commit LSN. The test demonstrates\nremote faultinjector interface to inject a fault on standby. That's where\nexec_fault_injector_command() and related code is exercised.\n\nPatch summary:\n0001 - the original fault injector patch up thread with remote fault\ninjection capability\n0006 - TAP test that makes use of the remote fault injector API\nPatches 0002-0005 are not included because they are not changed.\n\nAsim", "msg_date": "Fri, 6 Sep 2019 18:52:51 +0530", "msg_from": "Asim R P <apraveen@pivotal.io>", "msg_from_op": true, "msg_subject": "Re: Fault injection framework" } ]
[ { "msg_contents": "Currently, we fail to do $SUBJECT: post-restore, an extension will\nbe owned by the role used to do the restore. This is because pg_dump\ndoes not consider that extensions have owners at all, so it doesn't\nissue ALTER EXTENSION OWNER TO, which is a command that the server\ndoesn't have anyway.\n\nWe've not gotten complaints about this, AFAIR, suggesting it's only a\nminor problem in practice. Probably most extensions are superuser-owned\nanyway. However, we do theoretically support PL extensions that are\nowned by database owners, and if the \"trustable extension\" idea that\nI proposed yesterday[1] gets in, there might soon be a lot more cases\nof non-superuser-owned extensions. Moreover, although pg_upgrade will\npreserve the ownership of individual objects within the extension,\na regular dump/restore will not. This means a database owner would\nlose the ability to adjust permissions on a PL after dump/restore,\nwhich seems like a problem. So I started thinking about how to fix it.\n\nThe obvious way to fix it is to implement ALTER EXTENSION OWNER TO,\nbut that has a big problem: what should we do with the ownership of\nthe contained objects? Taking the example of one of the PL extensions,\nwe'd like it to also change ownership of the procedural language object,\nbut it *must not* give away ownership of the C-language handler functions,\nat least not if the ownership recipient is not a superuser. (A user who\nowns a C-language function can alter its properties to do almost\nanything.) There doesn't seem to be any way to distinguish these cases\nexcept with very ad-hoc, ugly, restrictive code. I considered proposing\nthat we *only* change ownership of contained procedural language objects,\nbut ick. That's ugly, and it would hobble the usefulness of the\n@extowner@ mechanism I proposed in [1] (although possibly that's not\nvery useful for anything but PLs anyway?).\n\nMaybe, instead of @extowner@ as proposed (which is certainly just a\nquick-n-dirty mechanism), we could add some syntax that would explicitly\nidentify objects whose ownership ought to track that of the extension.\nSeems like a lot of work though.\n\nAnother idea, which is much uglier conceptually but seems like it\ncould be done with not much code, is to teach pg_dump/pg_restore\nthat it must use SET SESSION AUTHORIZATION to set the ownership of\nan extension even when it's using ALTER OWNER for everything else.\nThe main drawback that I can think of is that if the target user\nlacks permissions to create the extension in the destination database,\nCREATE EXTENSION will fail (and then probably later restore commands\nwill too), rather than leaving the extension in place with the wrong\nowner.\n\nI guess, if we're going to need custom restore code anyway,\nwe could imagine solving that problem by emitting\n\nSET SESSION AUTHORIZATION joe;\nCREATE EXTENSION someextension;\nRESET SESSION AUTHORIZATION;\nCREATE EXTENSION IF NOT EXISTS someextension;\n\nbut man is that ugly.\n\nBinary-upgrade mode has an independent problem:\nbinary_upgrade_create_empty_extension has a hard-wired assumption that \nit should use GetUserId() for the extension owner. We could imagine\nfixing that by passing the owner role name as a separate argument;\nthough if we go with the SET SESSION AUTHORIZATION solution for normal\nmode, I'm a bit inclined to use it for binary upgrade as well.\n\nI don't find any of these approaches terribly appealing.\nThoughts, better ideas?\n\n\t\t\tregards, tom lane\n\n[1] https://www.postgresql.org/message-id/5889.1566415762%40sss.pgh.pa.us\n\n\n", "msg_date": "Thu, 22 Aug 2019 15:08:58 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Preserving extension ownership in dump/restore/pg_upgrade" } ]
[ { "msg_contents": "Hello Hackers,\n\nThere is an edge case in 9_5_STABLE (doesn't reproduce 9_6+) we found in how\nbackends handle the TERM signal while handling a USR1 signal that can cause\nthem to infinitely wait. A backend can end up waiting forever inside\nSyncRepWaitForLSN() at:\n\nrc = WaitLatch(MyLatch, WL_LATCH_SET |\nWL_POSTMASTER_DEATH, -1, WAIT_EVENT_SYNC_REP);\n\nEven pg_terminate_backend() would not be able to terminate it after it\nreaches this point.\n\nStack trace:\n\n#0 0x00007f39418d73c8 in poll () from /lib64/libc.so.6\n#1 0x0000000000753d7b in WaitLatchOrSocket (latch=0x7f3940d371cc,\nwakeEvents=17, sock=-1, timeout=-1)\n at pg_latch.c:333\n#2 0x0000000000753b8c in WaitLatch (latch=0x7f3940d371cc, wakeEvents=17,\ntimeout=-1) at pg_latch.c:197\n#3 0x00000000007a0e02 in SyncRepWaitForLSN (XactCommitLSN=167868344) at\nsyncrep.c:231\n#4 0x0000000000518b8a in RecordTransactionCommit () at xact.c:1349\n#5 0x000000000051966d in CommitTransaction () at xact.c:2057\n#6 0x000000000051a1f9 in CommitTransactionCommand () at xact.c:2769\n#7 0x000000000054ff5e in RemoveTempRelationsCallback (code=1, arg=0) at\nnamespace.c:3878\n#8 0x00000000007be3d1 in shmem_exit (code=1) at ipc.c:228\n#9 0x00000000007be2c6 in proc_exit_prepare (code=1) at ipc.c:185\n#10 0x00000000007be234 in proc_exit (code=1) at ipc.c:102\n#11 0x000000000093152e in errfinish (dummy=0) at elog.c:535\n#12 0x00000000007ea492 in ProcessInterrupts () at postgres.c:2913\n#13 0x00000000007e9f93 in die (postgres_signal_arg=15) at postgres.c:2682\n#14 <signal handler called>\n#15 procsignal_sigusr1_handler (postgres_signal_arg=10) at procsignal.c:271\n#16 <signal handler called>\n#17 SocketBackend (inBuf=0x7ffc8dde0f80) at postgres.c:353\n#18 0x00000000007e70ca in ReadCommand (inBuf=0x7ffc8dde0f80) at\npostgres.c:510\n#19 0x00000000007eb990 in PostgresMain (argc=1, argv=0x1708cd0,\ndbname=0x1708b38 \"gpadmin\",\n username=0x1708b18 \"gpadmin\") at postgres.c:4032\n#20 0x0000000000769922 in BackendRun (port=0x172e060) at postmaster.c:4309\n#21 0x0000000000769086 in BackendStartup (port=0x172e060) at\npostmaster.c:3983\n#22 0x00000000007657dc in ServerLoop () at postmaster.c:1706\n#23 0x0000000000764e16 in PostmasterMain (argc=3, argv=0x1707ce0) at\npostmaster.c:1314\n#24 0x00000000006bcdb3 in main (argc=3, argv=0x1707ce0) at main.c:228\n\nRoot cause:\n\nThe reason why the backend waits forever in WaitLatch is that it expects a\nUSR1\nsignal to be delivered in order to wake it up from the wait\n(WaitLatchOrSocket\nimplementation) using latch_sigusr1_handler. Now since its is already\ninside a\nUSR1 handler, USR1 is blocked by default. Thus, it never receives a USR1 and\nnever wakes up.\n\nReproduction: [9_5_STABLE, commit: 5a32fcd]\n\nWe must align the stars as follows:\n\n1. Create a psql session and create a temp table. [temp table forces a Tx\nduring backend termination to drop the table => SyncRepWaitForLSN will be\ncalled]\n\n2. Since, we don't have a fault injection framework, we have to rely on the\ndebugger: Attach to the following processes and install these breakpoints:\n\ni) Attach to the Backend:\nb procsignal_sigusr1_handler\nb postgres.c:353\nat: SocketBackend: ereport(DEBUG1,\n(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),\nerrmsg(\"unexpected EOF on client connection\")));\n\nii) Attach to the Wal Sender, no need for a specific breakpoint [We need to\nmake the Wal Sender fall behind in order for the condition lsn <=\nWalSndCtl->lsn[mode] to be false inside SyncRepWaitForLSN()]\n\n3. kill -9 the psql process [This will send an EOF to the backend's\nconnection\nto the front end, which will cause DoingCommandRead = true and\nwhereToSendOutput = DestNone (in SocketBackend()). This will later ensure\nthat\nProcessInterrupts() is called from within die: the backend's TERM handler]\n\n4. Continue the backend process in the debugger, it should reach the\nbreakpoint\nwe set inside SocketBackend.\n\n5. Send a USR1 to the backend. kill -SIGUSR1. Continue the backend. We will\nhit\nthe breakpoint b procsignal_sigusr1_handler.\n\n6. Send a TERM or perform pg_terminate_backend() on the backend.\n\n7. Detach from all of the processes.\n\n8. The backend will be waiting for replication forever inside\nSyncRepWaitForLSN(). We can confirm this by pausing the backend and checking\nthe back trace and also by looking at pg_stat_activity. Subsequent attempts\nto\nterminate the backend would be futile.\n\n\nWorking fix:\nAt the start of SyncRepWaitForLSN() check if we are already in a USR1\nhandler.\nIf yes, we return. We use sigprocmask(), sigismember() to perform the\ndetection.\n\n-----\nAshwin Agrawal, Bhuvnesh Chaudhary, Jesse Zhang and Soumyadeep Chakraborty\n\nHello Hackers,There is an edge case in 9_5_STABLE (doesn't reproduce 9_6+) we found in howbackends handle the TERM signal while handling a USR1 signal that can causethem to infinitely wait. A backend can end up waiting forever insideSyncRepWaitForLSN() at: rc = WaitLatch(MyLatch, WL_LATCH_SET |WL_POSTMASTER_DEATH, -1, WAIT_EVENT_SYNC_REP);Even pg_terminate_backend() would not be able to terminate it after it reaches this point.Stack trace:#0  0x00007f39418d73c8 in poll () from /lib64/libc.so.6#1  0x0000000000753d7b in WaitLatchOrSocket (latch=0x7f3940d371cc, wakeEvents=17, sock=-1, timeout=-1)    at pg_latch.c:333#2  0x0000000000753b8c in WaitLatch (latch=0x7f3940d371cc, wakeEvents=17, timeout=-1) at pg_latch.c:197#3  0x00000000007a0e02 in SyncRepWaitForLSN (XactCommitLSN=167868344) at syncrep.c:231#4  0x0000000000518b8a in RecordTransactionCommit () at xact.c:1349#5  0x000000000051966d in CommitTransaction () at xact.c:2057#6  0x000000000051a1f9 in CommitTransactionCommand () at xact.c:2769#7  0x000000000054ff5e in RemoveTempRelationsCallback (code=1, arg=0) at namespace.c:3878#8  0x00000000007be3d1 in shmem_exit (code=1) at ipc.c:228#9  0x00000000007be2c6 in proc_exit_prepare (code=1) at ipc.c:185#10 0x00000000007be234 in proc_exit (code=1) at ipc.c:102#11 0x000000000093152e in errfinish (dummy=0) at elog.c:535#12 0x00000000007ea492 in ProcessInterrupts () at postgres.c:2913#13 0x00000000007e9f93 in die (postgres_signal_arg=15) at postgres.c:2682#14 <signal handler called>#15 procsignal_sigusr1_handler (postgres_signal_arg=10) at procsignal.c:271#16 <signal handler called>#17 SocketBackend (inBuf=0x7ffc8dde0f80) at postgres.c:353#18 0x00000000007e70ca in ReadCommand (inBuf=0x7ffc8dde0f80) at postgres.c:510#19 0x00000000007eb990 in PostgresMain (argc=1, argv=0x1708cd0, dbname=0x1708b38 \"gpadmin\",    username=0x1708b18 \"gpadmin\") at postgres.c:4032#20 0x0000000000769922 in BackendRun (port=0x172e060) at postmaster.c:4309#21 0x0000000000769086 in BackendStartup (port=0x172e060) at postmaster.c:3983#22 0x00000000007657dc in ServerLoop () at postmaster.c:1706#23 0x0000000000764e16 in PostmasterMain (argc=3, argv=0x1707ce0) at postmaster.c:1314#24 0x00000000006bcdb3 in main (argc=3, argv=0x1707ce0) at main.c:228Root cause:The reason why the backend waits forever in WaitLatch is that it expects a USR1signal to be delivered in order to wake it up from the wait (WaitLatchOrSocketimplementation) using latch_sigusr1_handler. Now since its is already inside aUSR1 handler, USR1 is blocked by default. Thus, it never receives a USR1 andnever wakes up.Reproduction: [9_5_STABLE, commit: 5a32fcd]We must align the stars as follows:1. Create a psql session and create a temp table. [temp table forces a Txduring backend termination to drop the table => SyncRepWaitForLSN will becalled]2. Since, we don't have a fault injection framework, we have to rely on thedebugger: Attach to the following processes and install these breakpoints: i) Attach to the Backend:b procsignal_sigusr1_handler b postgres.c:353at: SocketBackend: ereport(DEBUG1,(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),errmsg(\"unexpected EOF on client connection\")));ii) Attach to the Wal Sender, no need for a specific breakpoint [We need tomake the Wal Sender fall behind in order for the condition lsn <=WalSndCtl->lsn[mode] to be false inside SyncRepWaitForLSN()]3. kill -9 the psql process [This will send an EOF to the backend's connectionto the front end, which will cause DoingCommandRead = true andwhereToSendOutput = DestNone (in SocketBackend()). This will later ensure thatProcessInterrupts() is called from within die: the backend's TERM handler] 4. Continue the backend process in the debugger, it should reach the breakpointwe set inside SocketBackend.5. Send a USR1 to the backend. kill -SIGUSR1. Continue the backend. We will hitthe breakpoint b procsignal_sigusr1_handler.6. Send a TERM or perform pg_terminate_backend() on the backend.7. Detach from all of the processes.8. The backend will be waiting for replication forever insideSyncRepWaitForLSN(). We can confirm this by pausing the backend and checkingthe back trace and also by looking at pg_stat_activity. Subsequent attempts toterminate the backend would be futile.Working fix: At the start of SyncRepWaitForLSN() check if we are already in a USR1 handler.If yes, we return. We use sigprocmask(), sigismember() to perform thedetection.-----Ashwin Agrawal, Bhuvnesh Chaudhary, Jesse Zhang and Soumyadeep Chakraborty", "msg_date": "Thu, 22 Aug 2019 14:52:06 -0700", "msg_from": "Soumyadeep Chakraborty <soumyadeep2007@gmail.com>", "msg_from_op": true, "msg_subject": "Infinite wait for SyncRep while handling USR1" } ]
[ { "msg_contents": "Hi all,\n\nAttached is a patch set to respawn the issue of $subject which has\nbeen discussed here:\nhttps://www.postgresql.org/message-id/20170720204733.40f2b7eb.nagata@sraoss.co.jp\n\nThe patch has been committed once as of cd8ce3a but it got shortly\nreverted after with 98d54bb because of buildfarm failures.\n\nThe root of the buildfarm issues was that session hooks cannot be\ntested with a simple LOAD, hence we need to mark the test with\nNO_INSTALLCHECK. Unfortunately we lacked support for that in MSVC\nscripts, until I solved that with 431f1599 when refactoring PGXS\nmakefile rules for regression tests.\n\nWhile on it, I have done a review over the patch, cleaning it up a bit\nand I found some issues, so the initial patch was not fully baked\neither:\n- previous hook calls were only called for normal backends, which was\nincorrect as we define the backend so as we apply no backend-related\nfiltering for the hook.\n- The README could be also more talkative.\n- test_session_hooks--1.0.sql also got confused with the module name.\nAnd actually there is no need to have the SQL and control files just\nfor a module loading a hook. So it is enough to use MODULE_big for\nthis purpose.\n- The query generated needs to use quote_literal_cstr for the string\nvalues added to the query.\n- sample_session_start_hook and sample_session_end_hook missed a\n(void), causing a compiler warning on Windows. \n\nAttached is an updated patch set to reintroduce the hook, as there was\na ask for it recently, fixing also the issue that we previously tried\nto deal with. I have tested the patch on Windows to make sure that\nthe test gets correctly bypassed, so this time we should not have any\nbuildfarm failures.\n\nI am adding that to next CF. Credits go of course to the initial\nauthors and reviewers of this feature.\n\nAny opinions?\n--\nMichael", "msg_date": "Fri, 23 Aug 2019 13:26:02 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Hooks for session start and end, take two" }, { "msg_contents": "Hello,\n\nThank you for the work done on this subject.\nAfter starting to play with it, I have a question and a remark:\n\n> - previous hook calls were only called for normal backends, which was\n> incorrect as we define the backend so as we apply no backend-related\n> filtering for the hook. \n\nDoes that mean that all processes seen in pg_stat_activity like\n- autovacuum launcher\n- logical replication launcher\n- background writer\n- checkpointer\n- walwriter\n... \n- Parallel worker\nare available with that hook (it seems not) ?\n\nThe patch refers to a 2017 copyright, that's all I found yet ;o)\n\nRegards\nPAscal\n\n\n\n--\nSent from: https://www.postgresql-archive.org/PostgreSQL-hackers-f1928748.html\n\n\n", "msg_date": "Thu, 26 Sep 2019 09:57:57 -0700 (MST)", "msg_from": "legrand legrand <legrand_legrand@hotmail.com>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On Thu, Sep 26, 2019 at 09:57:57AM -0700, legrand legrand wrote:\n> Does that mean that all processes seen in pg_stat_activity like\n> - autovacuum launcher\n> - logical replication launcher\n> - background writer\n> - checkpointer\n> - walwriter\n> ... \n> - Parallel worker\n> are available with that hook (it seems not) ?\n\nAll processes using PostgresMain() for their startup take this code\npath like WAL senders and normal backend sessions, but not things\ngoing through StartChildProcess() (WAL receiver, bgwriter, etc.) or\nother processes like autovacuum processes which use a different start\ncode path.\n\n> The patch refers to a 2017 copyright, that's all I found yet ;o)\n\nFixed, thanks!\n--\nMichael", "msg_date": "Fri, 27 Sep 2019 13:54:26 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On Fri, Sep 27, 2019 at 12:54 AM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Thu, Sep 26, 2019 at 09:57:57AM -0700, legrand legrand wrote:\n> > Does that mean that all processes seen in pg_stat_activity like\n> > - autovacuum launcher\n> > - logical replication launcher\n> > - background writer\n> > - checkpointer\n> > - walwriter\n> > ...\n> > - Parallel worker\n> > are available with that hook (it seems not) ?\n>\n> All processes using PostgresMain() for their startup take this code\n> path like WAL senders and normal backend sessions, but not things\n> going through StartChildProcess() (WAL receiver, bgwriter, etc.) or\n> other processes like autovacuum processes which use a different start\n> code path.\n\nThere is another patchset submitted to this CF\n(https://commitfest.postgresql.org/24/2259/) that attempts to\ncentralize all process startup to make use of the StartChildProcess\nentrypoint. The patchset then introduces a fork_process hook that\nwould be hit by every backend type immediately after forking. Looking\nat your patch, it seems like there won't be too much conflict between\nthe two, but I wonder if we can collaborate on the hook portion to\nachieve both of our goals?\n\nAs noted in the related thread, I'm currently breaking out the\ncentralization patch into separate pieces: one for the infrastructure\nchange (including MyAuxProc adoption of the centralized startup), one\nfor each process type, and one for the fork_process hook. The\nsubstance of the patchset will remain mostly the same if you want to\ntake a look.\n\nI look forward to hearing your thoughts on the matter.\n\nThanks,\n-- \nMike Palmiotto\nhttps://crunchydata.com\n\n\n", "msg_date": "Fri, 27 Sep 2019 15:01:39 -0400", "msg_from": "Mike Palmiotto <mike.palmiotto@crunchydata.com>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "Michael Paquier-2 wrote\n> On Thu, Sep 26, 2019 at 09:57:57AM -0700, legrand legrand wrote:\n>> Does that mean that all processes seen in pg_stat_activity like\n>> - autovacuum launcher\n>> - logical replication launcher\n>> - background writer\n>> - checkpointer\n>> - walwriter\n>> ... \n>> - Parallel worker\n>> are available with that hook (it seems not) ?\n> \n> All processes using PostgresMain() for their startup take this code\n> path like WAL senders and normal backend sessions, but not things\n> going through StartChildProcess() (WAL receiver, bgwriter, etc.) or\n> other processes like autovacuum processes which use a different start\n> code path.\n\nOK I confirm:\n- \"client backend\" appears at session start and end hook,\n- \"autovacuum worker\" and \"pg_background\" only appears at session end hook\n (backend_start can be retreived from pg_stat_activity),\n- \"parallel workers\" are not visible at all\n (because extension cannot assign XIDs during a parallel operation)\n\nAll seems fine to me.\n\nRegards\nPAscal\n\n\n\n\n\n\n--\nSent from: https://www.postgresql-archive.org/PostgreSQL-hackers-f1928748.html\n\n\n", "msg_date": "Fri, 27 Sep 2019 12:26:31 -0700 (MST)", "msg_from": "legrand legrand <legrand_legrand@hotmail.com>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On Fri, Sep 27, 2019 at 4:26 PM legrand legrand <legrand_legrand@hotmail.com>\nwrote:\n>\n> OK I confirm:\n> - \"client backend\" appears at session start and end hook,\n> - \"autovacuum worker\" and \"pg_background\" only appears at session end hook\n> (backend_start can be retreived from pg_stat_activity),\n> - \"parallel workers\" are not visible at all\n> (because extension cannot assign XIDs during a parallel operation)\n>\n> All seems fine to me.\n>\n\nHi all,\n\nFirst of all thanks Michael for bringing this to life again.\n\nI poked a little with the patch and everything is ok. Your check for normal\nbackend on test_session_hooks is much simpler than I did before:\n\n+ /* just consider normal backends */\n+ if (MyBackendId == InvalidBackendId)\n+ return;\n\nBut one thing came to my mind, why not in this first version we hook just\nnormal backends?\n\nRegards,\n\n--\n Fabrízio de Royes Mello Timbira - http://www.timbira.com.br/\n PostgreSQL: Consultoria, Desenvolvimento, Suporte 24x7 e Treinamento\n\nOn Fri, Sep 27, 2019 at 4:26 PM legrand legrand <legrand_legrand@hotmail.com> wrote:>> OK I confirm:> - \"client backend\" appears at session start and end hook,> - \"autovacuum worker\" and \"pg_background\" only appears at session end hook>   (backend_start can be retreived from pg_stat_activity),> - \"parallel workers\" are not visible at all>   (because extension cannot assign XIDs during a parallel operation)>> All seems fine to me.>Hi all,First of all thanks Michael for bringing this to life again.I poked a little with the patch and everything is ok. Your check for normal backend on test_session_hooks is much simpler than I did before:+    /* just consider normal backends */+    if (MyBackendId == InvalidBackendId)+        return;But one thing came to my mind, why not in this first version we hook just normal backends? Regards,--   Fabrízio de Royes Mello         Timbira - http://www.timbira.com.br/   PostgreSQL: Consultoria, Desenvolvimento, Suporte 24x7 e Treinamento", "msg_date": "Sat, 28 Sep 2019 10:43:36 -0300", "msg_from": "=?UTF-8?Q?Fabr=C3=ADzio_de_Royes_Mello?= <fabriziomello@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On Sat, Sep 28, 2019 at 10:43:36AM -0300, Fabrízio de Royes Mello wrote:\n> I poked a little with the patch and everything is ok. Your check for normal\n> backend on test_session_hooks is much simpler than I did before:\n> \n> + /* just consider normal backends */\n> + if (MyBackendId == InvalidBackendId)\n> + return;\n> \n> But one thing came to my mind, why not in this first version we hook just\n> normal backends?\n\nThis code path can only be taken by normal backends, so that would\napply, still I don't actually see why we should limit us here on the\nbackend side. If for a reason or another those two code paths begin\nto be taken by a backend with InvalidBackendId, then users of the\nsession start/end hook will need to think how to handle it if they\ndidn't from the start, which sounds like a good thing to me.\n--\nMichael", "msg_date": "Mon, 30 Sep 2019 10:29:41 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On Sun, Sep 29, 2019 at 10:29 PM Michael Paquier <michael@paquier.xyz>\nwrote:\n>\n> This code path can only be taken by normal backends, so that would\n> apply, still I don't actually see why we should limit us here on the\n> backend side. If for a reason or another those two code paths begin\n> to be taken by a backend with InvalidBackendId, then users of the\n> session start/end hook will need to think how to handle it if they\n> didn't from the start, which sounds like a good thing to me.\n>\n\nMakes sense to me. I become a reviewer and run all tests (make check &&\nmake check-world) and everything is ok. Changed status to \"ready for\ncommiter\".\n\nRegards,\n\n--\n Fabrízio de Royes Mello Timbira - http://www.timbira.com.br/\n PostgreSQL: Consultoria, Desenvolvimento, Suporte 24x7 e Treinamento\n\nOn Sun, Sep 29, 2019 at 10:29 PM Michael Paquier <michael@paquier.xyz> wrote:>> This code path can only be taken by normal backends, so that would> apply, still I don't actually see why we should limit us here on the> backend side.  If for a reason or another those two code paths begin> to be taken by a backend with InvalidBackendId, then users of the> session start/end hook will need to think how to handle it if they> didn't from the start, which sounds like a good thing to me.>Makes sense to me. I become a reviewer and run all tests (make check && make check-world) and everything is ok. Changed status to \"ready for commiter\".Regards,--   Fabrízio de Royes Mello         Timbira - http://www.timbira.com.br/   PostgreSQL: Consultoria, Desenvolvimento, Suporte 24x7 e Treinamento", "msg_date": "Mon, 30 Sep 2019 14:46:42 -0300", "msg_from": "=?UTF-8?Q?Fabr=C3=ADzio_de_Royes_Mello?= <fabriziomello@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On Mon, Sep 30, 2019 at 02:46:42PM -0300, Fabrízio de Royes Mello wrote:\n> Makes sense to me. I become a reviewer and run all tests (make check &&\n> make check-world) and everything is ok. Changed status to \"ready for\n> commiter\".\n\nThanks. There was an extra problem in the module hidden in the logs\nof the regression tests: the autovacuum launcher has a backend ID\nassigned at the moment of the session end hook (not the start), but it\nis connected to no databases so I added a check on that in the start\nand end hooks of the module. That's more logic this way anyway as we\nrun a transaction in the test, and much better than using directly\nGetUserIdAndSecContext() which would not assert for an invalid user\nID. And done with e788bd9.\n--\nMichael", "msg_date": "Tue, 1 Oct 2019 12:17:22 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "Hi,\n\nMoving the discussion of the issues leading to this being reverted back\nto -hackers:\n\nOn 2019-10-02 23:52:31 +0900, Fujii Masao wrote:\n> On Wed, Oct 2, 2019 at 10:08 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n> >\n> > On 2019-Oct-02, Michael Paquier wrote:\n> >\n> > > On Wed, Oct 02, 2019 at 01:27:50PM +0900, Fujii Masao wrote:\n> > > > If only session end hook is problematic, you will commit session start\n> > > > hook again?\n> > >\n> > > Sure, it would be possible to cut the apple in half here. Now my\n> > > understanding was that both hooks were a set. What do people think?\n> >\n> > I think that having just session start is still useful\n\n> +1\n\nWell, I think the patch actually needs to do a lot more design work to\nbe comittable and usable. It's very unclear how these hooks are actually\nsupposed to be used safely. Issues I see:\n\n- the startup hook isn't actually guaranteed to be able to write\n anything, we might be in hot-standby\n- the startup hook doesn't just run in normal sessions, it also runs in\n walsenders, including ones not connected to a database. But for some\n implementation reasons it won't run for background workers.\n- the shutdown hook placement means that any error triggered within the\n handler probably cannot be cleaned up properly anymore\n- do we actually want to run code like this for e.g. FATAL errors?\n- THERE IS NOT A SINGLE COMMENT EXPLAINING WHAT CAN BE SAFELY DONE IN THESE\n HOOKS. In fact, outside of the tests, the only comments in this are:\n /* Hook for plugins to get control at start and end of session */\n /* Hook for plugins to get control at start of session */\n /* Hook at session end */\n /* Hook for plugins to get control at end of session */\n\n\n> Regarding session end hook, you can do the almost same thing as that hook\n> by calling on_shmem_exit(), before_shmem_exit() or on_proc_exit() in\n> other hook like session start hook. This approach also has the same issue\n> discussed upthread, though. Anyway, I'm not sure if session end hook is\n> \"actually\" necessary.\n\nNo, it's not actually the same (at least for\nbefore_shmem_exit). ShutdownPostgres() runs deliberately as the *last*\nbefore_shmem_exit to run before we switch over to tearing down shmem:\n\n\t/*\n\t * Set up process-exit callback to do pre-shutdown cleanup. This is the\n\t * first before_shmem_exit callback we register; thus, this will be the\n\t * last thing we do before low-level modules like the buffer manager begin\n\t * to close down. We need to have this in place before we begin our first\n\t * transaction --- if we fail during the initialization transaction, as is\n\t * entirely possible, we need the AbortTransaction call to clean up.\n\t */\n\n *\n * User-level cleanup, such as temp-relation removal and UNLISTEN, happens\n * via separate callbacks that execute before this one. We don't combine the\n * callbacks because we still want this one to happen if the user-level\n * cleanup fails.\n\n\n- Andres\n\n\n", "msg_date": "Wed, 2 Oct 2019 10:23:54 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2019-10-02 23:52:31 +0900, Fujii Masao wrote:\n>> Regarding session end hook, you can do the almost same thing as that hook\n>> by calling on_shmem_exit(), before_shmem_exit() or on_proc_exit() in\n>> other hook like session start hook. This approach also has the same issue\n>> discussed upthread, though. Anyway, I'm not sure if session end hook is\n>> \"actually\" necessary.\n\n> No, it's not actually the same (at least for\n> before_shmem_exit).\n\nYeah. The important point here is that if you want to be able to execute\nSQL, then you can't close down *ANY* subsystems before that. Even in the\nsimple scenario exercised by the test case, imagine that there are user\ntriggers attached to the table it wants to insert a row in. They could\nexecute anything at all.\n\nThus, we can't run any shutdown hooks before this one, if indeed we\nconsider it to be a shutdown hook at all.\n\nA possible fix is to do it as the first action in proc_exit, but that will\nfall foul of Andres' points about not wanting to do it in non-session\nbackends, nor in FATAL exits, nor in the case where a previous try failed.\nPerhaps a better idea is to put it into PostgresMain's handling of client\nEOF, despite the large comment saying not to add more code there.\n\n(Or, maybe invent a new class of shutdown callbacks?\nbefore_before_shmem_exit seems like a pretty grotty concept, but it's\nmore or less what we need here. It would sure be nice if we had an\nactual specification for what is allowed to happen in these different\nclasses of callbacks...)\n\nIn any case, the hook would have to be responsible for cancelling any open\ntransaction for itself, in order to have a clean environment to run SQL\ncode in. It cannot piggyback on existing transaction-closing code to do\nthat, because any user-written code could throw an error inside the hook's\ntransaction and thereby break the invariant that we're not in a\ntransaction after that point.\n\nBottom line: there needs to be thought and testing of the case where the\nexecuted SQL throws an error. We need to recover from that and exit\ncleanly, and the committed patch surely would not have. Likewise there\nshould be a test for the case where we exit the session mid-transaction\nor mid-failed-transaction.\n\nBTW, my first thought about why the test case was failing was that it\nhad race conditions. We now see that the problems were worse than that,\nbut before a new on-session-exit test goes in, you need to think about\nit. You have no guarantee that the callback will execute before the\nclient-side test script does its next action. Thus, for example, I\nwondered if the SELECTs were failing because the expected insertion\nhadn't happened yet, or if the DROP ROLEs were failing because there\nwas still a live session logged in under the role.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 02 Oct 2019 13:51:43 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On Wed, Oct 02, 2019 at 01:51:43PM -0400, Tom Lane wrote:\n> Thus, we can't run any shutdown hooks before this one, if indeed we\n> consider it to be a shutdown hook at all.\n> \n> A possible fix is to do it as the first action in proc_exit, but that will\n> fall foul of Andres' points about not wanting to do it in non-session\n> backends, nor in FATAL exits, nor in the case where a previous try failed.\n> Perhaps a better idea is to put it into PostgresMain's handling of client\n> EOF, despite the large comment saying not to add more code there.\n\nPerhaps.\n\n> (Or, maybe invent a new class of shutdown callbacks?\n> before_before_shmem_exit seems like a pretty grotty concept, but it's\n> more or less what we need here. It would sure be nice if we had an\n> actual specification for what is allowed to happen in these different\n> classes of callbacks...)\n\nIt seems to me that we may actually be looking at a concept of\ncallback priority here. Say you could assign a number to each\ncallback registered, and control their order at shutdown. I am\nwondering if we shouldn't do that anyway. Likely there could be cases\nwhere it makes sense to ensure the ordering of the actions where we\nhave dependencies between some subsystems? For example\nShutdownPostgres is registered first, meaning that it runs last\nanyway. Now for other future things or even extensions there could be\nan argument?\n\n> In any case, the hook would have to be responsible for cancelling any open\n> transaction for itself, in order to have a clean environment to run SQL\n> code in. It cannot piggyback on existing transaction-closing code to do\n> that, because any user-written code could throw an error inside the hook's\n> transaction and thereby break the invariant that we're not in a\n> transaction after that point.\n\nStill, it would mean that any module hooking in the area would need to\ndo the cleanup all the time...\n--\nMichael", "msg_date": "Thu, 3 Oct 2019 10:51:32 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On Wed, Oct 02, 2019 at 10:23:54AM -0700, Andres Freund wrote:\n> - the startup hook isn't actually guaranteed to be able to write\n> anything, we might be in hot-standby\n\nRight.\n\n> - the startup hook doesn't just run in normal sessions, it also runs in\n> walsenders, including ones not connected to a database. But for some\n> implementation reasons it won't run for background workers.\n\nThe idea here is to have a hook which can be triggered at the start of\na process which can be externally triggered, which I guess is normal\neven for WAL senders not connected to a database.\n\n> - do we actually want to run code like this for e.g. FATAL errors?\n\nThat was the intention.\n\n> - THERE IS NOT A SINGLE COMMENT EXPLAINING WHAT CAN BE SAFELY DONE IN THESE\n> HOOKS. In fact, outside of the tests, the only comments in this are:\n> /* Hook for plugins to get control at start and end of session */\n> /* Hook for plugins to get control at start of session */\n> /* Hook at session end */\n> /* Hook for plugins to get control at end of session */\n\nWe include in the backend code a dozen of hooks or so similar to this\none (excluding from the count GUC and reloption hooks and such). For\nmost of them we do not provide much extensive documentation nor\nexplanations similar to that, so it is rather unclear what would be a\nminimum and acceptable set of comments and/or documentation which\nwould be fine (the same comment could basically apply to the planner\nor post-parse hooks). Should we finally add a specific section in the\nuser-visible docs even if there has been reluctance to do so? My\nguess is that we go down to this kind of requirement if we want to be\nable to never forget to add documentation for any kind of new hook.\n--\nMichael", "msg_date": "Thu, 3 Oct 2019 11:03:39 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "Hi,\n\nOn 2019-10-03 11:03:39 +0900, Michael Paquier wrote:\n> On Wed, Oct 02, 2019 at 10:23:54AM -0700, Andres Freund wrote:\n> > - the startup hook isn't actually guaranteed to be able to write\n> > anything, we might be in hot-standby\n> \n> Right.\n> \n> > - the startup hook doesn't just run in normal sessions, it also runs in\n> > walsenders, including ones not connected to a database. But for some\n> > implementation reasons it won't run for background workers.\n> \n> The idea here is to have a hook which can be triggered at the start of\n> a process which can be externally triggered, which I guess is normal\n> even for WAL senders not connected to a database.\n\nBut what can you do in that situation? Without a database connection,\nfor example, you better not consider inserting anything into a table.\n\n\n> > - do we actually want to run code like this for e.g. FATAL errors?\n> \n> That was the intention.\n\nI have *SERIOUS* problems with performing additional writing\ntransactions in case of a FATAL. Something might have thrown that for a\nreason, and just carrying on executing an arbitrary amount of code, this\nmight even involve triggers etc, imo seriously is not OK.\n\n\n> > - THERE IS NOT A SINGLE COMMENT EXPLAINING WHAT CAN BE SAFELY DONE IN THESE\n> > HOOKS. In fact, outside of the tests, the only comments in this are:\n> > /* Hook for plugins to get control at start and end of session */\n> > /* Hook for plugins to get control at start of session */\n> > /* Hook at session end */\n> > /* Hook for plugins to get control at end of session */\n> \n> We include in the backend code a dozen of hooks or so similar to this\n> one (excluding from the count GUC and reloption hooks and such). For\n> most of them we do not provide much extensive documentation nor\n> explanations similar to that\n\nI don't mean sgml docs, but rather code comments. Most hooks don't have\na caveat list as long as the hooks proposed here. And for most the\nspecific location they hook into is more obvious: Whereas e.g. planner\nhook can just happen when planning happens, the proposed hooks here\ncould plausible be put into many different places.\n\nIf somebody had bothered to add an explanation as to why the hook\nplacements are a good idea, they might have noticed that the location\nthe shutdown hook was placed at was terrible.\n\n\n> so it is rather unclear what would be a minimum and acceptable set of\n> comments and/or documentation which would be fine (the same comment\n> could basically apply to the planner or post-parse hooks).\n\nMeh. As described above, I don't think most other hooks are as vague and\ndangerous as these. Nor is the existance of underdocumented code an\nargument for adding more.\n\n\n> Should we finally add a specific section in the user-visible docs even\n> if there has been reluctance to do so? My guess is that we go down to\n> this kind of requirement if we want to be able to never forget to add\n> documentation for any kind of new hook.\n\nThis seems like an entirely separate discussion.\n\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 2 Oct 2019 21:09:53 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On Wed, Oct 02, 2019 at 09:09:53PM -0700, Andres Freund wrote:\n> On 2019-10-03 11:03:39 +0900, Michael Paquier wrote:\n>> The idea here is to have a hook which can be triggered at the start of\n>> a process which can be externally triggered, which I guess is normal\n>> even for WAL senders not connected to a database.\n> \n> But what can you do in that situation? Without a database connection,\n> for example, you better not consider inserting anything into a table.\n\nAdding extra custom logging information, or plug that information\nelsewhere than Postgres. I have use cases for that when it comes to\nstore external telemetry data or audit things for events happening\nspecifically in Postgres.\n\n> I have *SERIOUS* problems with performing additional writing\n> transactions in case of a FATAL. Something might have thrown that for a\n> reason, and just carrying on executing an arbitrary amount of code, this\n> might even involve triggers etc, imo seriously is not OK.\n\nWell, hook authors can do a lot of stupid things.. Anyway it looks\nthat the end hook is out of scope as far as the discussion has gone\nbased on the lack of facility, and that there is still interest for\nthe start hook.\n\nI am just attaching a separate patch which adds only the start hook.\nThe discussion could always respawn from that. This takes care of the\nHBA configuration when testing on Windows, and the module is still\nnamed \"hooks\" intentionally to avoid a future rename.\n--\nMichael", "msg_date": "Thu, 3 Oct 2019 13:20:09 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "Hi,\n\nOn 2019-10-03 13:20:09 +0900, Michael Paquier wrote:\n> On Wed, Oct 02, 2019 at 09:09:53PM -0700, Andres Freund wrote:\n> > I have *SERIOUS* problems with performing additional writing\n> > transactions in case of a FATAL. Something might have thrown that for a\n> > reason, and just carrying on executing an arbitrary amount of code, this\n> > might even involve triggers etc, imo seriously is not OK.\n> \n> Well, hook authors can do a lot of stupid things..\n\nI don't have much problems if they knowingly do stupid stuff. But if\nwhat we provide basically only consists out of pitfalls, than we need to\nreconsider the interface, or at least have guidance on how to avoid\nthem.\n\n\n> Anyway it looks that the end hook is out of scope as far as the\n> discussion has gone based on the lack of facility, and that there is\n> still interest for the start hook.\n\nI don't really think that's a fair summary of what's been discussed.\n\n\n> diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c\n> index e8d8e6f828..6d80cc2d64 100644\n> --- a/src/backend/tcop/postgres.c\n> +++ b/src/backend/tcop/postgres.c\n> @@ -171,6 +171,9 @@ static ProcSignalReason RecoveryConflictReason;\n> static MemoryContext row_description_context = NULL;\n> static StringInfoData row_description_buf;\n> \n> +/* Hook for plugins to get control at start of session */\n> +session_start_hook_type session_start_hook = NULL;\n> +\n> /* ----------------------------------------------------------------\n> *\t\tdecls for routines only used in this file\n> * ----------------------------------------------------------------\n> @@ -3968,6 +3971,9 @@ PostgresMain(int argc, char *argv[],\n> \tif (!IsUnderPostmaster)\n> \t\tPgStartTime = GetCurrentTimestamp();\n> \n> +\tif (session_start_hook)\n> +\t\t(*session_start_hook) ();\n> +\n> \t/*\n> \t * POSTGRES main processing loop begins here\n> \t *\n> diff --git a/src/include/tcop/tcopprot.h b/src/include/tcop/tcopprot.h\n> index ec21f7e45c..f42935f019 100644\n> --- a/src/include/tcop/tcopprot.h\n> +++ b/src/include/tcop/tcopprot.h\n> @@ -30,6 +30,10 @@ extern PGDLLIMPORT const char *debug_query_string;\n> extern int\tmax_stack_depth;\n> extern int\tPostAuthDelay;\n> \n> +/* Hook for plugins to get control at start session */\n> +typedef void (*session_start_hook_type) (void);\n> +extern PGDLLIMPORT session_start_hook_type session_start_hook;\n> +\n> /* GUC-configurable parameters */\n \nIn this state I think this patch should be flat out rejected.\n\nI'm seriously baffled at how this stuff is being pursued aggressively,\nquite apparently without any serious design considerations. I mean this\nstuff had to be backed out twice, yet it's being reproposed without much\nconsideration for concerns?\n\n- Andres\n\n\n", "msg_date": "Wed, 2 Oct 2019 21:35:43 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On Thu, Oct 3, 2019 at 1:35 AM Andres Freund <andres@anarazel.de> wrote:\n>\n> [...]\n>\n> In this state I think this patch should be flat out rejected.\n>\n\nOk.\n\n> I'm seriously baffled at how this stuff is being pursued aggressively,\n> quite apparently without any serious design considerations. I mean this\n> stuff had to be backed out twice, yet it's being reproposed without much\n> consideration for concerns?\n>\n\nAnd what if (again) for the first version of session start hook we do it\njust for:\n- client backends\n- background workers\n\nFor sure we'll need new design, but for now I'm can't imagine a use case\nfor sessions different than listed above.\n\nRegards,\n\n--\n Fabrízio de Royes Mello Timbira - http://www.timbira.com.br/\n PostgreSQL: Consultoria, Desenvolvimento, Suporte 24x7 e Treinamento\n\nOn Thu, Oct 3, 2019 at 1:35 AM Andres Freund <andres@anarazel.de> wrote:>> [...]> > In this state I think this patch should be flat out rejected.>Ok.> I'm seriously baffled at how this stuff is being pursued aggressively,> quite apparently without any serious design considerations. I mean this> stuff had to be backed out twice, yet it's being reproposed without much> consideration for concerns?>And what if (again) for the first version of session start hook we do it just for:- client backends- background workersFor sure we'll need new design, but for now I'm can't imagine a use case for sessions different than listed above.Regards,--   Fabrízio de Royes Mello         Timbira - http://www.timbira.com.br/   PostgreSQL: Consultoria, Desenvolvimento, Suporte 24x7 e Treinamento", "msg_date": "Thu, 3 Oct 2019 11:19:58 -0300", "msg_from": "=?UTF-8?Q?Fabr=C3=ADzio_de_Royes_Mello?= <fabriziomello@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "Hi,\n\nOn 2019-10-03 11:19:58 -0300, Fabr�zio de Royes Mello wrote:\n> On Thu, Oct 3, 2019 at 1:35 AM Andres Freund <andres@anarazel.de> wrote:\n> >\n> > [...]\n> >\n> > In this state I think this patch should be flat out rejected.\n> >\n> \n> Ok.\n> \n> > I'm seriously baffled at how this stuff is being pursued aggressively,\n> > quite apparently without any serious design considerations. I mean this\n> > stuff had to be backed out twice, yet it's being reproposed without much\n> > consideration for concerns?\n> >\n> \n> And what if (again) for the first version of session start hook we do it\n> just for:\n> - client backends\n> - background workers\n> \n> For sure we'll need new design, but for now I'm can't imagine a use case\n> for sessions different than listed above.\n\nI think what would need to be designed is something more like\nRegisterXactCallback():\n\n/*\n *\tstart- and end-of-transaction callbacks for dynamically loaded modules\n */\ntypedef enum\n{\n\tXACT_EVENT_COMMIT,\n\tXACT_EVENT_PARALLEL_COMMIT,\n\tXACT_EVENT_ABORT,\n\tXACT_EVENT_PARALLEL_ABORT,\n\tXACT_EVENT_PREPARE,\n\tXACT_EVENT_PRE_COMMIT,\n\tXACT_EVENT_PARALLEL_PRE_COMMIT,\n\tXACT_EVENT_PRE_PREPARE\n} XactEvent;\n\ntypedef void (*XactCallback) (XactEvent event, void *arg);\n\nextern void RegisterXactCallback(XactCallback callback, void *arg);\nextern void UnregisterXactCallback(XactCallback callback, void *arg);\n\n\nwhich would be called at various parts of a processes lifetime. Maybe\nsomething like:\n\n1) shortly after process creation\n2) shortly after shared memory attach\n3) after database connection has been established\n4) after database writes are possible (this excludes database-less walsenders)\n5a) before closing database connection due to fatal error\n (with a note saying that no writes are ever allowed)\n5b) before closing database connection due to normal exit\n (with a note saying that errors better be handled, and that no\n transaction may escape)\n6) before shared memory detach\n7) before final exit\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 3 Oct 2019 08:09:11 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On Thu, Oct 3, 2019 at 11:09 AM Andres Freund <andres@anarazel.de> wrote:\n>\n> <snip>\n> I think what would need to be designed is something more like\n> RegisterXactCallback():\n>\n> /*\n> * start- and end-of-transaction callbacks for dynamically loaded modules\n> */\n> typedef enum\n> {\n> XACT_EVENT_COMMIT,\n> XACT_EVENT_PARALLEL_COMMIT,\n> XACT_EVENT_ABORT,\n> XACT_EVENT_PARALLEL_ABORT,\n> XACT_EVENT_PREPARE,\n> XACT_EVENT_PRE_COMMIT,\n> XACT_EVENT_PARALLEL_PRE_COMMIT,\n> XACT_EVENT_PRE_PREPARE\n> } XactEvent;\n>\n> typedef void (*XactCallback) (XactEvent event, void *arg);\n>\n> extern void RegisterXactCallback(XactCallback callback, void *arg);\n> extern void UnregisterXactCallback(XactCallback callback, void *arg);\n>\n>\n> which would be called at various parts of a processes lifetime. Maybe\n> something like:\n>\n> 1) shortly after process creation\n> 2) shortly after shared memory attach\n> 3) after database connection has been established\n> 4) after database writes are possible (this excludes database-less walsenders)\n> 5a) before closing database connection due to fatal error\n> (with a note saying that no writes are ever allowed)\n> 5b) before closing database connection due to normal exit\n> (with a note saying that errors better be handled, and that no\n> transaction may escape)\n> 6) before shared memory detach\n> 7) before final exit\n\nThis suggestion really resonates with me, as I had considered\nsomething similar in the process centralization patchset (CF entry\nlinked upthread and discussion here:\nhttps://www.postgresql.org/message-id/flat/CAMN686FE0OdZKp9YPO=htC6LnA6aW4r-+jq=3Q5RAoFQgW8EtA@mail.gmail.com).\nIt would be possible to build such a mechanism into that existing\narchitecture rather easily. Has anyone had a chance to review that\nwork?\n\nThanks,\n-- \nMike Palmiotto\nhttps://crunchydata.com\n\n\n", "msg_date": "Thu, 3 Oct 2019 11:39:33 -0400", "msg_from": "Mike Palmiotto <mike.palmiotto@crunchydata.com>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "From: Michael Paquier <michael@paquier.xyz>\r\n> Adding extra custom logging information, or plug that information\r\n> elsewhere than Postgres. I have use cases for that when it comes to\r\n> store external telemetry data or audit things for events happening\r\n> specifically in Postgres.\r\n> \r\n> Well, hook authors can do a lot of stupid things.. Anyway it looks\r\n> that the end hook is out of scope as far as the discussion has gone\r\n> based on the lack of facility, and that there is still interest for\r\n> the start hook.\r\n\r\nI've got interested in this. What's the current status of this patch? The CF entry shows it was committed.\r\n\r\nhttps://commitfest.postgresql.org/25/2251/\r\n\r\nBut I understood not, because the relevant code doesn't appear in HEAD, and Git log shows that it was reverted. Am I correct?\r\n\r\n\r\nI'm thinking of using this feature to address an issue raised by a user who is considering migrating from Oracle. Oracle caches SQL execution plans in shared memory and enables any session to use them. He wants to hide the plan creation time from end users after database restart (perhaps the plan creation is slow.) To do that in Oracle, he runs possible SQL statements in a session solely for warm-up before resuming service for end users. Then, later new sessions of end users can use the cached execution plans.\r\n\r\nIdeally, PostgreSQL should be able to share query plans among sessions without user intervention. But I guess it would be difficult. Instead, with this session start hook and the connection pooling, individual sessions can run possible SQL statements using PREPARE and EXECUTE once (forcing generic plans) at session start.\r\n\r\n\r\n\r\nBTW, the user interface of the feature is unduly difficult for my use case and the use cases you mentioned. I think users should be able to use the feature only with SQL, without creating extensions. That also allows the use of this feature in DBaaS. How about creating a new event trigger type, connect trigger, after Oracle's logon trigger?\r\n\r\nCREATE EVENT TRIGGER mytrigger\r\n AFTER CONNECT [ON mydatabase]\r\n EXECUTE {PROCEDURE | FUNCTION} myproc();\r\n\r\nIf some hacker wants to do what SQL can't, he can specify a UDF in C.\r\n\r\n\r\nRegards\r\nTakayuki Tsunakawa\r\n\r\n\r\n", "msg_date": "Fri, 20 Dec 2019 02:45:26 +0000", "msg_from": "\"tsunakawa.takay@fujitsu.com\" <tsunakawa.takay@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: Hooks for session start and end, take two" }, { "msg_contents": "On Fri, Dec 20, 2019 at 02:45:26AM +0000, tsunakawa.takay@fujitsu.com wrote:\n> I've got interested in this. What's the current status of this\n> patch? The CF entry shows it was committed.\n>\n> But I understood not, because the relevant code doesn't appear in\n> HEAD, and Git log shows that it was reverted. Am I correct? \n\nThe patch has been committed once as of e788bd9, then reverted as of\n9555cc8 because it had a couple of fundamental issues and many people\nwere not happy with it. The latest discussions point out to some more\nadvanced designs based on callbacks at certain points of a session\nlifetime. You may want to double-check on that first.\n--\nMichael", "msg_date": "Fri, 20 Dec 2019 16:20:18 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On 2019-Dec-20, Michael Paquier wrote:\n\n> On Fri, Dec 20, 2019 at 02:45:26AM +0000, tsunakawa.takay@fujitsu.com wrote:\n> > I've got interested in this. What's the current status of this\n> > patch? The CF entry shows it was committed.\n> >\n> > But I understood not, because the relevant code doesn't appear in\n> > HEAD, and Git log shows that it was reverted. Am I correct? \n> \n> The patch has been committed once as of e788bd9, then reverted as of\n> 9555cc8 because it had a couple of fundamental issues and many people\n> were not happy with it.\n\nHmm, should we mark the commitfest entry as rejected then? Having it be\nmarked committed seems pretty confusing. The next version of the patch\nwould have its own CF entry, I presume.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 20 Dec 2019 11:18:07 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> On 2019-Dec-20, Michael Paquier wrote:\n>> The patch has been committed once as of e788bd9, then reverted as of\n>> 9555cc8 because it had a couple of fundamental issues and many people\n>> were not happy with it.\n\n> Hmm, should we mark the commitfest entry as rejected then? Having it be\n> marked committed seems pretty confusing. The next version of the patch\n> would have its own CF entry, I presume.\n\nRWF seems appropriate. We haven't rejected the concept altogether,\nAFAICT.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 20 Dec 2019 09:23:40 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On 2019-Dec-20, Tom Lane wrote:\n\n> Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> > On 2019-Dec-20, Michael Paquier wrote:\n> >> The patch has been committed once as of e788bd9, then reverted as of\n> >> 9555cc8 because it had a couple of fundamental issues and many people\n> >> were not happy with it.\n> \n> > Hmm, should we mark the commitfest entry as rejected then? Having it be\n> > marked committed seems pretty confusing. The next version of the patch\n> > would have its own CF entry, I presume.\n> \n> RWF seems appropriate. We haven't rejected the concept altogether,\n> AFAICT.\n\nFair enough.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 20 Dec 2019 11:33:02 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Hooks for session start and end, take two" }, { "msg_contents": "On Fri, Dec 20, 2019 at 11:33:02AM -0300, Alvaro Herrera wrote:\n> Fair enough.\n\nAnd done:\nhttps://commitfest.postgresql.org/25/2251/\nSorry for the late reply.\n--\nMichael", "msg_date": "Sat, 21 Dec 2019 11:29:33 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Hooks for session start and end, take two" } ]
[ { "msg_contents": "With the additional functionality, the --help synopsis of pg_checksums\nhas gotten quite long:\n\n pg_checksums enables, disables, or verifies data checksums in a\n PostgreSQL database cluster.\n\nCan we try to shorten this a bit? Maybe\n\n pg_checksums manages data checksums in a PostgreSQL database cluster.\n\nOther ideas?\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 23 Aug 2019 08:19:24 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "pg_checksums --help synopsis is quite long" }, { "msg_contents": "Hello Peter,\n\n> With the additional functionality, the --help synopsis of pg_checksums\n> has gotten quite long:\n>\n> pg_checksums enables, disables, or verifies data checksums in a\n> PostgreSQL database cluster.\n>\n> Can we try to shorten this a bit? Maybe\n>\n> pg_checksums manages data checksums in a PostgreSQL database cluster.\n>\n> Other ideas?\n\nMy 0.02 €:\n\n pg_checksums triggers or verifies checksums in a Postgres cluster.\n\nI like the somehow detailed functionality list, if space allows, so I \ntried to compressed the other parts.\n\nNot sure that there could be a checksum on anything else but data.\n\nI have decided that PostgreSQL is a mouthful, thus I'm rather using \n\"Postgres\".\n\n-- \nFabien.", "msg_date": "Fri, 23 Aug 2019 08:49:12 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: pg_checksums --help synopsis is quite long" }, { "msg_contents": "On Fri, Aug 23, 2019 at 8:49 AM Fabien COELHO <coelho@cri.ensmp.fr> wrote:\n\n>\n> Hello Peter,\n>\n> > With the additional functionality, the --help synopsis of pg_checksums\n> > has gotten quite long:\n> >\n> > pg_checksums enables, disables, or verifies data checksums in a\n> > PostgreSQL database cluster.\n> >\n> > Can we try to shorten this a bit? Maybe\n> >\n> > pg_checksums manages data checksums in a PostgreSQL database cluster.\n> >\n> > Other ideas?\n>\n> My 0.02 €:\n>\n> pg_checksums triggers or verifies checksums in a Postgres cluster.\n>\n\nI think trigger is a bad word to use there, but I was already thinking to\nsuggest something like \"pg_checksums manages or verifies checksums in a\nPostgreSQL cluster\", if that doesn't end up being too long?\n\n\nI like the somehow detailed functionality list, if space allows, so I\n> tried to compressed the other parts.\n>\n> Not sure that there could be a checksum on anything else but data.\n>\n\nYeah, while we call them \"data checksums\" in most places, dropping the word\ndata seems acceptable if we need to in order to get it short enough.\n\n\nI have decided that PostgreSQL is a mouthful, thus I'm rather using\n> \"Postgres\".\n>\n\nChanging that in one tool and not everything would of course be really\nsilly. And if you want to bring up the renaming again, please do so on\npgsql-advocacy as a separate topic :)\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/ <http://www.hagander.net/>\n Work: https://www.redpill-linpro.com/ <http://www.redpill-linpro.com/>\n\nOn Fri, Aug 23, 2019 at 8:49 AM Fabien COELHO <coelho@cri.ensmp.fr> wrote:\nHello Peter,\n\n> With the additional functionality, the --help synopsis of pg_checksums\n> has gotten quite long:\n>\n>   pg_checksums enables, disables, or verifies data checksums in a\n>   PostgreSQL database cluster.\n>\n> Can we try to shorten this a bit?  Maybe\n>\n>   pg_checksums manages data checksums in a PostgreSQL database cluster.\n>\n> Other ideas?\n\nMy 0.02 €:\n\n   pg_checksums triggers or verifies checksums in a Postgres cluster.I think trigger is a bad word to use there, but I was already thinking to suggest something like \"pg_checksums manages or verifies checksums in a PostgreSQL cluster\", if that doesn't end up being too long? I like the somehow detailed functionality list, if space allows, so I \ntried to compressed the other parts.\n\nNot sure that there could be a checksum on anything else but data.Yeah, while we call them \"data checksums\" in most places, dropping the word data seems acceptable if we need to in order to get it short enough.\nI have decided that PostgreSQL is a mouthful, thus I'm rather using \n\"Postgres\".Changing that in one tool and not everything would of course be really silly. And if you want to bring up the renaming again, please do so on pgsql-advocacy as a separate topic :) --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Fri, 23 Aug 2019 09:59:25 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: pg_checksums --help synopsis is quite long" }, { "msg_contents": "On Fri, Aug 23, 2019 at 09:59:25AM +0200, Magnus Hagander wrote:\n> I think trigger is a bad word to use there, but I was already thinking to\n> suggest something like \"pg_checksums manages or verifies checksums in a\n> PostgreSQL cluster\", if that doesn't end up being too long?\n\nDoesn't \"manage\" somewhat include \"verify? I don't find \"trigger\"\nmuch helpful.\n\n> Yeah, while we call them \"data checksums\" in most places, dropping the word\n> data seems acceptable if we need to in order to get it short enough.\n\nIt would like to keep \"data checksums\" in the output, and by using the\nsuggestion of Peter upthread (aka only \"manages\"), the output gets\ndown:\n$ pg_checksums --help | head -n1\npg_checksums manages data checksums in a PostgreSQL database cluster.\n$ pg_checksums --help | head -n1 | wc -c\n70\n\n>> I have decided that PostgreSQL is a mouthful, thus I'm rather using\n>> \"Postgres\".\n> \n> Changing that in one tool and not everything would of course be really\n> silly. And if you want to bring up the renaming again, please do so on\n> pgsql-advocacy as a separate topic :)\n\nIndeed. The official spelling is still \"PostgreSQL\".\n--\nMichael", "msg_date": "Fri, 23 Aug 2019 18:45:35 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pg_checksums --help synopsis is quite long" }, { "msg_contents": "Bonjour Michaᅵl,\n\n> It would like to keep \"data checksums\" in the output,\n\nYou can do as you feel.\n\n>>> I have decided that PostgreSQL is a mouthful, thus I'm rather using\n>>> \"Postgres\".\n>>\n>> Changing that in one tool and not everything would of course be really \n>> silly. And if you want to bring up the renaming again, please do so on \n>> pgsql-advocacy as a separate topic :)\n>\n> Indeed. The official spelling is still \"PostgreSQL\".\n\nYep. I'm using \"Postgres\" wherever & whenever I can as a personal choice, \nbut I'm not planning to campaign about it. Now, it is good to know that \n\"postgres.org\" seems owned by the project.\n\n-- \nFabien.", "msg_date": "Fri, 23 Aug 2019 19:21:44 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: pg_checksums --help synopsis is quite long" } ]
[ { "msg_contents": "Hi,\n\nIt is quite common to set a global statement_timeout to a few seconds\n(or minutes) in postgresql.conf in order to avoid hitting a production\nserver with slow/bad queries.\nThis value is applied to all connections in the system unless it is\nredefined per database, user, or explicitly changed in the connection.\nPg_rewind runs quite a few queries on the primary and if\nstatement_timeout hits one of them it breaks the whole process. I\ncan't tell for sure if this is an unrecoverable error or not and maybe\nthe second run of pg_rewind would be able to finish the process. Even\nin case if retry is possible it makes it hard to use it for reliable\nautomation.\n\nThere are a few workarounds to this problem:\n1. ALTER DATABASE postgres SET statement_timeout = 0;\n2. ALTER rewind_username SET statement_timeout = 0;\n3. Run export PGOPTIONS=\"-c statement_timeout=0\" before calling pg_rwind.\n\nAll of them have certain pros and cons. The third approach works good\nfor automation, but IMHO we should simply fix pg_rewind itself and SET\nstatement_timeout after establishing a connection, so everybody will\nbenefit from it.\n\nPatch attached.\n\nRegards,\n--\nAlexander Kukushkin", "msg_date": "Fri, 23 Aug 2019 10:05:02 +0200", "msg_from": "Alexander Kukushkin <cyberdemn@gmail.com>", "msg_from_op": true, "msg_subject": "Statement timeout in pg_rewind" }, { "msg_contents": "On Fri, Aug 23, 2019 at 10:05:02AM +0200, Alexander Kukushkin wrote:\n> Hi,\n> \n> It is quite common to set a global statement_timeout to a few seconds\n> (or minutes) in postgresql.conf in order to avoid hitting a production\n> server with slow/bad queries.\n\nTrue!\n\nIs pg_rewind the only thing that this hits?\n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate\n\n\n", "msg_date": "Sun, 25 Aug 2019 22:14:10 +0200", "msg_from": "David Fetter <david@fetter.org>", "msg_from_op": false, "msg_subject": "Re: Statement timeout in pg_rewind" }, { "msg_contents": "David Fetter <david@fetter.org> writes:\n> Is pg_rewind the only thing that this hits?\n\npg_dump has forced statement_timeout to 0 for ages. If pg_rewind\nis also likely to have a long-running transaction, I don't see any\ngood reason for it not to do likewise.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 25 Aug 2019 16:30:38 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Statement timeout in pg_rewind" }, { "msg_contents": "On Sun, Aug 25, 2019 at 04:30:38PM -0400, Tom Lane wrote:\n> David Fetter <david@fetter.org> writes:\n> > Is pg_rewind the only thing that this hits?\n> \n> pg_dump has forced statement_timeout to 0 for ages. If pg_rewind\n> is also likely to have a long-running transaction, I don't see any\n> good reason for it not to do likewise.\n\nMy mistake.\n\nI meant to ask whether, in addition to pg_dump and pg_rewind, there\nare other things that should ignore statement_timeout settings.\n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate\n\n\n", "msg_date": "Sun, 25 Aug 2019 22:34:29 +0200", "msg_from": "David Fetter <david@fetter.org>", "msg_from_op": false, "msg_subject": "Re: Statement timeout in pg_rewind" }, { "msg_contents": "On Sun, Aug 25, 2019 at 10:34:29PM +0200, David Fetter wrote:\n> I meant to ask whether, in addition to pg_dump and pg_rewind, there\n> are other things that should ignore statement_timeout settings.\n\nSure. Please note that I am not sure if it is worth bothering about\nall the code paths which emit SQL queries as one thing to consider is\nthat your query \"SET statement_timeout = 0\" could be cancelled by the\nsystem's default, defeating its purpose. (For example, just enforce\nstatement_timeout = 1 into PostgresNode.pm::init and enjoy the show).\nSo any tool that we consider worth fixing should be able to act with\ntimeout values that are realistic. On top of pg_rewind, there is a\npoint to raise about src/bin/scripts/ (just enforce the parameters in\ncommon.c), and vacuumlo which creates a temporary table potentially\nlarge.\n\nAlexander, it seems to me that we should also consider lock_timeout\nand idle_in_transaction_session_timeout (new as of 9.6), no? We could\nalso group the PQexec/PQresultStatus into a simple wrapper which gets\nalso called by run_simple_query().\n--\nMichael", "msg_date": "Mon, 26 Aug 2019 13:27:54 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Statement timeout in pg_rewind" }, { "msg_contents": "Hi,\n\nOn Mon, 26 Aug 2019 at 06:28, Michael Paquier <michael@paquier.xyz> wrote:\n\n> Alexander, it seems to me that we should also consider lock_timeout\n> and idle_in_transaction_session_timeout (new as of 9.6), no? We could\n\nWell, I was thinking about it and came to the conclusion that we are\nneither taking heavy locks nor explicitly opening a transaction and\ntherefore we can avoid changing them.\nBut maybe you are right, having them set to the safe value shouldn't hurt.\n\n> also group the PQexec/PQresultStatus into a simple wrapper which gets\n> also called by run_simple_query().\n\nI don't think we can use the same wrapper for run_simple_query() and\nfor places where we call a SET, because PQresultStatus() returns\nPGRES_TUPLES_OK and PGRES_COMMAND_OK respectively.\nPassing expected ExecStatusType to the wrapper for comparison is\nlooking a bit ugly to me.\n\nRegards,\n--\nAlexander Kukushkin\n\n\n", "msg_date": "Mon, 26 Aug 2019 15:42:46 +0200", "msg_from": "Alexander Kukushkin <cyberdemn@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Statement timeout in pg_rewind" }, { "msg_contents": "On Mon, Aug 26, 2019 at 03:42:46PM +0200, Alexander Kukushkin wrote:\n> Well, I was thinking about it and came to the conclusion that we are\n> neither taking heavy locks nor explicitly opening a transaction and\n> therefore we can avoid changing them.\n> But maybe you are right, having them set to the safe value shouldn't\n> hurt.\n\nI'd rather be on the safe side and as we are looking at this at this\narea.. Who knows if this logic is going to change in the future and\nhow it will change.\n\n> I don't think we can use the same wrapper for run_simple_query() and\n> for places where we call a SET, because PQresultStatus() returns\n> PGRES_TUPLES_OK and PGRES_COMMAND_OK respectively.\n> Passing expected ExecStatusType to the wrapper for comparison is\n> looking a bit ugly to me.\n\nOops, I misread this part. What about a simple wrapper\nrun_simple_command which checks after PGRES_COMMAND_OK, and frees the\nresult then? This could be used for the temporary table creation and\nwhen setting synchronous_commit.\n--\nMichael", "msg_date": "Tue, 27 Aug 2019 15:35:34 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Statement timeout in pg_rewind" }, { "msg_contents": "On Tue, 27 Aug 2019 at 08:36, Michael Paquier <michael@paquier.xyz> wrote:\n\n> I'd rather be on the safe side and as we are looking at this at this\n> area.. Who knows if this logic is going to change in the future and\n> how it will change.\n\nAgree.\n\n> Oops, I misread this part. What about a simple wrapper\n> run_simple_command which checks after PGRES_COMMAND_OK, and frees the\n> result then? This could be used for the temporary table creation and\n> when setting synchronous_commit.\n\nDone, please see the next version attached.\n\nRegards,\n--\nAlexander Kukushkin", "msg_date": "Tue, 27 Aug 2019 10:45:27 +0200", "msg_from": "Alexander Kukushkin <cyberdemn@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Statement timeout in pg_rewind" }, { "msg_contents": "On Tue, Aug 27, 2019 at 10:45:27AM +0200, Alexander Kukushkin wrote:\n> Done, please see the next version attached.\n\nI have made the new error message consistent with run_simple_query to\navoid more work to translators and because it is possible to know\nimmediately the code path involved thanks to the SQL query, then\napplied the fix down to 9.5 where pg_rewind has been added. Please\nnote that your patch had a warning as \"result\" is not needed in\nrun_simple_command().\n\nidle_in_transaction_session_timeout only applies to 9.6 and newer\nversions. lock_timeout (imagine a concurrent lock on pg_class for\nexample) and statement_timeout can cause issues, but the full set gets\ndisabled as your patch did and as mentioned upthread.\n--\nMichael", "msg_date": "Wed, 28 Aug 2019 11:51:33 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Statement timeout in pg_rewind" }, { "msg_contents": "Hi,\n\nThank you, Michael, for committing it!\n\nOn Wed, 28 Aug 2019 at 04:51, Michael Paquier <michael@paquier.xyz> wrote:\n> note that your patch had a warning as \"result\" is not needed in\n> run_simple_command().\n\nOhh, sorry about that. I compiled the whole source tree and the\nwarning was buried down among other output :(\n\nRegards,\n--\nAlexander Kukushkin\n\n\n", "msg_date": "Wed, 28 Aug 2019 10:38:39 +0200", "msg_from": "Alexander Kukushkin <cyberdemn@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Statement timeout in pg_rewind" }, { "msg_contents": "Alexander Kukushkin <cyberdemn@gmail.com> writes:\n> On Wed, 28 Aug 2019 at 04:51, Michael Paquier <michael@paquier.xyz> wrote:\n>> note that your patch had a warning as \"result\" is not needed in\n>> run_simple_command().\n\n> Ohh, sorry about that. I compiled the whole source tree and the\n> warning was buried down among other output :(\n\n\"make -s\" is your friend ...\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 28 Aug 2019 12:29:18 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Statement timeout in pg_rewind" } ]
[ { "msg_contents": "As of PostgreSQL, an appropriately built client will initiate TCP/IP\nconnections with these packets:\n\n1. GSSENCRequest\n2. SSLRequest\n3. StartupMessage\n\nOlder servers will respond to the first one with:\n\nFATAL: unsupported frontend protocol 1234.5680: server supports 2.0 to 3.0\n\nlibpq will then try to reconnect with SSLRequest. So this works out in\npractice, but it will require two TCP/IP connections and leave these\nmessages in the log.\n\nI think we should at least document this somehow in the release notes.\nAlso, third-party implementors of the server protocol should be made\naware of this, again probably via the release notes.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 23 Aug 2019 12:09:26 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "backward compatibility of GSSENCRequest" } ]
[ { "msg_contents": "Hi,\n\nI'm currently working on a tool to visualize an execution plan [1]. For\nthose who know PEV, it's actually a fork of this great tool since it\nhasn't been active for more than 2 years.\n\nAmong other things, I'd like to show information for the parallel\nqueries. First of which is information about the workers.\n\nI'm facing a problem when I am trying to parse a plan in the JSON\nformat. The \"Workers\" key may be duplicated.\n\nWhile it's not invalid to have keys with the same name several times at\nthe same level in a JSON object, it makes it almost impossible to get\nthe full info when parsed. Indeed when parsing such a JSON string only\nthe last key is kept. Part of the information is lost.\n\nJSON validators warn us with the following message : \"Duplicate key,\nnames should be unique.\"\n\nHere's an example of a plan in VERBOSE mode.\n\n[\n {\n \"Plan\": {\n \"Node Type\": \"Gather Merge\",\n \"Parallel Aware\": false,\n \"Actual Startup Time\": 1720.052,\n \"Actual Total Time\": 4252.290,\n \"Actual Rows\": 10000000,\n \"Actual Loops\": 1,\n \"Output\": [\"c1\", \"c2\"],\n \"Workers Planned\": 2,\n \"Workers Launched\": 2,\n \"Plans\": [\n {\n \"Node Type\": \"Sort\",\n \"Parent Relationship\": \"Outer\",\n \"Parallel Aware\": false,\n \"Actual Startup Time\": 1558.638,\n \"Actual Total Time\": 2127.522,\n \"Actual Rows\": 3333333,\n \"Actual Loops\": 3,\n \"Output\": [\"c1\", \"c2\"],\n \"Sort Key\": [\"t1.c1\"],\n \"Sort Method\": \"external merge\",\n \"Sort Space Used\": 126152,\n \"Sort Space Type\": \"Disk\",\n \"Workers\": [\n {\n \"Worker Number\": 0,\n \"Sort Method\": \"external merge\",\n \"Sort Space Used\": 73552,\n \"Sort Space Type\": \"Disk\"\n },\n {\n \"Worker Number\": 1,\n \"Sort Method\": \"external merge\",\n \"Sort Space Used\": 73320,\n \"Sort Space Type\": \"Disk\"\n }\n ],\n \"Workers\": [\n {\n \"Worker Number\": 0,\n \"Actual Startup Time\": 1487.846,\n \"Actual Total Time\": 1996.879,\n \"Actual Rows\": 2692973,\n \"Actual Loops\": 1\n },\n {\n \"Worker Number\": 1,\n \"Actual Startup Time\": 1468.256,\n \"Actual Total Time\": 2012.744,\n \"Actual Rows\": 2684443,\n \"Actual Loops\": 1\n }\n ],\n \"Plans\": [\n {\n \"Node Type\": \"Seq Scan\",\n \"Parent Relationship\": \"Outer\",\n \"Parallel Aware\": true,\n \"Relation Name\": \"t1\",\n \"Schema\": \"public\",\n \"Alias\": \"t1\",\n \"Actual Startup Time\": 0.211,\n \"Actual Total Time\": 372.858,\n \"Actual Rows\": 3333333,\n \"Actual Loops\": 3,\n \"Output\": [\"c1\", \"c2\"],\n \"Workers\": [\n {\n \"Worker Number\": 0,\n \"Actual Startup Time\": 0.029,\n \"Actual Total Time\": 368.356,\n \"Actual Rows\": 2692973,\n \"Actual Loops\": 1\n },\n {\n \"Worker Number\": 1,\n \"Actual Startup Time\": 0.033,\n \"Actual Total Time\": 368.874,\n \"Actual Rows\": 2684443,\n \"Actual Loops\": 1\n }\n ]\n }\n ]\n }\n ]\n },\n \"Planning Time\": 0.170,\n \"Triggers\": [\n ],\n \"Execution Time\": 4695.141\n }\n]\n\nAs you can see, the \"Workers\" key is duplicated in the Sort node.\n\nHere's the equivalent in TEXT format:\n\n---------------------------------\n Gather Merge (cost=735306.27..1707599.95 rows=8333364 width=17)\n(actual time=1560.468..3749.583 rows=10000000 loops=1)\n Output: c1, c2\n Workers Planned: 2\n Workers Launched: 2\n -> Sort (cost=734306.25..744722.95 rows=4166682 width=17) (actual\ntime=1474.182..1967.788 rows=3333333 loops=3)\n Output: c1, c2\n Sort Key: t1.c1\n Sort Method: external merge Disk: 125168kB\n Worker 0: Sort Method: external merge Disk: 73768kB\n Worker 1: Sort Method: external merge Disk: 74088kB\n Worker 0: actual time=1431.136..1883.370 rows=2700666 loops=1\n Worker 1: actual time=1431.175..1891.630 rows=2712505 loops=1\n -> Parallel Seq Scan on public.t1 (cost=0.00..105264.82\nrows=4166682 width=17) (actual time=0.214..386.014 rows=3333333 loops=3)\n Output: c1, c2\n Worker 0: actual time=0.027..382.325 rows=2700666 loops=1\n Worker 1: actual time=0.038..384.951 rows=2712505 loops=1\n Planning Time: 0.180 ms\n Execution Time: 4166.867 ms\n(18 rows)\n---------------------------------\n\nI think that the text format should stay as is.\n\nFor the JSON format however it would be better in my opinion if\n\"Workers\" data is merged. Parsing should not imply anything else than\n\"var myObj = JSON.parse(theJsonString);\".\n\nWhat do you think?\n\nThanks.\n\n[1] https://dalibo.github.io/pev2/\n\n\n", "msg_date": "Fri, 23 Aug 2019 14:47:56 +0200", "msg_from": "Pierre Giraud <pierre.giraud@dalibo.com>", "msg_from_op": true, "msg_subject": "Explain: Duplicate key \"Workers\" in JSON format" }, { "msg_contents": "\nOn 8/23/19 8:47 AM, Pierre Giraud wrote:\n> \"Plans\": [\n> {\n> \"Node Type\": \"Sort\",\n> \"Parent Relationship\": \"Outer\",\n> \"Parallel Aware\": false,\n> \"Actual Startup Time\": 1558.638,\n> \"Actual Total Time\": 2127.522,\n> \"Actual Rows\": 3333333,\n> \"Actual Loops\": 3,\n> \"Output\": [\"c1\", \"c2\"],\n> \"Sort Key\": [\"t1.c1\"],\n> \"Sort Method\": \"external merge\",\n> \"Sort Space Used\": 126152,\n> \"Sort Space Type\": \"Disk\",\n> \"Workers\": [\n> {\n> \"Worker Number\": 0,\n> \"Sort Method\": \"external merge\",\n> \"Sort Space Used\": 73552,\n> \"Sort Space Type\": \"Disk\"\n> },\n> {\n> \"Worker Number\": 1,\n> \"Sort Method\": \"external merge\",\n> \"Sort Space Used\": 73320,\n> \"Sort Space Type\": \"Disk\"\n> }\n> ],\n> \"Workers\": [\n> {\n> \"Worker Number\": 0,\n> \"Actual Startup Time\": 1487.846,\n> \"Actual Total Time\": 1996.879,\n> \"Actual Rows\": 2692973,\n> \"Actual Loops\": 1\n> },\n> {\n> \"Worker Number\": 1,\n> \"Actual Startup Time\": 1468.256,\n> \"Actual Total Time\": 2012.744,\n> \"Actual Rows\": 2684443,\n> \"Actual Loops\": 1\n> }\n> ],\n\n\nYes, that's really awful.\n\n\n...\n\n\n> I think that the text format should stay as is.\n>\n> For the JSON format however it would be better in my opinion if\n> \"Workers\" data is merged. Parsing should not imply anything else than\n> \"var myObj = JSON.parse(theJsonString);\".\n>\n> What do you think?\n>\n\nMaybe a simpler fix would be to rename one set of nodes to\n\"Sort-Workers\" or some such.\n\n\ncheers\n\n\nandrew\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Fri, 23 Aug 2019 09:30:59 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Explain: Duplicate key \"Workers\" in JSON format" }, { "msg_contents": "Hi hackers,\n\nOn Fri, 23 Aug 2019 09:30:59 -0400\nAndrew Dunstan <andrew.dunstan@2ndquadrant.com> wrote:\n\n> On 8/23/19 8:47 AM, Pierre Giraud wrote:\n> > \"Plans\": [\n> > {\n> > \"Node Type\": \"Sort\",\n> > \"Parent Relationship\": \"Outer\",\n> > \"Parallel Aware\": false,\n> > \"Actual Startup Time\": 1558.638,\n> > \"Actual Total Time\": 2127.522,\n> > \"Actual Rows\": 3333333,\n> > \"Actual Loops\": 3,\n> > \"Output\": [\"c1\", \"c2\"],\n> > \"Sort Key\": [\"t1.c1\"],\n> > \"Sort Method\": \"external merge\",\n> > \"Sort Space Used\": 126152,\n> > \"Sort Space Type\": \"Disk\",\n> > \"Workers\": [\n> > {\n> > \"Worker Number\": 0,\n> > \"Sort Method\": \"external merge\",\n> > \"Sort Space Used\": 73552,\n> > \"Sort Space Type\": \"Disk\"\n> > },\n> > {\n> > \"Worker Number\": 1,\n> > \"Sort Method\": \"external merge\",\n> > \"Sort Space Used\": 73320,\n> > \"Sort Space Type\": \"Disk\"\n> > }\n> > ],\n> > \"Workers\": [\n> > {\n> > \"Worker Number\": 0,\n> > \"Actual Startup Time\": 1487.846,\n> > \"Actual Total Time\": 1996.879,\n> > \"Actual Rows\": 2692973,\n> > \"Actual Loops\": 1\n> > },\n> > {\n> > \"Worker Number\": 1,\n> > \"Actual Startup Time\": 1468.256,\n> > \"Actual Total Time\": 2012.744,\n> > \"Actual Rows\": 2684443,\n> > \"Actual Loops\": 1\n> > }\n> > ], \n> \n> Yes, that's really awful.\n> \n> \n> ...\n> \n> \n> > I think that the text format should stay as is.\n> >\n> > For the JSON format however it would be better in my opinion if\n> > \"Workers\" data is merged. Parsing should not imply anything else than\n> > \"var myObj = JSON.parse(theJsonString);\".\n> >\n> > What do you think?\n\nPlease, find in attachment a patch that merge parallel data together.\n\nNote that duplicated keys are discouraged in json specs, but they are forbidden\nin yaml ones. See link in the commit message.\n\nRegards,", "msg_date": "Thu, 5 Dec 2019 17:59:52 +0100", "msg_from": "Jehan-Guillaume de Rorthais <jgdr@dalibo.com>", "msg_from_op": false, "msg_subject": "Re: Explain: Duplicate key \"Workers\" in JSON format" }, { "msg_contents": "We have not fixed this, have we?\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 31 Mar 2020 14:06:50 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Explain: Duplicate key \"Workers\" in JSON format" }, { "msg_contents": "On 2020-03-31 14:06:50 -0300, Alvaro Herrera wrote:\n> We have not fixed this, have we?\n\nI thought we did:\n\ncommit 10013684970453a0ddc86050bba813c611114321\nAuthor: Tom Lane <tgl@sss.pgh.pa.us>\nDate: 2020-01-25 18:16:42 -0500\n\n Clean up EXPLAIN's handling of per-worker details.\n\n Previously, it was possible for EXPLAIN ANALYZE of a parallel query\n to produce several different \"Workers\" fields for a single plan node,\n because different portions of explain.c independently generated\n per-worker data and wrapped that output in separate fields. This\n is pretty bogus, especially for the structured output formats: even\n if it's not technically illegal, most programs would have a hard time\n dealing with such data.\n\n\n", "msg_date": "Tue, 31 Mar 2020 10:16:22 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Explain: Duplicate key \"Workers\" in JSON format" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> We have not fixed this, have we?\n\nIsn't this 10013684970453a0ddc86050bba813c611114321 ?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 31 Mar 2020 13:18:13 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Explain: Duplicate key \"Workers\" in JSON format" }, { "msg_contents": "On 2020-Mar-31, Tom Lane wrote:\n\n> Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> > We have not fixed this, have we?\n> \n> Isn't this 10013684970453a0ddc86050bba813c611114321 ?\n\nAh, right, another thread reporting the same thing, two months after\nthis one.\n\nThanks both :-)\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 31 Mar 2020 14:22:03 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Explain: Duplicate key \"Workers\" in JSON format" } ]
[ { "msg_contents": "Hello team,\n\nThis is the first time I post here, if you can provide some help, would be\nmuch appreciated.\n\nI have an application that can not access the database due to OID value for\nhstore extension is bigger than an integer value. Application uses a NpgSql\ndriver that only supports integer types for OIDs.\n\nWe have a new app version, which uses a new driver version that supports\nbigint and has no issues at all, but for that specific database, we still\nneed to use that old version of the app.\n\nI have searched for a workaround or something that can help us to be able\nto connect to the database, but have not found anything related.\n\nI also tried by dropping, creating extension again, but same result.\n\nDoes any of you know any workaround that can help here?\n\nWe are using postgresql 9.2.24.\n\nThanks.\n\n-- \nCONFIDENTIALITY\nThis e-mail message and any attachments thereto, is \nintended only for use by the addressee(s) named herein and may contain \nlegally privileged and/or confidential information. If you are not the \nintended recipient of this e-mail message, you are hereby notified that any \ndissemination, distribution or copying of this e-mail message, and any \nattachments thereto, is strictly prohibited. If you have received this \ne-mail message in error, please immediately notify the sender and \npermanently delete the original and any copies of this email and any prints \nthereof.\nABSENT AN EXPRESS STATEMENT TO THE CONTRARY HEREINABOVE, THIS \nE-MAIL IS NOT INTENDED AS A SUBSTITUTE FOR A WRITING. Notwithstanding the \nUniform Electronic Transactions Act or the applicability of any other law \nof similar substance and effect, absent an express statement to the \ncontrary hereinabove, this e-mail message its contents, and any attachments \nhereto are not intended to represent an offer or acceptance to enter into a \ncontract and are not otherwise intended to bind the sender, 42Q (or any of \nits subsidiaries), or any other person or entity.", "msg_date": "Fri, 23 Aug 2019 08:58:50 -0500", "msg_from": "Roberto Mireles <roberto.mireles@42-q.com>", "msg_from_op": true, "msg_subject": "Hstore OID bigger than an integer" }, { "msg_contents": "On 2019-Aug-23, Roberto Mireles wrote:\n\n> I have an application that can not access the database due to OID value for\n> hstore extension is bigger than an integer value. Application uses a NpgSql\n> driver that only supports integer types for OIDs.\n\nThat's a bug in Npgsql. OIDs are unsigned.\n\n> I have searched for a workaround or something that can help us to be able\n> to connect to the database, but have not found anything related.\n> \n> I also tried by dropping, creating extension again, but same result.\n\nAs a workaround, it would probably work to change the OID counter back\nto the positive side of the signed value (probably using pg_resetxlog,\nbeware), then drop and recreate the extension.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 23 Aug 2019 11:40:23 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Hstore OID bigger than an integer" }, { "msg_contents": "On Fri, Aug 23, 2019 at 08:58:50AM -0500, Roberto Mireles wrote:\n>Hello team,\n>\n>This is the first time I post here, if you can provide some help, would be\n>much appreciated.\n>\n>I have an application that can not access the database due to OID value for\n>hstore extension is bigger than an integer value. Application uses a NpgSql\n>driver that only supports integer types for OIDs.\n>\n\nI'm not familiar with npgsql, but OID is an unsigned integer. So if you\nhave an OID greater than 2147483647, then that can't be converted into a\n32-bit integer, of course (npgsql likely gets a text value, and then fails\nwhile parsing it).\n\n>We have a new app version, which uses a new driver version that supports\n>bigint and has no issues at all, but for that specific database, we still\n>need to use that old version of the app.\n>\n>I have searched for a workaround or something that can help us to be able\n>to connect to the database, but have not found anything related.\n>\n>I also tried by dropping, creating extension again, but same result.\n>\n>Does any of you know any workaround that can help here?\n>\n>We are using postgresql 9.2.24.\n>\n\nWell, this is likely an issue you should raise with npgsql instead. I'd\nassume they have a way to deal with OID values properly.\n\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Fri, 23 Aug 2019 17:54:16 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Hstore OID bigger than an integer" }, { "msg_contents": "On Fri, Aug 23, 2019 at 9:26 AM Roberto Mireles\n<roberto.mireles@42-q.com> wrote:\n>\n> Hello team,\n>\n> This is the first time I post here, if you can provide some help, would be much appreciated.\n>\n> I have an application that can not access the database due to OID value for hstore extension is bigger than an integer value. Application uses a NpgSql driver that only supports integer types for OIDs.\n>\n> We have a new app version, which uses a new driver version that supports bigint and has no issues at all, but for that specific database, we still need to use that old version of the app.\n>\n> I have searched for a workaround or something that can help us to be able to connect to the database, but have not found anything related.\n>\n> I also tried by dropping, creating extension again, but same result.\n>\n> Does any of you know any workaround that can help here?\n\nA full dump/restore of the database (via pg_dump) might work, as long\nas the oids are not dumped with the database, which I believe to be\nthe default. This ought to reset the oid counter. Some while back,\noids were changed so the counter was table specific (IIRC). Not sure\nwas after 9.2. If it was, upgrading the database (which you should be\nlooking at anyways) might help. Also, raise an issue upstream.\n\nmerlin\n\n\n", "msg_date": "Fri, 23 Aug 2019 12:03:50 -0500", "msg_from": "Merlin Moncure <mmoncure@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Hstore OID bigger than an integer" } ]
[ { "msg_contents": "Hi Folks,\n\n\nI am having trouble setting up replication with Postgres 11.3.\npg_basebackup is taking an unusually long time for an small Postgres\ndatabase. Anything wrong in my configuration or anything I could do to\nspeed up pg_basebackup?\n\n\nI recently upgraded form Postgres 9.2.1. Using a similar postgres\nconfiguration, apart from some updates to config for Postgres 11.3. I am\nusing pg_basebackup to replicate from the master. I am using secure ssh\ntunnel for the replication between master and slave, I.e. there is a ssh\ntunnel that forwards data from the localhost on port 5433 on the slave to\nthe master server’s port 5432.\n\n\npg_basebackup is taking about 30 seconds.\n\nc12-array2-c1:/# du ./path/to/database\n\n249864 ./nimble/var/private/config/versions/group/sodb\n\n\npg_basebackup -D $PGSQL_BASEBKUP_PATH -U $DBUSER -c fast -l $backup_name -h\nlocalhost -p 5433 --wal-method=stream -Pv -s 10\n\n\npostgresql.conf:\n\n….\n\nmax_connections = 100 # (change requires restart)\n\n# Note: Increasing max_connections costs ~400 bytes of shared memory per\n\n# connection slot, plus lock space (see max_locks_per_transaction).\n\n#superuser_reserved_connections = 3 # (change requires restart)\n\nunix_socket_directories = '/var/run/postgresql' # (change requires\nrestart)\n\n…..\n\n# - Security and Authentication -\n\n#authentication_timeout = 1min # 1s-600s\n\n#ssl = off # (change requires restart)\n\n#ssl_ciphers = 'ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH' # allowed SSL\nciphers\n\n # (change requires restart)\n\n#ssl_renegotiation_limit = 512MB # amount of data between\nrenegotiations\n\n#ssl_cert_file = 'server.crt' # (change requires restart)\n\n#ssl_key_file = 'server.key' # (change requires restart)\n\n#ssl_ca_file = '' # (change requires restart)\n\n#ssl_crl_file = '' # (change requires restart)\n\n#password_encryption = on\n\n#db_user_namespace = off\n\n# Kerberos and GSSAPI\n\n#krb_server_keyfile = ''\n\n#krb_srvname = 'postgres' # (Kerberos only)\n\n#krb_caseins_users = off\n\n# - TCP Keepalives -\n\n# see \"man 7 tcp\" for details\n\n#tcp_keepalives_idle = 0 # TCP_KEEPIDLE, in seconds;\n\n # 0 selects the system default\n\n#tcp_keepalives_interval = 0 # TCP_KEEPINTVL, in seconds;\n\n # 0 selects the system default\n\n#tcp_keepalives_count = 0 # TCP_KEEPCNT;\n\n # 0 selects the system default\n\n…..\n\nshared_buffers = 32MB # 32 or 300MB based on model\n\n # (change requires restart)\n\n#temp_buffers = 8MB # min 800kB\n\n….\n\nwork_mem = 10MB # min 64kB\n\n#maintenance_work_mem = 16MB # min 1MB\n\n…..\n\nwal_level = replica # minimal, archive, or hot_standby\n\n # (change requires restart)\n\n#fsync = on # turns forced synchronization on\nor off\n\n#synchronous_commit = on # synchronization level;\n\n # off, local, remote_write, or on\n\nwal_sync_method = open_sync # the default is the first option\n\n # supported by the operating system:\n\n # open_datasync\n\n # fdatasync (default on Linux)\n\n # fsync\n\n # fsync_writethrough\n\n # open_sync\n\n#full_page_writes = on # recover from partial page writes\n\n#wal_buffers = -1 # min 32kB, -1 sets based on\nshared_buffers\n\n # (change requires restart)\n\n#wal_writer_delay = 200ms # 1-10000 milliseconds\n\n#commit_delay = 0 # range 0-100000, in microseconds\n\n#commit_siblings = 5 # range 1-1000\n\n# - Checkpoints -\n\n#checkpoint_segments = 3 # in logfile segments, min 1, 16MB\neach\n\ncheckpoint_timeout = 1min # range 30s-1h\n\n#checkpoint_completion_target = 0.5 # checkpoint target duration, 0.0 -\n1.0\n\n#checkpoint_warning = 30s # 0 disables\n\n# - Archiving -\n\narchive_mode = on # allows archiving to be done\n\n # (change requires restart)\n\narchive_command = '/bin/true' # command to use to archive a logfile segment\n\n # placeholders: %p = path of file to archive\n\n # %f = file name only\n\n # e.g. 'test ! -f /mnt/server/archivedir/%f\n&& cp %p /mnt/server/archivedir/%f'\n\n#archive_timeout = 0 # force a logfile segment switch after this\n\n # number of seconds; 0 disables\n\n…..\n\nmax_wal_senders = 10 # max number of walsender processes\n\n # (change requires restart)\n\nwal_keep_segments = 10 # in logfile segments, 16MB each; 0 disables\n\nwal_sender_timeout = 10s # in milliseconds; 0 disables\n\n# - Master Server -\n\n# These settings are ignored on a standby server.\n\nsynchronous_standby_names = '' # standby servers that provide sync rep\n\n # comma-separated list of application_name\n\n # from standby(s); '*' = all\n\n#vacuum_defer_cleanup_age = 0 # number of xacts by which cleanup is\ndelayed\n\n# - Standby Servers -\n\n# These settings are ignored on a master server.\n\nhot_standby = on # \"on\" allows queries during recovery\n\n # (change requires restart)\n\n#max_standby_archive_delay = 30s # max delay before canceling queries\n\n # when reading WAL from archive;\n\n # -1 allows indefinite delay\n\n#max_standby_streaming_delay = 30s # max delay before canceling queries\n\n # when reading streaming WAL;\n\n # -1 allows indefinite delay\n\nwal_receiver_status_interval = 3s # send replies at least this often\n\n # 0 disables\n\n#hot_standby_feedback = off # send info from standby to prevent\n\n # query conflicts\n\n\nHi Folks,\n\nI am having trouble setting up replication with Postgres 11.3. pg_basebackup is taking an unusually long time for an small Postgres database. Anything wrong in my configuration or anything I could do to speed up pg_basebackup?\n\nI recently upgraded form Postgres 9.2.1. Using a similar postgres configuration,  apart from some updates to config for Postgres 11.3. I am using pg_basebackup to replicate from the master. I am using secure ssh tunnel for the replication between master and slave, I.e. there is a ssh tunnel that forwards data from the localhost on port 5433 on the slave to the master server’s port 5432. \n\npg_basebackup is taking about 30 seconds.\nc12-array2-c1:/# du ./path/to/database\n249864  ./nimble/var/private/config/versions/group/sodb\n\npg_basebackup -D $PGSQL_BASEBKUP_PATH -U $DBUSER -c fast -l $backup_name -h localhost -p 5433 --wal-method=stream -Pv -s 10\n\npostgresql.conf:\n….\nmax_connections = 100                   # (change requires restart)\n# Note:  Increasing max_connections costs ~400 bytes of shared memory per\n# connection slot, plus lock space (see max_locks_per_transaction).\n#superuser_reserved_connections = 3     # (change requires restart)\nunix_socket_directories = '/var/run/postgresql'   # (change requires restart)\n…..\n# - Security and Authentication -\n#authentication_timeout = 1min          # 1s-600s\n#ssl = off                              # (change requires restart)\n#ssl_ciphers = 'ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH'      # allowed SSL ciphers\n                                        # (change requires restart)\n#ssl_renegotiation_limit = 512MB        # amount of data between renegotiations\n#ssl_cert_file = 'server.crt'           # (change requires restart)\n#ssl_key_file = 'server.key'            # (change requires restart)\n#ssl_ca_file = ''                       # (change requires restart)\n#ssl_crl_file = ''                      # (change requires restart)\n#password_encryption = on\n#db_user_namespace = off\n# Kerberos and GSSAPI\n#krb_server_keyfile = ''\n#krb_srvname = 'postgres'               # (Kerberos only)\n#krb_caseins_users = off\n# - TCP Keepalives -\n# see \"man 7 tcp\" for details\n#tcp_keepalives_idle = 0                # TCP_KEEPIDLE, in seconds;\n                                        # 0 selects the system default\n#tcp_keepalives_interval = 0            # TCP_KEEPINTVL, in seconds;\n                                        # 0 selects the system default\n#tcp_keepalives_count = 0               # TCP_KEEPCNT;\n                                        # 0 selects the system default\n…..\nshared_buffers = 32MB     # 32 or 300MB based on model\n                                        # (change requires restart)\n#temp_buffers = 8MB                     # min 800kB\n….\nwork_mem = 10MB                         # min 64kB\n#maintenance_work_mem = 16MB            # min 1MB\n…..\nwal_level = replica               # minimal, archive, or hot_standby\n                                        # (change requires restart)\n#fsync = on                             # turns forced synchronization on or off\n#synchronous_commit = on                # synchronization level;\n                                        # off, local, remote_write, or on\nwal_sync_method = open_sync             # the default is the first option\n                                        # supported by the operating system:\n                                        #   open_datasync\n                                        #   fdatasync (default on Linux)\n                                        #   fsync\n                                        #   fsync_writethrough\n                                        #   open_sync\n#full_page_writes = on                  # recover from partial page writes\n#wal_buffers = -1                       # min 32kB, -1 sets based on shared_buffers\n                                        # (change requires restart)\n#wal_writer_delay = 200ms               # 1-10000 milliseconds\n#commit_delay = 0                       # range 0-100000, in microseconds\n#commit_siblings = 5                    # range 1-1000\n# - Checkpoints -\n#checkpoint_segments = 3                # in logfile segments, min 1, 16MB each\ncheckpoint_timeout = 1min               # range 30s-1h\n#checkpoint_completion_target = 0.5     # checkpoint target duration, 0.0 - 1.0\n#checkpoint_warning = 30s               # 0 disables\n# - Archiving -\narchive_mode = on # allows archiving to be done\n                                # (change requires restart)\narchive_command = '/bin/true' # command to use to archive a logfile segment\n                                # placeholders: %p = path of file to archive\n                                #               %f = file name only\n                                # e.g. 'test ! -f /mnt/server/archivedir/%f && cp %p /mnt/server/archivedir/%f'\n#archive_timeout = 0            # force a logfile segment switch after this\n                                # number of seconds; 0 disables\n…..\nmax_wal_senders = 10  # max number of walsender processes\n                                # (change requires restart)\nwal_keep_segments = 10  # in logfile segments, 16MB each; 0 disables\nwal_sender_timeout = 10s      # in milliseconds; 0 disables\n# - Master Server -\n# These settings are ignored on a standby server.\nsynchronous_standby_names = '' # standby servers that provide sync rep\n                                # comma-separated list of application_name\n                                # from standby(s); '*' = all\n#vacuum_defer_cleanup_age = 0   # number of xacts by which cleanup is delayed\n# - Standby Servers -\n# These settings are ignored on a master server.\nhot_standby = on           # \"on\" allows queries during recovery\n                                        # (change requires restart)\n#max_standby_archive_delay = 30s        # max delay before canceling queries\n                                        # when reading WAL from archive;\n                                        # -1 allows indefinite delay\n#max_standby_streaming_delay = 30s      # max delay before canceling queries\n                                        # when reading streaming WAL;\n                                        # -1 allows indefinite delay\nwal_receiver_status_interval = 3s       # send replies at least this often\n                                        # 0 disables\n#hot_standby_feedback = off             # send info from standby to prevent\n                                        # query conflicts", "msg_date": "Fri, 23 Aug 2019 20:24:47 -0700", "msg_from": "andy andy <brookline.andy@gmail.com>", "msg_from_op": true, "msg_subject": "pg_basebackup is taking an unusually long time with Postgres 11.3" } ]
[ { "msg_contents": "Hi,\n\nllvmjit_inline.cpp:177:55: error: ‘make_unique’ is not a member of ‘llvm’\n std::unique_ptr<ImportMapTy> globalsToInline =\nllvm::make_unique<ImportMapTy>();\n\nThat's because they just moved to C++14 and replaced their own\nllvm::make_unique<> with std::make_unique<>:\n\nhttps://github.com/llvm-mirror/llvm/commit/114087caa6f95b526861c3af94b3093d9444c57b\n\nPerhaps we'll need some macrology to select between llvm and std\nversions? I am guessing we can't decree that PostgreSQL's minimum C++\nlevel is C++14 and simply change it to std::make_unique.\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Sun, 25 Aug 2019 08:08:11 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "LLVM breakage on seawasp" }, { "msg_contents": "Hi,\n\nOn August 24, 2019 1:08:11 PM PDT, Thomas Munro <thomas.munro@gmail.com> wrote:\n>Hi,\n>\n>llvmjit_inline.cpp:177:55: error: ‘make_unique’ is not a member of\n>‘llvm’\n> std::unique_ptr<ImportMapTy> globalsToInline =\n>llvm::make_unique<ImportMapTy>();\n>\n>That's because they just moved to C++14 and replaced their own\n>llvm::make_unique<> with std::make_unique<>:\n>\n>https://github.com/llvm-mirror/llvm/commit/114087caa6f95b526861c3af94b3093d9444c57b\n>\n>Perhaps we'll need some macrology to select between llvm and std\n>versions? I am guessing we can't decree that PostgreSQL's minimum C++\n>level is C++14 and simply change it to std::make_unique.\n\nPerhaps just a\n#if new_enough\nusing std::make_unique\n#else\nusing llvm::mak_eunique\n\nAt the start of the file, and then use it unqualified?\n\nAndres\n-- \nSent from my Android device with K-9 Mail. Please excuse my brevity.\n\n\n", "msg_date": "Sat, 24 Aug 2019 13:24:09 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LLVM breakage on seawasp" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On August 24, 2019 1:08:11 PM PDT, Thomas Munro <thomas.munro@gmail.com> wrote:\n>> That's because they just moved to C++14 and replaced their own\n>> llvm::make_unique<> with std::make_unique<>:\n>> https://github.com/llvm-mirror/llvm/commit/114087caa6f95b526861c3af94b3093d9444c57b\n>> Perhaps we'll need some macrology to select between llvm and std\n>> versions? I am guessing we can't decree that PostgreSQL's minimum C++\n>> level is C++14 and simply change it to std::make_unique.\n\nSo we're depending on APIs that upstream doesn't think are stable?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 24 Aug 2019 16:57:56 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: LLVM breakage on seawasp" }, { "msg_contents": "Hi,\n\nOn August 24, 2019 1:57:56 PM PDT, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>Andres Freund <andres@anarazel.de> writes:\n>> On August 24, 2019 1:08:11 PM PDT, Thomas Munro\n><thomas.munro@gmail.com> wrote:\n>>> That's because they just moved to C++14 and replaced their own\n>>> llvm::make_unique<> with std::make_unique<>:\n>>>\n>https://github.com/llvm-mirror/llvm/commit/114087caa6f95b526861c3af94b3093d9444c57b\n>>> Perhaps we'll need some macrology to select between llvm and std\n>>> versions? I am guessing we can't decree that PostgreSQL's minimum\n>C++\n>>> level is C++14 and simply change it to std::make_unique.\n>\n>So we're depending on APIs that upstream doesn't think are stable?\n\n Seawasp iirc builds against the development branch of llvm, which explains why we see failures there. Does that address what you are concerned about? If not, could you expand?\n\nAndres\n-- \nSent from my Android device with K-9 Mail. Please excuse my brevity.\n\n\n", "msg_date": "Sat, 24 Aug 2019 14:11:00 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LLVM breakage on seawasp" }, { "msg_contents": "On Sun, Aug 25, 2019 at 8:24 AM Andres Freund <andres@anarazel.de> wrote:\n> On August 24, 2019 1:08:11 PM PDT, Thomas Munro <thomas.munro@gmail.com> wrote:\n> >Perhaps we'll need some macrology to select between llvm and std\n> >versions? I am guessing we can't decree that PostgreSQL's minimum C++\n> >level is C++14 and simply change it to std::make_unique.\n>\n> Perhaps just a\n> #if new_enough\n> using std::make_unique\n> #else\n> using llvm::mak_eunique\n>\n> At the start of the file, and then use it unqualified?\n\nYeah, it's a pain though, you'd have to say:\n\n#if llvm >= 9\n# if cpp >= 14\n# using std::make_unique;\n# else\n# error \"postgres needs at least c++ 14 to use llvm 9\"\n# endif\n#else\n# using llvm::make_unique;\n#endif\n\nMaybe we should just use std::unique_ptr's constructor, ie give it new\nImportMayTy() instead of using make_unique(), even though that's not\ncool C++ these days?\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Sun, 25 Aug 2019 09:15:35 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: LLVM breakage on seawasp" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On August 24, 2019 1:57:56 PM PDT, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> So we're depending on APIs that upstream doesn't think are stable?\n\n> Seawasp iirc builds against the development branch of llvm, which explains why we see failures there. Does that address what you are concerned about? If not, could you expand?\n\nI know it's the development branch. The question is whether this\nbreakage is something *they* ought to be fixing. If not, I'm\nworried that we're too much in bed with implementation details\nof LLVM that we shouldn't be depending on.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 24 Aug 2019 17:37:55 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: LLVM breakage on seawasp" }, { "msg_contents": "Hi,\n\nOn August 24, 2019 2:37:55 PM PDT, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>Andres Freund <andres@anarazel.de> writes:\n>> On August 24, 2019 1:57:56 PM PDT, Tom Lane <tgl@sss.pgh.pa.us>\n>wrote:\n>>> So we're depending on APIs that upstream doesn't think are stable?\n>\n>> Seawasp iirc builds against the development branch of llvm, which\n>explains why we see failures there. Does that address what you are\n>concerned about? If not, could you expand?\n>\n>I know it's the development branch. The question is whether this\n>breakage is something *they* ought to be fixing. If not, I'm\n>worried that we're too much in bed with implementation details\n>of LLVM that we shouldn't be depending on.\n\nDon't think so - it's a C++ standard feature in the version of the standard LLVM is based on. So it's pretty reasonable for them to drop their older backwards compatible function.\n\nAccess\n-- \nSent from my Android device with K-9 Mail. Please excuse my brevity.\n\n\n", "msg_date": "Sat, 24 Aug 2019 14:39:32 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LLVM breakage on seawasp" }, { "msg_contents": "Hi,\n\nOn 2019-08-25 09:15:35 +1200, Thomas Munro wrote:\n> On Sun, Aug 25, 2019 at 8:24 AM Andres Freund <andres@anarazel.de> wrote:\n> > On August 24, 2019 1:08:11 PM PDT, Thomas Munro <thomas.munro@gmail.com> wrote:\n> > >Perhaps we'll need some macrology to select between llvm and std\n> > >versions? I am guessing we can't decree that PostgreSQL's minimum C++\n> > >level is C++14 and simply change it to std::make_unique.\n> >\n> > Perhaps just a\n> > #if new_enough\n> > using std::make_unique\n> > #else\n> > using llvm::mak_eunique\n> >\n> > At the start of the file, and then use it unqualified?\n> \n> Yeah, it's a pain though, you'd have to say:\n> \n> #if llvm >= 9\n> # if cpp >= 14\n> # using std::make_unique;\n> # else\n> # error \"postgres needs at least c++ 14 to use llvm 9\"\n> # endif\n> #else\n> # using llvm::make_unique;\n> #endif\n\nI don't think we'd really need the inner part, because you can't use\nllvm 9 without a new enough compiler. There's plenty make_unique use in\ninline functions etc.\n\n\n> Maybe we should just use std::unique_ptr's constructor, ie give it new\n> ImportMayTy() instead of using make_unique(), even though that's not\n> cool C++ these days?\n\nYea, wfm. do you want to make it so?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sat, 24 Aug 2019 14:46:54 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: LLVM breakage on seawasp" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On August 24, 2019 2:37:55 PM PDT, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I know it's the development branch. The question is whether this\n>> breakage is something *they* ought to be fixing. If not, I'm\n>> worried that we're too much in bed with implementation details\n>> of LLVM that we shouldn't be depending on.\n\n> Don't think so - it's a C++ standard feature in the version of the standard LLVM is based on. So it's pretty reasonable for them to drop their older backwards compatible function.\n\nWhether it's reasonable or not doesn't really matter to my point.\nWe shouldn't be in the business of tracking multitudes of small\nchanges in LLVM, no matter whether they're individually \"reasonable\".\nThe more often this happens, the more concerned I am that we chose\nthe wrong semantic level to interface at.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 24 Aug 2019 17:54:50 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: LLVM breakage on seawasp" }, { "msg_contents": "On Sun, Aug 25, 2019 at 9:46 AM Andres Freund <andres@anarazel.de> wrote:\n> > Maybe we should just use std::unique_ptr's constructor, ie give it new\n> > ImportMayTy() instead of using make_unique(), even though that's not\n> > cool C++ these days?\n>\n> Yea, wfm. do you want to make it so?\n\nDone.\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Sun, 25 Aug 2019 14:56:55 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: LLVM breakage on seawasp" } ]
[ { "msg_contents": "Core was generated by `postgres: telsasoft ts 10.100.2.162(33500) SELECT '.\nProgram terminated with signal 6, Aborted.\n#0 0x00000039ff6325e5 in raise (sig=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64\n64 return INLINE_SYSCALL (tgkill, 3, pid, selftid, sig);\nMissing separate debuginfos, use: debuginfo-install audit-libs-2.4.5-3.el6.x86_64 cyrus-sasl-lib-2.1.23-15.el6_6.2.x86_64 geos36-3.6.3-1.rhel6.1.x86_64 json-c-0.11-12.el6.x86_64 keyutils-libs-1.4-5.el6.x86_64 libcom_err-1.41.12-22.el6.x86_64 libgcc-4.4.7-17.el6.x86_64 libicu-4.2.1-14.el6.x86_64 libselinux-2.0.94-7.el6.x86_64 libstdc++-4.4.7-17.el6.x86_64 nspr-4.11.0-1.el6.x86_64 nss-3.21.0-8.el6.x86_64 nss-softokn-freebl-3.14.3-23.3.el6_8.x86_64 nss-util-3.21.0-2.el6.x86_64 postgis24_11-2.4.5-1.rhel6.1.x86_64 proj49-4.9.3-3.rhel6.1.x86_64 zlib-1.2.3-29.el6.x86_64\n(gdb) bt\n#0 0x00000039ff6325e5 in raise (sig=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64\n#1 0x00000039ff633dc5 in abort () at abort.c:92\n#2 0x00000039ff6704f7 in __libc_message (do_abort=2, fmt=0x39ff758a60 \"*** glibc detected *** %s: %s: 0x%s ***\\n\") at ../sysdeps/unix/sysv/linux/libc_fatal.c:198\n#3 0x00000039ff675f3e in malloc_printerr (action=3, str=0x39ff758df0 \"double free or corruption (!prev)\", ptr=<value optimized out>, ar_ptr=<value optimized out>) at malloc.c:6360\n#4 0x00000039ff678dd0 in _int_free (av=0x39ff98e120, p=0x1d40b090, have_lock=0) at malloc.c:4846\n#5 0x00000000006269e5 in ExecHashJoinNewBatch (pstate=0x2771218) at nodeHashjoin.c:1058\n#6 ExecHashJoinImpl (pstate=0x2771218) at nodeHashjoin.c:539\n#7 ExecHashJoin (pstate=0x2771218) at nodeHashjoin.c:565\n#8 0x00000000006131d0 in ExecProcNodeInstr (node=0x2771218) at execProcnode.c:461\n#9 0x0000000000633286 in ExecProcNode (pstate=0x2771108) at ../../../src/include/executor/executor.h:247\n#10 ExecSort (pstate=0x2771108) at nodeSort.c:107\n#11 0x00000000006131d0 in ExecProcNodeInstr (node=0x2771108) at execProcnode.c:461\n#12 0x000000000061d51e in ExecProcNode (aggstate=0x2770d30) at ../../../src/include/executor/executor.h:247\n#13 fetch_input_tuple (aggstate=0x2770d30) at nodeAgg.c:406\n#14 0x000000000061ee70 in agg_retrieve_direct (pstate=0x2770d30) at nodeAgg.c:1755\n#15 ExecAgg (pstate=0x2770d30) at nodeAgg.c:1570\n#16 0x00000000006131d0 in ExecProcNodeInstr (node=0x2770d30) at execProcnode.c:461\n#17 0x000000000060f4b7 in ExecProcNode (queryDesc=0x2940950, direction=<value optimized out>, count=0, execute_once=48) at ../../../src/include/executor/executor.h:247\n#18 ExecutePlan (queryDesc=0x2940950, direction=<value optimized out>, count=0, execute_once=48) at execMain.c:1723\n#19 standard_ExecutorRun (queryDesc=0x2940950, direction=<value optimized out>, count=0, execute_once=48) at execMain.c:364\n#20 0x00007ff08f74f618 in pgss_ExecutorRun (queryDesc=0x2940950, direction=ForwardScanDirection, count=0, execute_once=true) at pg_stat_statements.c:892\n#21 0x00007ff08f2cc81d in explain_ExecutorRun (queryDesc=0x2940950, direction=ForwardScanDirection, count=0, execute_once=true) at auto_explain.c:281\n#22 0x000000000075444b in PortalRunSelect (portal=0x2571f00, forward=<value optimized out>, count=0, dest=<value optimized out>) at pquery.c:932\n#23 0x0000000000755631 in PortalRun (portal=0x2571f00, count=9223372036854775807, isTopLevel=true, run_once=true, dest=0x928e7a8, altdest=0x928e7a8, completionTag=0x7ffcaa940670 \"\") at pquery.c:773\n#24 0x0000000000752267 in exec_simple_query (\n query_string=0x2753e08 \"--BEGIN SQL\\nSELECT * FROM\\n\\n(SELECT site_office AS site_gran,\\n \\tsite_location AS cell,\\n\\tdisplay_site_name (sect_name, site_name, sect_mscid) AS sitename,\\n\\tperiod, data_cell.bh_day,\\n\\n\", '-' <repeats 17 times>, \"Ac\"...) at postgres.c:1145\n#25 0x0000000000753211 in PostgresMain (argc=<value optimized out>, argv=<value optimized out>, dbname=0x252b1f8 \"ts\", username=<value optimized out>) at postgres.c:4182\n#26 0x00000000006e2587 in BackendRun (argc=<value optimized out>, argv=<value optimized out>) at postmaster.c:4358\n#27 BackendStartup (argc=<value optimized out>, argv=<value optimized out>) at postmaster.c:4030\n#28 ServerLoop (argc=<value optimized out>, argv=<value optimized out>) at postmaster.c:1707\n#29 PostmasterMain (argc=<value optimized out>, argv=<value optimized out>) at postmaster.c:1380\n#30 0x0000000000656a80 in main (argc=3, argv=0x24f7570) at main.c:228\n\nI found this report from 9.6 last month; copying those parties.\nhttps://www.postgresql.org/message-id/CAHyXU0xzwzgnUTyK62ZkG0_1CQsBHwnTVT2TSX7iwTEv1ve9ag%40mail.gmail.com\n\nMerlin: what OS are you running on and what postgres package, or was it\ncompiled locally ?\n\nWe're running:\npostgresql11-server-11.5-1PGDG.rhel6.x86_64\nCentOS release 6.8\nglibc-2.12-1.192.el6.x86_64\nlinux 2.6.32-754.3.5.el6.x86_64\nDMI: VMware, Inc. VMware Virtual Platform/440BX Desktop Reference Platform, BIOS 6.00 09/21/2015\nModel name: Intel(R) Xeon(R) CPU E5-2683 v4 @ 2.10GHz\n\nI see this is available but not installed: 2.12-1.212.el6_10.3\n\nThe VM has no known issues.\n\nts=# SELECT * FROM pg_config();\n..\n| CONFIGURE | '--enable-rpath' '--prefix=/usr/pgsql-11' '--includedir=/usr/pgsql-11/include' '--mandir=/usr/pgsql-11/share/man' '--datadir=/usr/pgsql-11/share' '--libdir=/usr/pgsql-11/lib' '--with-icu' '--with-perl' '--with-python' '--with-tcl' '--with-tclconfig=/usr/lib64' '--with-openssl' '--with-pam' '--with-gssapi' '--with-includes=/usr/include' '--with-libraries=/usr/lib64' '--enable-nls' '--with-uuid=e2fs' '--with-libxml' '--with-libxslt' '--with-ldap' '--with-system-tzdata=/usr/share/zoneinfo' '--sysconfdir=/etc/sysconfig/pgsql' '--docdir=/usr/pgsql-11/doc' '--htmldir=/usr/pgsql-11/doc/html' 'CFLAGS=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic' 'LDFLAGS=-Wl,--as-needed' 'PKG_CONFIG_PATH=:/usr/lib64/pkgconfig:/usr/share/pkgconfig' 'ICU_CFLAGS=-I/usr/include' 'ICU_LIBS=-L/usr/lib64 -licui18n -licuuc -licudata'\n| CC | gcc\n| CPPFLAGS | -I/usr/include -D_GNU_SOURCE -I/usr/include/libxml2 -I/usr/include\n| CFLAGS | -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic\n| CFLAGS_SL | -fPIC\n| LDFLAGS | -Wl,--as-needed -L/usr/lib64 -Wl,--as-needed -Wl,-rpath,'/usr/pgsql-11/lib',--enable-new-dtags\n| LDFLAGS_EX | \n| LDFLAGS_SL | \n| LIBS | -lpgcommon -lpgport -lpthread -lxslt -lxml2 -lpam -lssl -lcrypto -lgssapi_krb5 -lz -lreadline -lrt -lcrypt -ldl -lm \n\n#0 0x00000039ff6325e5 in raise (sig=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64\n resultvar = 0\n pid = <value optimized out>\n selftid = <value optimized out>\n#1 0x00000039ff633dc5 in abort () at abort.c:92\n save_stage = 2\n act = {__sigaction_handler = {sa_handler = 0x7ffcaa93f5c8, sa_sigaction = 0x7ffcaa93f5c8}, sa_mask = {__val = {140723170309552, 140723170319605, 49, 249099024494, 3, 140723170309562, 6, \n 249099024498, 2, 140723170309550, 2, 249099017763, 1, 249099024494, 3, 140723170309558}}, sa_flags = 10, sa_restorer = 0x39ff757872}\n sigs = {__val = {32, 0 <repeats 15 times>}}\n#2 0x00000039ff6704f7 in __libc_message (do_abort=2, fmt=0x39ff758a60 \"*** glibc detected *** %s: %s: 0x%s ***\\n\") at ../sysdeps/unix/sysv/linux/libc_fatal.c:198\n ap = {{gp_offset = 40, fp_offset = 48, overflow_arg_area = 0x7ffcaa93ff30, reg_save_area = 0x7ffcaa93fe40}}\n ap_copy = {{gp_offset = 16, fp_offset = 48, overflow_arg_area = 0x7ffcaa93ff30, reg_save_area = 0x7ffcaa93fe40}}\n fd = 2\n on_2 = <value optimized out>\n list = <value optimized out>\n nlist = <value optimized out>\n cp = <value optimized out>\n written = <value optimized out>\n#3 0x00000039ff675f3e in malloc_printerr (action=3, str=0x39ff758df0 \"double free or corruption (!prev)\", ptr=<value optimized out>, ar_ptr=<value optimized out>) at malloc.c:6360\n buf = \"000000001d40b0a0\"\n cp = <value optimized out>\n#4 0x00000039ff678dd0 in _int_free (av=0x39ff98e120, p=0x1d40b090, have_lock=0) at malloc.c:4846\n size = <value optimized out>\n fb = <value optimized out>\n nextchunk = <value optimized out>\n nextsize = <value optimized out>\n nextinuse = <value optimized out>\n prevsize = <value optimized out>\n bck = <value optimized out>\n fwd = <value optimized out>\n errstr = <value optimized out>\n locked = <value optimized out>\n#5 0x00000000006269e5 in ExecHashJoinNewBatch (pstate=0x2771218) at nodeHashjoin.c:1058\n nbatch = <value optimized out>\n curbatch = <value optimized out>\n slot = <value optimized out>\n hashvalue = 1756558929\n hashtable = 0x3c4ed48\n innerFile = 0x1d40b0d8\n#6 ExecHashJoinImpl (pstate=0x2771218) at nodeHashjoin.c:539\n outerNode = 0x27714d8\n hashNode = 0x2772348\n econtext = <value optimized out>\n node = 0x2771218\n joinqual = 0x0\n otherqual = 0x0\n---Type <return> to continue, or q <return> to quit---\n hashtable = 0xc8\n hashvalue = 0\n batchno = 41357576\n parallel_state = <value optimized out>\n#7 ExecHashJoin (pstate=0x2771218) at nodeHashjoin.c:565\nNo locals.\n#8 0x00000000006131d0 in ExecProcNodeInstr (node=0x2771218) at execProcnode.c:461\n result = <value optimized out>\n#9 0x0000000000633286 in ExecProcNode (pstate=0x2771108) at ../../../src/include/executor/executor.h:247\nNo locals.\n#10 ExecSort (pstate=0x2771108) at nodeSort.c:107\n plannode = <value optimized out>\n outerNode = 0x2771218\n tupDesc = <value optimized out>\n node = 0x2771108\n estate = 0x2770a40\n dir = ForwardScanDirection\n tuplesortstate = 0x3c87160\n slot = <value optimized out>\n...\n\n\nIf GDB isn't lying and I'm not being confuse by git, that's:\n BufFileClose(innerFile);\n\nWhich does (at least):\n\n pfree(file->files);\n pfree(file->offsets);\n pfree(file);\n\n\n(gdb) p *innerFile\n$2 = {numFiles = 1, files = 0xa421328, offsets = 0xa421310, isInterXact = false, dirty = false, readOnly = false, fileset = 0x0, name = 0x0, resowner = 0x24f93e0, curFile = 0, curOffset = 73016512, \n pos = 0, nbytes = 0, buffer = {\n data = '\\000' <repeats 44 times>, \"Q\\366\\262h\\220\\004\\000\\000\\000\\000\\000\\000\\000\\000L\\000\\003\\000(\\377\\377\\377\\377\\377\\177\\372\\377\\377\\017\\000\\000\\000\\000\\000\\000\\000\\000\\257\\321\\345\\333\\063\\002\\000\\003\", '\\000' <repeats 23 times>\"\\204, \\003\\000\\000\\000\\000\\000\\000K\\000\\000\\000\\000\\000\\000\\000K\\000\\000\\000\\000\\000\\000\\000K\\000\\000\\000\\000\\000\\000\\000K\\000\\000\\000\\000\\000\\000\\000b\\000\\000\\000\\000\\000\\000\\000c\\000\\000\\000\\000\\000\\000\\000c\\000\\000\\000\\000\\000\\000\\000d\", '\\000' <repeats 15 times>, \"q\\002\\000\\000\\000\\000\\000\\000d\", '\\000' <repeats 23 times>, \"I\\000\\000\\000\\000\\000\\000\\000\\344H\\a\\000\\000\\000\\000\\000\\017\\000\\210\\026\\000\\310\\024\\000\\024H\\000\\000\\000\\000\\000\\000\\017\\000\\210\\035\\000H!\\027\\000\\210\\216\\000T\\vB\\017\\304\\t\\027\\000\\210\\a\\000\\206\\b\\033\\030.\\\"\", '\\000' <repeats 11 times>..., force_align_d = 0, force_align_i64 = 0}}\n\n(gdb) p innerFile->files[0]\n$8 = 2397\n\n\n\n\n", "msg_date": "Sat, 24 Aug 2019 21:25:01 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": true, "msg_subject": "pg11.5: ExecHashJoinNewBatch: glibc detected...double free or\n corruption (!prev)" }, { "msg_contents": "On Sat, Aug 24, 2019 at 7:25 PM Justin Pryzby <pryzby@telsasoft.com> wrote:\n> Merlin: what OS are you running on and what postgres package, or was it\n> compiled locally ?\n\nI was reminded of this issue from last year, which also appeared to\ninvolve BufFileClose() and a double-free:\n\nhttps://postgr.es/m/87y3hmee19.fsf@news-spur.riddles.org.uk\n\nThat was a BufFile that was under the control of a tuplestore, so it\nwas similar to but different from your case. I suspect it's related.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Sat, 24 Aug 2019 20:15:34 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: pg11.5: ExecHashJoinNewBatch: glibc detected...double free or\n corruption (!prev)" }, { "msg_contents": "On Sun, Aug 25, 2019 at 3:15 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> I was reminded of this issue from last year, which also appeared to\n> involve BufFileClose() and a double-free:\n>\n> https://postgr.es/m/87y3hmee19.fsf@news-spur.riddles.org.uk\n>\n> That was a BufFile that was under the control of a tuplestore, so it\n> was similar to but different from your case. I suspect it's related.\n\nHmm. tuplestore.c follows the same coding pattern as nodeHashjoin.c:\nit always nukes its pointer after calling BufFileFlush(), so it\nshouldn't be capable of calling it twice for the same pointer, unless\nwe have two copies of that pointer somehow.\n\nMerlin's reported a double-free apparently in ExecHashJoin(), not\nExecHashJoinNewBatch() like this report. Unfortunately that tells us\nvery little.\n\nOn Sun, Aug 25, 2019 at 2:25 PM Justin Pryzby <pryzby@telsasoft.com> wrote:\n> #4 0x00000039ff678dd0 in _int_free (av=0x39ff98e120, p=0x1d40b090, have_lock=0) at malloc.c:4846\n> #5 0x00000000006269e5 in ExecHashJoinNewBatch (pstate=0x2771218) at nodeHashjoin.c:1058\n\nCan you reproduce this or was it a one-off crash?\n\nHmm. We don't have enough stack frames to know where in here, and\npresumably aset.c, this is, but as you noted it's got to be somewhere\nhere:\n\nvoid\nBufFileClose(BufFile *file)\n{\n int i;\n\n /* flush any unwritten data */\n BufFileFlush(file);\n /* close and delete the underlying file(s) */\n for (i = 0; i < file->numFiles; i++)\n FileClose(file->files[i]);\n /* release the buffer space */\n pfree(file->files);\n pfree(file->offsets);\n pfree(file);\n}\n\nBufFileFlush() and FileClose() don't seem to be able to reach free().\npfree() always reaches free() for sizes > allocChunkLimit (8KB in\nExecutorState). Given numFiles = 1 (as you showed), I expect\nfile->files and file->offsets to be small allocations, and file itself\nto be large due to the 8KB buffer inside it.\n\nSome possibilities:\n\n1. Somehow we actually called BufFileClose() twice. Hard to see how\nwe'd do that, as mentioned.\n\n2. Somehow the BufFile was created in the wrong memory context, and\nthe memory was freed earlier. Note that ExecHashJoinSaveTuple()'s\ncomment requires you to call it with CurrentMemoryContext == the\nexecutor context, but nothing in the code enforces that. As for the\ntuplestore.c case, note also that tuplestore.c explicitly sets\nCurrentResourceOwner, but not CurrentMemoryContext. I suppose there\nmight be some obscure path somewhere, possibly through a custom\noperator or suchlike, that leaves us in a strange memory context, or\nsomething like that? But then I feel like we'd have received\nreproducible reports and a test case by now.\n\n3. Random memory corruption caused by buffer overrun who-knows-where.\n\n> glibc-2.12-1.192.el6.x86_64\n> linux 2.6.32-754.3.5.el6.x86_64\n\nGreetings, time traveller! I see that the tuplestore.c report was\nalso on a system of that vintage. Hmm.\n\n> #10 ExecSort (pstate=0x2771108) at nodeSort.c:107\n> plannode = <value optimized out>\n> outerNode = 0x2771218\n> tupDesc = <value optimized out>\n> node = 0x2771108\n> estate = 0x2770a40\n> dir = ForwardScanDirection\n> tuplesortstate = 0x3c87160\n> slot = <value optimized out>\n\nIt's interesting that a sort was involved here and it owns a\ntuplestore, but hard to see the connection.\n\n> (gdb) p *innerFile\n> $2 = {numFiles = 1, files = 0xa421328, offsets = 0xa421310, isInterXact = false, dirty = false, readOnly = false, fileset = 0x0, name = 0x0, resowner = 0x24f93e0, curFile = 0, curOffset = 73016512,\n>\n> pos = 0, nbytes = 0, buffer = {\n> data = '\\000' <repeats 44 times>, \"Q\\366\\262h\\220\\004\\000\\000\\000\\000\\000\\000\\000\\000L\\000\\003\\000(\\377\\377\\377\\377\\377\\177\\372\\377\\377\\017\\000\\000\\000\\000\\000\\000\\000\\000\\257\\321\\345\\333\\063\\002\\000\\003\", '\\000' <repeats 23 times>\"\\204, \\003\\000\\000\\000\\000\\000\\000K\\000\\000\\000\\000\\000\\000\\000K\\000\\000\\000\\000\\000\\000\\000K\\000\\000\\000\\000\\000\\000\\000K\\000\\000\\000\\000\\000\\000\\000b\\000\\000\\000\\000\\000\\000\\000c\\000\\000\\000\\000\\000\\000\\000c\\000\\000\\000\\000\\000\\000\\000d\", '\\000' <repeats 15 times>, \"q\\002\\000\\000\\000\\000\\000\\000d\", '\\000' <repeats 23 times>, \"I\\000\\000\\000\\000\\000\\000\\000\\344H\\a\\000\\000\\000\\000\\000\\017\\000\\210\\026\\000\\310\\024\\000\\024H\\000\\000\\000\\000\\000\\000\\017\\000\\210\\035\\000H!\\027\\000\\210\\216\\000T\\vB\\017\\304\\t\\027\\000\\210\\a\\000\\206\\b\\033\\030.\\\"\", '\\000' <repeats 11 times>..., force_align_d = 0, force_align_i64 = 0}}\n>\n> (gdb) p innerFile->files[0]\n> $8 = 2397\n\nHmm. That all looks pretty sane from here, but tells us nothing about\nwhether it was already freed and if so where.\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Mon, 26 Aug 2019 13:09:19 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg11.5: ExecHashJoinNewBatch: glibc detected...double free or\n corruption (!prev)" }, { "msg_contents": "On Mon, Aug 26, 2019 at 01:09:19PM +1200, Thomas Munro wrote:\n> On Sun, Aug 25, 2019 at 3:15 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> > I was reminded of this issue from last year, which also appeared to\n> > involve BufFileClose() and a double-free:\n> >\n> > https://postgr.es/m/87y3hmee19.fsf@news-spur.riddles.org.uk\n> >\n> > That was a BufFile that was under the control of a tuplestore, so it\n> > was similar to but different from your case. I suspect it's related.\n> \n> Hmm. tuplestore.c follows the same coding pattern as nodeHashjoin.c:\n> it always nukes its pointer after calling BufFileFlush(), so it\n> shouldn't be capable of calling it twice for the same pointer, unless\n> we have two copies of that pointer somehow.\n> \n> Merlin's reported a double-free apparently in ExecHashJoin(), not\n> ExecHashJoinNewBatch() like this report. Unfortunately that tells us\n> very little.\n> \n> On Sun, Aug 25, 2019 at 2:25 PM Justin Pryzby <pryzby@telsasoft.com> wrote:\n> > #4 0x00000039ff678dd0 in _int_free (av=0x39ff98e120, p=0x1d40b090, have_lock=0) at malloc.c:4846\n> > #5 0x00000000006269e5 in ExecHashJoinNewBatch (pstate=0x2771218) at nodeHashjoin.c:1058\n> \n> Can you reproduce this or was it a one-off crash?\n\nThe query was of our large reports, and this job runs every 15min against\nrecently-loaded data; in the immediate case, between\n2019-08-24t08:00:00 and 2019-08-24 09:00:00\n\nI can rerun it fine, and I ran it in a loop for awhile last night with no\nissues.\n\ntime psql ts -f tmp/sql-2019-08-24.1 |wc\n 5416 779356 9793941\n\nSince it was asked in other thread Peter mentioned:\n\nts=# SHOW work_mem;\nwork_mem | 128MB\n\nts=# SHOW shared_buffers ;\nshared_buffers | 1536MB\n\n> might be some obscure path somewhere, possibly through a custom\n> operator or suchlike, that leaves us in a strange memory context, or\n> something like that? But then I feel like we'd have received\n> reproducible reports and a test case by now.\n\nNo custom operator in sight. Just NATURAL JOIN on integers, and WHERE on\ntimestamp, some plpgsql and int[].\n\nJustin\n\n\n", "msg_date": "Sun, 25 Aug 2019 20:44:14 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": true, "msg_subject": "Re: pg11.5: ExecHashJoinNewBatch: glibc detected...double free or\n corruption (!prev)" }, { "msg_contents": "On Mon, Aug 26, 2019 at 1:44 PM Justin Pryzby <pryzby@telsasoft.com> wrote:\n> On Mon, Aug 26, 2019 at 01:09:19PM +1200, Thomas Munro wrote:\n> > On Sun, Aug 25, 2019 at 3:15 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> > > I was reminded of this issue from last year, which also appeared to\n> > > involve BufFileClose() and a double-free:\n> > >\n> > > https://postgr.es/m/87y3hmee19.fsf@news-spur.riddles.org.uk\n> > >\n> > > That was a BufFile that was under the control of a tuplestore, so it\n> > > was similar to but different from your case. I suspect it's related.\n> >\n> > Hmm. tuplestore.c follows the same coding pattern as nodeHashjoin.c:\n> > it always nukes its pointer after calling BufFileFlush(), so it\n> > shouldn't be capable of calling it twice for the same pointer, unless\n> > we have two copies of that pointer somehow.\n> >\n> > Merlin's reported a double-free apparently in ExecHashJoin(), not\n> > ExecHashJoinNewBatch() like this report. Unfortunately that tells us\n> > very little.\n\nHere's another one:\n\nhttps://www.postgresql.org/message-id/flat/20170601081104.1500.56202%40wrigleys.postgresql.org\n\nHmm. Also on RHEL/CentOS 6, and also involving sorting, hashing,\nBufFileClose() but this time the glibc double free error is in\nrepalloc().\n\nAnd another one (repeatedly happening):\n\nhttps://www.postgresql.org/message-id/flat/3976998C-8D3B-4825-9B10-69ECB70A597A%40appnexus.com\n\nAlso on RHEL/CentOS 6, this time a sort in once case and a hash join\nin another case.\n\nOf course it's entirely possible that we have a bug here and I'm very\nkeen to find it, but I can't help noticing the common factor here is\nthat they're all running ancient RHEL 6.x releases, except Merlin who\ndidn't say. Merlin?\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Mon, 26 Aug 2019 14:34:31 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg11.5: ExecHashJoinNewBatch: glibc detected...double free or\n corruption (!prev)" }, { "msg_contents": "I'm not sure but maybe this is useful ?\n\n|(gdb) p VfdCache[2397]\n|$9 = {fd = -1, fdstate = 0, resowner = 0x24f93e0, nextFree = 2393, lruMoreRecently = 0, lruLessRecently = 2360, seekPos = 73016512, fileSize = 0, fileName = 0x0, fileFlags = 2, fileMode = 384}\n\nKnowing this report, very possibly this was a tempfile, possible a parallel fileset.\nI don't see parallel workers in the query plan, but I do have external sort:\n\n -> Sort (cost=20801.16..20801.60 rows=175 width=628) (actual time=39150.619..40730.793 rows=2002440 loops=1)\n Sort Key: data_cell.sect_id\n Sort Method: external sort Disk: 1613224kB\n -> Hash Join (cost=20649.46..20794.64 rows=175 width=628) (actual time=736.734..2423.020 rows=2002440 loops=1)\n Hash Cond: (eric_enodeb_cell_201908.start_time = data_cell.period)\n\nNote, we run report with enable_nestloop=off (say what you will). And the\nreport runs within an transaction which we roll back. I suspect that's maybe\nrelevant for cleaning up files.\n\nAh, it's more than 24h old but saved the logfile with crash marker, so I found:\n\nsudo zgrep 26188 /var/log/postgresql/crash-postgresql-2019-08-24_121600.log.gz\n< 2019-08-24 12:16:17.037 CDT telsasoft >LOG: temporary file: path \"base/pgsql_tmp/pgsql_tmp26188.5\", size 336726940\n< 2019-08-24 12:16:17.038 CDT telsasoft >LOG: temporary file: path \"base/pgsql_tmp/pgsql_tmp26188.54\", size 6354\n< 2019-08-24 12:16:20.081 CDT telsasoft >LOG: temporary file: path \"base/pgsql_tmp/pgsql_tmp26188.6\", size 270914376\n< 2019-08-24 12:16:20.083 CDT telsasoft >LOG: temporary file: path \"base/pgsql_tmp/pgsql_tmp26188.39\", size 7024\n< 2019-08-24 12:16:23.464 CDT telsasoft >LOG: temporary file: path \"base/pgsql_tmp/pgsql_tmp26188.7\", size 213332328\n< 2019-08-24 12:16:23.465 CDT telsasoft >LOG: temporary file: path \"base/pgsql_tmp/pgsql_tmp26188.37\", size 5984\n...\n< 2019-08-24 12:17:42.966 CDT telsasoft >LOG: temporary file: path \"base/pgsql_tmp/pgsql_tmp26188.125\", size 6534\n< 2019-08-24 12:17:43.035 CDT telsasoft >LOG: temporary file: path \"base/pgsql_tmp/pgsql_tmp26188.97\", size 72828152\n< 2019-08-24 12:17:43.036 CDT telsasoft >LOG: temporary file: path \"base/pgsql_tmp/pgsql_tmp26188.112\", size 6474\n< 2019-08-24 12:17:43.114 CDT telsasoft >LOG: temporary file: path \"base/pgsql_tmp/pgsql_tmp26188.90\", size 73016512\n< 2019-08-24 12:17:50.109 CDT >LOG: server process (PID 26188) was terminated by signal 6: Aborted\n\nsudo zgrep -cFw 'pgsql_tmp26188' /var/log/postgresql/crash-postgresql-2019-08-24_121600.log.gz \n=> 116\n\nsudo zgrep -Fw 'pgsql_tmp26188' /var/log/postgresql/crash-postgresql-2019-08-24_121600.log.gz |awk '{s+=$NF}END{print s/1024^3}'\n9.86781\n\nFWIW:\n\n log_temp_files | 0\n stats_temp_directory | pg_stat_tmp\n temp_file_limit | -1\n temp_tablespaces | \"\"\"\"\"\"\"\"\"\"\"\"\"\"\n\nApparently, the last is garbage from our upgrade script, but in any case it\nwent to PGDATA.\n\nJustin\n\n\n", "msg_date": "Sun, 25 Aug 2019 21:54:21 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": true, "msg_subject": "Re: pg11.5: ExecHashJoinNewBatch: glibc detected...double free or\n corruption (!prev)" }, { "msg_contents": "On Mon, Aug 26, 2019 at 02:34:31PM +1200, Thomas Munro wrote:\n>On Mon, Aug 26, 2019 at 1:44 PM Justin Pryzby <pryzby@telsasoft.com> wrote:\n>> On Mon, Aug 26, 2019 at 01:09:19PM +1200, Thomas Munro wrote:\n>> > On Sun, Aug 25, 2019 at 3:15 PM Peter Geoghegan <pg@bowt.ie> wrote:\n>> > > I was reminded of this issue from last year, which also appeared to\n>> > > involve BufFileClose() and a double-free:\n>> > >\n>> > > https://postgr.es/m/87y3hmee19.fsf@news-spur.riddles.org.uk\n>> > >\n>> > > That was a BufFile that was under the control of a tuplestore, so it\n>> > > was similar to but different from your case. I suspect it's related.\n>> >\n>> > Hmm. tuplestore.c follows the same coding pattern as nodeHashjoin.c:\n>> > it always nukes its pointer after calling BufFileFlush(), so it\n>> > shouldn't be capable of calling it twice for the same pointer, unless\n>> > we have two copies of that pointer somehow.\n>> >\n>> > Merlin's reported a double-free apparently in ExecHashJoin(), not\n>> > ExecHashJoinNewBatch() like this report. Unfortunately that tells us\n>> > very little.\n>\n>Here's another one:\n>\n>https://www.postgresql.org/message-id/flat/20170601081104.1500.56202%40wrigleys.postgresql.org\n>\n>Hmm. Also on RHEL/CentOS 6, and also involving sorting, hashing,\n>BufFileClose() but this time the glibc double free error is in\n>repalloc().\n>\n>And another one (repeatedly happening):\n>\n>https://www.postgresql.org/message-id/flat/3976998C-8D3B-4825-9B10-69ECB70A597A%40appnexus.com\n>\n>Also on RHEL/CentOS 6, this time a sort in once case and a hash join\n>in another case.\n>\n>Of course it's entirely possible that we have a bug here and I'm very\n>keen to find it, but I can't help noticing the common factor here is\n>that they're all running ancient RHEL 6.x releases, except Merlin who\n>didn't say. Merlin?\n>\n\nIt'd be interesting to know the exact glibc version for those machines.\n\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services \n\n\n", "msg_date": "Mon, 26 Aug 2019 10:57:01 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: pg11.5: ExecHashJoinNewBatch: glibc detected...double free or\n corruption (!prev)" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> Of course it's entirely possible that we have a bug here and I'm very\n> keen to find it, but I can't help noticing the common factor here is\n> that they're all running ancient RHEL 6.x releases, except Merlin who\n> didn't say. Merlin?\n\nHm, Justin said he had\nglibc-2.12-1.192.el6.x86_64\nwhich is a little bit behind the times but not *that* ancient.\n\nFor reference, attached is the rpm --changelog output on an up-to-date\nRHEL6 box for glibc running back to 2.12-1.192. Unfortunately a lot\nof the referenced bugzilla entries aren't public, but the one-liner\ndescriptions don't seem to suggest that they found any heap overruns\nthat would be interesting for us.\n\nHowever ... there is some pretty interesting info at\nhttps://bugzilla.redhat.com/show_bug.cgi?id=1338673\nsuggesting that compiling with a late-model gcc against older RHEL6\nheaders could result in bad code. I wonder whether the reporters'\nservers were built using such a configuration. (Although the linkage,\nif any, to this report still wouldn't be very clear.)\n\n\t\t\tregards, tom lane\n\n\n* Mon Apr 01 2019 Florian Weimer <fweimer@redhat.com> - 2.12-1.212.3\n- Remove abort() warning in manual (#1577437)\n\n* Mon Apr 01 2019 Florian Weimer <fweimer@redhat.com> - 2.12-1.212.2\n- ja_JP: Add new Japanese Era name (#1555930)\n\n* Mon Apr 01 2019 Florian Weimer <fweimer@redhat.com> - 2.12-1.212.1\n- regex: Fix false match in trailing characters (#1668169)\n\n* Fri Nov 17 2017 Patsy Franklin <pfrankli@redhat.com> - 2.12-1.212\n- CVE-2017-15670: glob: Fix one-byte overflow with GLOB_TILDE (#1504810)\n- CVE-2017-15804: glob: Fix buffer overflow in GLOB_TILDE unescaping (#1504810)\n\n* Mon Jun 19 2017 Florian Weimer <fweimer@redhat.com> - 2.12-1.211\n- Avoid large allocas in the dynamic linker (#1452717)\n\n* Wed Mar 29 2017 Carlos O'Donell <carlos@redhat.com> - 2.12-1.210\n- Fix thread cancellation issues for setmntent() and others (#1437147).\n\n* Wed Jan 25 2017 Florian Weimer <fweimer@redhat.com> - 2.12-1.209\n- Fix AF_INET6 getaddrinfo with nscd (#1416496)\n\n* Tue Oct 18 2016 Carlos O'Donell <carlos@redhat.com> - 2.12-1.208\n- Update tests for struct sockaddr_storage changes (#1338673)\n\n* Mon Oct 17 2016 Martin Sebor <msebor@redhat.com> - 2.12-1.207\n- Use FL_CLOEXEC in internal calls to fopen (#1012343).\n\n* Mon Oct 17 2016 Carlos O'Donell <carlos@redhat.com> - 2.12-1.206\n- Fix CVE-2015-8779 glibc: Unbounded stack allocation in catopen function\n (#1358015).\n\n* Mon Oct 17 2016 DJ Delorie <dj@redhat.com> - 2.12-1.205\n- Make padding in struct sockaddr_storage explicit (#1338673)\n\n* Thu Oct 13 2016 Carlos O'Donell <carlos@redhat.com> - 2.12-1.204\n- Fix detection of Intel FMA hardware (#1384281).\n\n* Tue Oct 11 2016 Carlos O'Donell <carlos@redhat.com> - 2.12-1.203\n- Add support for el_GR@euro, ur_IN, and wal_ET locales (#1101858).\n\n* Tue Oct 11 2016 Patsy Franklin <pfrankli@redhat.com> - 2.12-1.202\n- Change malloc/tst-malloc-thread-exit.c to use fewer threads and \n avoid timeout (#1318380).\n\n* Tue Oct 11 2016 Patsy Franklin <pfrankli@redhat.com> - 2.12-1.201\n- df can fail on some systems (#1307029).\n\n* Wed Sep 21 2016 DJ Delorie <dj@redhat.com> - 2.12-1.200\n- Log uname, cpuinfo, meminfo during build (#1307029).\n\n* Mon Sep 12 2016 DJ Delorie <dj@redhat.com> - 2.12-1.199\n- Draw graphs for heap and stack only if MAXSIZE_HEAP and MAXSIZE_STACK\n are non-zero (#1331304).\n\n* Mon Sep 12 2016 DJ Delorie <dj@redhat.com> - 2.12-1.198\n- Avoid unneeded calls to __check_pf in getadddrinfo (#1270950)\n\n* Mon Sep 12 2016 Martin Sebor <msebor@redhat.com> - 2.12-1.197\n- Fix CVE-2015-8778 glibc: Integer overflow in hcreate and hcreate_r\n (#1358013).\n\n* Mon Sep 12 2016 Martin Sebor <msebor@redhat.com> - 2.12-1.196\n- Fix CVE-2015-8776 glibc: Segmentation fault caused by passing\n out-of-range data to strftime() (#1358011).\n\n* Mon Sep 12 2016 Florian Weimer <fweimer@redhat.com> - 2.12-1.195\n- tzdata-update: Ignore umask setting (#1373646)\n\n* Thu Sep 08 2016 Florian Weimer <fweimer@redhat.com> - 2.12-1.194\n- CVE-2014-9761: Fix unbounded stack allocation in nan* (#1358014)\n\n* Thu Feb 04 2016 Florian Weimer <fweimer@redhat.com> - 2.12-1.193\n- Avoid using uninitialized data in getaddrinfo (#1223095)\n\n* Thu Jan 28 2016 Carlos O'Donell <carlos@redhat.com> - 2.12-1.192\n- Update fix for CVE-2015-7547 (#1296029).\n\n\n", "msg_date": "Mon, 26 Aug 2019 12:45:24 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg11.5: ExecHashJoinNewBatch: glibc detected...double free or\n corruption (!prev)" }, { "msg_contents": "On Mon, Aug 26, 2019 at 12:45:24PM -0400, Tom Lane wrote:\n> However ... there is some pretty interesting info at\n> https://bugzilla.redhat.com/show_bug.cgi?id=1338673\n> suggesting that compiling with a late-model gcc against older RHEL6\n> headers could result in bad code. I wonder whether the reporters'\n> servers were built using such a configuration. (Although the linkage,\n> if any, to this report still wouldn't be very clear.)\n\nThat's a question for Devrim ?\n\nCan you tell which glibc headers were installed when compiling this package?\npostgresql11-server-11.5-1PGDG.rhel6.x86_64\n\nI can tell it was compiled using\nversion | PostgreSQL 11.5 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-23), 64-bit\n\nMaybe it doesn't matter, since, for better or worse, is not a \"late model\" cc.\n\nhttps://www.gnu.org/software/gcc/gcc-4.4/\nGCC 4.4.7\n March 13, 2012 (changes) \nThis release series is no longer maintained.\n\nJustin\n\n\n", "msg_date": "Mon, 26 Aug 2019 11:58:12 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": true, "msg_subject": "Re: pg11.5: ExecHashJoinNewBatch: glibc detected...double free or\n corruption (!prev)" }, { "msg_contents": "Justin Pryzby <pryzby@telsasoft.com> writes:\n> On Mon, Aug 26, 2019 at 12:45:24PM -0400, Tom Lane wrote:\n>> However ... there is some pretty interesting info at\n>> https://bugzilla.redhat.com/show_bug.cgi?id=1338673\n>> suggesting that compiling with a late-model gcc against older RHEL6\n>> headers could result in bad code. I wonder whether the reporters'\n>> servers were built using such a configuration. (Although the linkage,\n>> if any, to this report still wouldn't be very clear.)\n\n> I can tell it was compiled using\n> version | PostgreSQL 11.5 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-23), 64-bit\n\nAh, that appears to be the default compiler for RHEL6, so that theory\nis out the window. It's still interesting that we're only seeing this\nreported from RHEL6 ... maybe there's something specific to the code\nthat this gcc version generates?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 26 Aug 2019 13:01:52 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg11.5: ExecHashJoinNewBatch: glibc detected...double free or\n corruption (!prev)" }, { "msg_contents": "On Sun, Aug 25, 2019 at 9:35 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n>\n> On Mon, Aug 26, 2019 at 1:44 PM Justin Pryzby <pryzby@telsasoft.com> wrote:\n> > On Mon, Aug 26, 2019 at 01:09:19PM +1200, Thomas Munro wrote:\n> > > On Sun, Aug 25, 2019 at 3:15 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> > > > I was reminded of this issue from last year, which also appeared to\n> > > > involve BufFileClose() and a double-free:\n> > > >\n> > > > https://postgr.es/m/87y3hmee19.fsf@news-spur.riddles.org.uk\n> > > >\n> > > > That was a BufFile that was under the control of a tuplestore, so it\n> > > > was similar to but different from your case. I suspect it's related.\n> > >\n> > > Hmm. tuplestore.c follows the same coding pattern as nodeHashjoin.c:\n> > > it always nukes its pointer after calling BufFileFlush(), so it\n> > > shouldn't be capable of calling it twice for the same pointer, unless\n> > > we have two copies of that pointer somehow.\n> > >\n> > > Merlin's reported a double-free apparently in ExecHashJoin(), not\n> > > ExecHashJoinNewBatch() like this report. Unfortunately that tells us\n> > > very little.\n>\n> Here's another one:\n>\n> https://www.postgresql.org/message-id/flat/20170601081104.1500.56202%40wrigleys.postgresql.org\n>\n> Hmm. Also on RHEL/CentOS 6, and also involving sorting, hashing,\n> BufFileClose() but this time the glibc double free error is in\n> repalloc().\n>\n> And another one (repeatedly happening):\n>\n> https://www.postgresql.org/message-id/flat/3976998C-8D3B-4825-9B10-69ECB70A597A%40appnexus.com\n>\n> Also on RHEL/CentOS 6, this time a sort in once case and a hash join\n> in another case.\n>\n> Of course it's entirely possible that we have a bug here and I'm very\n> keen to find it, but I can't help noticing the common factor here is\n> that they're all running ancient RHEL 6.x releases, except Merlin who\n> didn't say. Merlin?\n\nJust noticed this.\nredhat-release: \"Red Hat Enterprise Linux Server release 6.9 (Santiago)\"\n\nmerlin\n\n\n", "msg_date": "Tue, 27 Aug 2019 17:18:56 -0500", "msg_from": "Merlin Moncure <mmoncure@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg11.5: ExecHashJoinNewBatch: glibc detected...double free or\n corruption (!prev)" }, { "msg_contents": "On Mon, Aug 26, 2019 at 12:01 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Justin Pryzby <pryzby@telsasoft.com> writes:\n> > On Mon, Aug 26, 2019 at 12:45:24PM -0400, Tom Lane wrote:\n> >> However ... there is some pretty interesting info at\n> >> https://bugzilla.redhat.com/show_bug.cgi?id=1338673\n> >> suggesting that compiling with a late-model gcc against older RHEL6\n> >> headers could result in bad code. I wonder whether the reporters'\n> >> servers were built using such a configuration. (Although the linkage,\n> >> if any, to this report still wouldn't be very clear.)\n>\n> > I can tell it was compiled using\n> > version | PostgreSQL 11.5 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-23), 64-bit\n>\n> Ah, that appears to be the default compiler for RHEL6, so that theory\n> is out the window. It's still interesting that we're only seeing this\n> reported from RHEL6 ... maybe there's something specific to the code\n> that this gcc version generates?\n\nFWIW, I've got the same compiler (which is natural, we are likely\nusing the same packaging):\nPostgreSQL 9.6.12 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313\n(Red Hat 4.4.7-23), 64-bit\n\nmerlin\n\n\n", "msg_date": "Tue, 27 Aug 2019 17:52:49 -0500", "msg_from": "Merlin Moncure <mmoncure@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg11.5: ExecHashJoinNewBatch: glibc detected...double free or\n corruption (!prev)" }, { "msg_contents": "On Tue, Aug 27, 2019 at 5:52 PM Merlin Moncure <mmoncure@gmail.com> wrote:\n>\n> On Mon, Aug 26, 2019 at 12:01 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >\n> > Justin Pryzby <pryzby@telsasoft.com> writes:\n> > > On Mon, Aug 26, 2019 at 12:45:24PM -0400, Tom Lane wrote:\n> > >> However ... there is some pretty interesting info at\n> > >> https://bugzilla.redhat.com/show_bug.cgi?id=1338673\n> > >> suggesting that compiling with a late-model gcc against older RHEL6\n> > >> headers could result in bad code. I wonder whether the reporters'\n> > >> servers were built using such a configuration. (Although the linkage,\n> > >> if any, to this report still wouldn't be very clear.)\n> >\n> > > I can tell it was compiled using\n> > > version | PostgreSQL 11.5 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-23), 64-bit\n> >\n> > Ah, that appears to be the default compiler for RHEL6, so that theory\n> > is out the window. It's still interesting that we're only seeing this\n> > reported from RHEL6 ... maybe there's something specific to the code\n> > that this gcc version generates?\n>\n> FWIW, I've got the same compiler (which is natural, we are likely\n> using the same packaging):\n> PostgreSQL 9.6.12 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313\n> (Red Hat 4.4.7-23), 64-bit\n\nI'm looking for more common threads here. One interesting fact about\nthis server is that we just realized (!) that cron was attempting to\nemail huge log files and failing due to misconfigured email. The mail\nqueue was building into the gigabytes so that on half hour cadence the\nserver was running out of memory until the mail process crashed.\nPostgres ran just fine through this process (which is pretty cool).\nSo, question: were there any memory issues on the other server on or\naround the crash?\n\nmerlin\n\n\n", "msg_date": "Tue, 3 Sep 2019 10:49:13 -0500", "msg_from": "Merlin Moncure <mmoncure@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg11.5: ExecHashJoinNewBatch: glibc detected...double free or\n corruption (!prev)" } ]
[ { "msg_contents": "The following bug has been logged on the website:\n\nBug reference: 15977\nLogged by: mtlh kdvt\nEmail address: emuser20140816@gmail.com\nPostgreSQL version: 12beta3\nOperating system: Windows\nDescription: \n\nWhen a ROLLBACK AND CHAIN command is executed in the implicit transaction\nblock, a new transaction will be started:\r\n db=# ROLLBACK AND CHAIN;\r\n WARNING: there is no transaction in progress\r\n ROLLBACK\r\n db=# ROLLBACK AND CHAIN;\r\n ROLLBACK\r\n\r\nHowever, a COMMIT AND CHAIN command won't start a new transaction:\r\n db=# COMMIT AND CHAIN;\r\n WARNING: there is no transaction in progress\r\n COMMIT\r\n db=# COMMIT AND CHAIN;\r\n WARNING: there is no transaction in progress\r\n COMMIT", "msg_date": "Sun, 25 Aug 2019 06:11:05 +0000", "msg_from": "PG Bug reporting form <noreply@postgresql.org>", "msg_from_op": true, "msg_subject": "BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "> The following bug has been logged on the website:\n>\n> Bug reference: 15977\n> Logged by: mtlh kdvt\n> Email address: emuser20140816@gmail.com\n> PostgreSQL version: 12beta3\n> Operating system: Windows\n> Description:\n>\n> When a ROLLBACK AND CHAIN command is executed in the implicit transaction\n> block, a new transaction will be started:\n> db=# ROLLBACK AND CHAIN;\n> WARNING: there is no transaction in progress\n> ROLLBACK\n> db=# ROLLBACK AND CHAIN;\n> ROLLBACK\n>\n> However, a COMMIT AND CHAIN command won't start a new transaction:\n> db=# COMMIT AND CHAIN;\n> WARNING: there is no transaction in progress\n> COMMIT\n> db=# COMMIT AND CHAIN;\n> WARNING: there is no transaction in progress\n> COMMIT\n\nThanks for the report.\n\nIndeed, I confirm, and I should have caught this one while reviewing…\n\nDoc says:\n\n\"If AND CHAIN is specified, a new transaction is immediately started with \nthe same transaction characteristics as the just finished one. Otherwise, \nno new transaction is started.\"\n\nIf there is no transaction in progress, the spec is undefined. Logically, \nITSM that there should be no tx reset if none was in progress, so ROLLBACK \nhas the wrong behavior?\n\nA quick glance at the code did not yield any obvious culprit, but maybe \nI'm not looking at the right piece of code.\n\nDoc could happend \", if any\" to be clearer.\n\n-- \nFabien.", "msg_date": "Sun, 25 Aug 2019 11:11:09 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "COMMIT AND CHAIN in implicit block leaves blockState as TBLOCK_STARTED,\nwhich doesn't trigger the chaining.\nbut ROLLBACK AND CHAIN sets the blockState into TBLOCK_ABORT_PENDING, so\nthe chaining is triggered.\n\nI think disabling s->chain beforehand should do the desired behavior.\n\n2019年8月25日(日) 18:11 Fabien COELHO <coelho@cri.ensmp.fr>:\n\n>\n> > The following bug has been logged on the website:\n> >\n> > Bug reference: 15977\n> > Logged by: mtlh kdvt\n> > Email address: emuser20140816@gmail.com\n> > PostgreSQL version: 12beta3\n> > Operating system: Windows\n> > Description:\n> >\n> > When a ROLLBACK AND CHAIN command is executed in the implicit transaction\n> > block, a new transaction will be started:\n> > db=# ROLLBACK AND CHAIN;\n> > WARNING: there is no transaction in progress\n> > ROLLBACK\n> > db=# ROLLBACK AND CHAIN;\n> > ROLLBACK\n> >\n> > However, a COMMIT AND CHAIN command won't start a new transaction:\n> > db=# COMMIT AND CHAIN;\n> > WARNING: there is no transaction in progress\n> > COMMIT\n> > db=# COMMIT AND CHAIN;\n> > WARNING: there is no transaction in progress\n> > COMMIT\n>\n> Thanks for the report.\n>\n> Indeed, I confirm, and I should have caught this one while reviewing…\n>\n> Doc says:\n>\n> \"If AND CHAIN is specified, a new transaction is immediately started with\n> the same transaction characteristics as the just finished one. Otherwise,\n> no new transaction is started.\"\n>\n> If there is no transaction in progress, the spec is undefined. Logically,\n> ITSM that there should be no tx reset if none was in progress, so ROLLBACK\n> has the wrong behavior?\n>\n> A quick glance at the code did not yield any obvious culprit, but maybe\n> I'm not looking at the right piece of code.\n>\n> Doc could happend \", if any\" to be clearer.\n>\n> --\n> Fabien.", "msg_date": "Thu, 29 Aug 2019 04:29:26 +0900", "msg_from": "fn ln <emuser20140816@gmail.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "\nHello,\n\n> COMMIT AND CHAIN in implicit block leaves blockState as TBLOCK_STARTED, \n> which doesn't trigger the chaining. but ROLLBACK AND CHAIN sets the \n> blockState into TBLOCK_ABORT_PENDING, so the chaining is triggered.\n>\n> I think disabling s->chain beforehand should do the desired behavior.\n\nPatch applies with \"patch\", although \"git apply\" complained because of \nCRLF line terminations forced by the octet-stream mime type.\n\nPatch compiles cleanly. Make check ok.\n\nPatch works for me, and solution seems appropriate. It should be committed \nfor pg 12.0.\n\nThere could be a test added in \"regress/sql/transactions.sql\", I'd suggest \nsomething like:\n\n-- implicit transaction and not chained.\nCOMMIT AND CHAIN;\nCOMMIT;\nROLLBACK AND CHAIN;\nROLLBACK;\n\nwhich should show the appropriate \"no transaction in progress\" warnings.\n\nDoc could be made a little clearer about what to expect when there is no \nexplicit transaction in progress.\n\n-- \nFabien.\n\n\n", "msg_date": "Thu, 29 Aug 2019 08:30:07 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "Added two kinds of test for the implicit transaction: in single query and\nin implicit block.\nThe patch file is now created with Unix-style line ending (LF).\n\n2019年8月29日(木) 15:30 Fabien COELHO <coelho@cri.ensmp.fr>:\n\n>\n> Hello,\n>\n> > COMMIT AND CHAIN in implicit block leaves blockState as TBLOCK_STARTED,\n> > which doesn't trigger the chaining. but ROLLBACK AND CHAIN sets the\n> > blockState into TBLOCK_ABORT_PENDING, so the chaining is triggered.\n> >\n> > I think disabling s->chain beforehand should do the desired behavior.\n>\n> Patch applies with \"patch\", although \"git apply\" complained because of\n> CRLF line terminations forced by the octet-stream mime type.\n>\n> Patch compiles cleanly. Make check ok.\n>\n> Patch works for me, and solution seems appropriate. It should be committed\n> for pg 12.0.\n>\n> There could be a test added in \"regress/sql/transactions.sql\", I'd suggest\n> something like:\n>\n> -- implicit transaction and not chained.\n> COMMIT AND CHAIN;\n> COMMIT;\n> ROLLBACK AND CHAIN;\n> ROLLBACK;\n>\n> which should show the appropriate \"no transaction in progress\" warnings.\n>\n> Doc could be made a little clearer about what to expect when there is no\n> explicit transaction in progress.\n>\n> --\n> Fabien.\n>", "msg_date": "Thu, 29 Aug 2019 20:39:39 +0900", "msg_from": "fn ln <emuser20140816@gmail.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "\nHello,\n\n> Added two kinds of test for the implicit transaction: in single query and\n> in implicit block.\n\nOk.\n\n> The patch file is now created with Unix-style line ending (LF).\n\nThanks.\n\nPatch applies and compiles cleanly. However, \"make check\" is not ok\non the added tests.\n\n SHOW transaction_read_only;\n transaction_read_only\n -----------------------\n - on\n + off\n\nISTM that the run is right and the patch test output is wrong, i.e. the \ntransaction_read_only is expected to stay as is.\n\n-- \nFabien.\n\n\n", "msg_date": "Thu, 29 Aug 2019 14:10:06 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "transaction_read_only must be 'on' because AND CHAIN test sets the\ndefault_transaction_read_only to 'on'.\nFailure of this test means that the transaction was chained from an\nimplicit transaction, which is not our desired behavior.\nPerhaps you are using a wrong binary?\n\n2019年8月29日(木) 21:10 Fabien COELHO <coelho@cri.ensmp.fr>:\n\n>\n> Hello,\n>\n> > Added two kinds of test for the implicit transaction: in single query and\n> > in implicit block.\n>\n> Ok.\n>\n> > The patch file is now created with Unix-style line ending (LF).\n>\n> Thanks.\n>\n> Patch applies and compiles cleanly. However, \"make check\" is not ok\n> on the added tests.\n>\n> SHOW transaction_read_only;\n> transaction_read_only\n> -----------------------\n> - on\n> + off\n>\n> ISTM that the run is right and the patch test output is wrong, i.e. the\n> transaction_read_only is expected to stay as is.\n>\n> --\n> Fabien.\n>\n\n\ntransaction_read_only must be 'on' because AND CHAIN test sets the default_transaction_read_only to 'on'.Failure of this test means that the transaction was chained from an implicit transaction, which is not our desired behavior.Perhaps you are using a wrong binary?\n2019年8月29日(木) 21:10 Fabien COELHO <coelho@cri.ensmp.fr>:\nHello,\n\n> Added two kinds of test for the implicit transaction: in single query and\n> in implicit block.\n\nOk.\n\n> The patch file is now created with Unix-style line ending (LF).\n\nThanks.\n\nPatch applies and compiles cleanly. However, \"make check\" is not ok\non the added tests.\n\n    SHOW transaction_read_only;\n     transaction_read_only\n    -----------------------\n   - on\n   + off\n\nISTM that the run is right and the patch test output is wrong, i.e. the \ntransaction_read_only is expected to stay as is.\n\n-- \nFabien.", "msg_date": "Thu, 29 Aug 2019 21:35:43 +0900", "msg_from": "fn ln <emuser20140816@gmail.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "Hello,\n\n> transaction_read_only must be 'on' because AND CHAIN test sets the\n> default_transaction_read_only to 'on'.\n\n> Failure of this test means that the transaction was chained from an \n> implicit transaction, which is not our desired behavior. Perhaps you are \n> using a wrong binary?\n\nNope, I blindly assumed that your patch was self contained, but it is not, \nand my test did not include the initial fix.\n\nThe usual approach is to send self-contained and numbered patches,\neg \"chain-fix-1.patch\", \"chain-fix-2.patch\", and so on, unless there are \ncomplex patches designed to be committed in stages.\n\nFor the expected result, I was wrongly assuming that \"SET TRANSACTION\" was \nsession persistent, which is not the case, there is a \"SET SESSION …\" for \nthat. Moreover, the usual transaction default is read-write, so I was a \nlittle surprise. It would help to show the (unusual) current setting \nbefore the test.\n\nI also have registered the patch to the CF app:\n\n \thttps://commitfest.postgresql.org/24/2265/\n\nBut I cannot fill in your name, maybe you could register and add it, or it \ncan be left blank.\n\n-- \nFabien.", "msg_date": "Thu, 29 Aug 2019 15:01:11 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "> The usual approach is to send self-contained and numbered patches,\n> eg \"chain-fix-1.patch\", \"chain-fix-2.patch\", and so on, unless there are\n> complex patches designed to be committed in stages.\nThanks, I got it. I have never made a patch before so I'll keep it in my\nmind.\nSelf-contained patch is now attached.\n\n> it can be left blank\nI'm fine with that.", "msg_date": "Thu, 29 Aug 2019 22:55:47 +0900", "msg_from": "fn ln <emuser20140816@gmail.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "\n> Thanks, I got it. I have never made a patch before so I'll keep it in my \n> mind. Self-contained patch is now attached.\n\nv3 applies, compiles, \"make check\" ok.\n\nI turned it ready on the app.\n\n-- \nFabien\n\n\n", "msg_date": "Thu, 29 Aug 2019 16:58:18 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "On 2019-08-29 16:58, Fabien COELHO wrote:\n> \n>> Thanks, I got it. I have never made a patch before so I'll keep it in my \n>> mind. Self-contained patch is now attached.\n> \n> v3 applies, compiles, \"make check\" ok.\n> \n> I turned it ready on the app.\n\nShould we make it an error instead of a warning?\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 3 Sep 2019 11:54:57 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "\n>> v3 applies, compiles, \"make check\" ok.\n>>\n>> I turned it ready on the app.\n>\n> Should we make it an error instead of a warning?\n\nISTM that it made sense to have the same behavior as out of transaction \nCOMMIT or ROLLBACK.\n\n-- \nFabien.\n\n\n", "msg_date": "Tue, 3 Sep 2019 12:03:26 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "We have three options:\n 1. Prohibit AND CHAIN outside a transaction block, but do nothing in\nplain COMMIT/ROLLBACK or AND NO CHAIN.\n 2. Deal \"there is no transaction in progress\" (and \"there is already a\ntransaction in progress\" if needed) as an error.\n 3. Leave as it is.\n\nOption 1 makes overall behavior more inconsistent, and option 2 might cause\nthe backward-compatibility issues.\nSo I think 3 is a better solution for now.\n\n2019年9月3日(火) 18:55 Peter Eisentraut <peter.eisentraut@2ndquadrant.com>:\n\n> On 2019-08-29 16:58, Fabien COELHO wrote:\n> >\n> >> Thanks, I got it. I have never made a patch before so I'll keep it in\n> my\n> >> mind. Self-contained patch is now attached.\n> >\n> > v3 applies, compiles, \"make check\" ok.\n> >\n> > I turned it ready on the app.\n>\n> Should we make it an error instead of a warning?\n>\n> --\n> Peter Eisentraut http://www.2ndQuadrant.com/\n> PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n>\n\n\nWe have three options:  1. Prohibit AND CHAIN outside a transaction block, but do nothing in plain COMMIT/ROLLBACK or AND NO CHAIN.  2. Deal \"there is no transaction in progress\" (and \"there is already a transaction in progress\" if needed) as an error.  3. Leave as it is.Option 1 makes overall behavior more inconsistent, and option 2 might cause the backward-compatibility issues.So I think 3 is a better solution for now.\n2019年9月3日(火) 18:55 Peter Eisentraut <peter.eisentraut@2ndquadrant.com>:On 2019-08-29 16:58, Fabien COELHO wrote:\n> \n>> Thanks, I got it. I have never made a patch before so I'll keep it in my \n>> mind. Self-contained patch is now attached.\n> \n> v3 applies, compiles, \"make check\" ok.\n> \n> I turned it ready on the app.\n\nShould we make it an error instead of a warning?\n\n-- \nPeter Eisentraut              http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Tue, 3 Sep 2019 22:27:49 +0900", "msg_from": "fn ln <emuser20140816@gmail.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "Hi,\n\nOn 2019-09-03 11:54:57 +0200, Peter Eisentraut wrote:\n> On 2019-08-29 16:58, Fabien COELHO wrote:\n> > \n> >> Thanks, I got it. I have never made a patch before so I'll keep it in my \n> >> mind. Self-contained patch is now attached.\n> > \n> > v3 applies, compiles, \"make check\" ok.\n> > \n> > I turned it ready on the app.\n\nI don't think is quite sufficient. Note that the same problem also\nexists for commits, one just needs force the commit to be part of a\nmulti-statement implicit transaction (i.e. a simple protocol exec /\nPQexec(), with multiple statements).\n\nE.g.:\n\npostgres[32545][1]=# ROLLBACK;\nWARNING: 25P01: there is no transaction in progress\nLOCATION: UserAbortTransactionBlock, xact.c:3914\nROLLBACK\nTime: 0.790 ms\npostgres[32545][1]=# SELECT 1\\;COMMIT AND CHAIN;\nWARNING: 25P01: there is no transaction in progress\nLOCATION: EndTransactionBlock, xact.c:3728\nCOMMIT\nTime: 0.945 ms\npostgres[32545][1]*=# COMMIT ;\nCOMMIT\nTime: 0.539 ms\n\nthe \\; bit forces psql to not split command into two separate protocol\nlevel commands, but to submit them together.\n\n\n> Should we make it an error instead of a warning?\n\nYea, I think for AND CHAIN we have to either error, or always start a\nnew transaction. I can see arguments for both, as long as it's\nconsistent.\n\nThe historical behaviour of issuing only WARNINGS when issuing COMMIT or\nROLLBACK outside of an explicit transaction seems to weigh in favor of\nnot erroring. Given that the result of such a transaction command is not\nan error, the AND CHAIN portion should work.\n\nAdditionally, we actually have COMMIT; ROLLBACK; PREPARE TRANSACTION all\nwork meaningfully for implicit transactions. E.g.:\n\npostgres[32545][1]=# CREATE TABLE test()\\; PREPARE TRANSACTION 'frak';\nWARNING: 25P01: there is no transaction in progress\nLOCATION: EndTransactionBlock, xact.c:3728\nPREPARE TRANSACTION\nTime: 15.094 ms\npostgres[32545][1]=# \\d test\nDid not find any relation named \"test\".\npostgres[32545][1]=# COMMIT PREPARED 'frak';\nCOMMIT PREPARED\nTime: 4.727 ms\npostgres[32545][1]=# \\d test\n Table \"public.test\"\n┌────────┬──────┬───────────┬──────────┬─────────┐\n│ Column │ Type │ Collation │ Nullable │ Default │\n├────────┼──────┼───────────┼──────────┼─────────┤\n└────────┴──────┴───────────┴──────────┴─────────┘\n\n\nThe argument in the other direction is that not erroring out hides bugs,\nlike an accidentally already committed transaction (which is\nparticularly bad for ROLLBACK). We can't easily change that for plain\nCOMMIT/ROLLBACK due to backward compat concerns, but for COMMIT|ROLLBACK\nAND CHAIN there's no such such concern.\n\nI think there's an argument that we ought to behave differently for\nCOMMIT/ROLLBACK/PREPARE in implicit transactions where multiple commands\nexist, and ones where that's not the case. Given that they all actually\nhave an effect if there's a preceding statement in the implicit\ntransaction, the WARNING doesn't actually seem that appropriate?\n\nThere's some arguments that it's sometimes useful to be able to force\ncommitting an implicit transaction. Consider e.g. executing batch schema\nmodifications with some sensitivity to latency (and thus wanting to use\nreduce latency by executing multiple statements via one protocol\nmessage). There's a few cases where committing earlier is quite useful\nin that scenario, e.g.:\n\nCREATE TYPE test_enum AS ENUM ('a', 'b', 'c');\nCREATE TABLE uses_test_enum(v test_enum);\n\nwithout explicit commit:\n\npostgres[32545][1]=# ALTER TYPE test_enum ADD VALUE 'd'\\;INSERT INTO uses_test_enum VALUES('d');\nERROR: 55P04: unsafe use of new value \"d\" of enum type test_enum\nLINE 1: ...t_enum ADD VALUE 'd';INSERT INTO uses_test_enum VALUES('d');\n ^\nHINT: New enum values must be committed before they can be used.\nLOCATION: check_safe_enum_use, enum.c:98\n\n\nwith explicit commit:\n\npostgres[32545][1]=# ALTER TYPE test_enum ADD VALUE 'd'\\;COMMIT\\;INSERT INTO uses_test_enum VALUES('d');\nWARNING: 25P01: there is no transaction in progress\nLOCATION: EndTransactionBlock, xact.c:3728\nINSERT 0 1\n\nThere's also the case that one might want to batch execute statements,\nbut not have to redo them if a later command fails.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 4 Sep 2019 00:53:05 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "I made another patch for suggested behavior (COMMIT/ROLLBACK AND CHAIN now\ngives us an error when used in an implicit block).\n\n2019年9月4日(水) 16:53 Andres Freund <andres@anarazel.de>:\n\n> Hi,\n>\n> On 2019-09-03 11:54:57 +0200, Peter Eisentraut wrote:\n> > On 2019-08-29 16:58, Fabien COELHO wrote:\n> > >\n> > >> Thanks, I got it. I have never made a patch before so I'll keep it in\n> my\n> > >> mind. Self-contained patch is now attached.\n> > >\n> > > v3 applies, compiles, \"make check\" ok.\n> > >\n> > > I turned it ready on the app.\n>\n> I don't think is quite sufficient. Note that the same problem also\n> exists for commits, one just needs force the commit to be part of a\n> multi-statement implicit transaction (i.e. a simple protocol exec /\n> PQexec(), with multiple statements).\n>\n> E.g.:\n>\n> postgres[32545][1]=# ROLLBACK;\n> WARNING: 25P01: there is no transaction in progress\n> LOCATION: UserAbortTransactionBlock, xact.c:3914\n> ROLLBACK\n> Time: 0.790 ms\n> postgres[32545][1]=# SELECT 1\\;COMMIT AND CHAIN;\n> WARNING: 25P01: there is no transaction in progress\n> LOCATION: EndTransactionBlock, xact.c:3728\n> COMMIT\n> Time: 0.945 ms\n> postgres[32545][1]*=# COMMIT ;\n> COMMIT\n> Time: 0.539 ms\n>\n> the \\; bit forces psql to not split command into two separate protocol\n> level commands, but to submit them together.\n>\n>\n> > Should we make it an error instead of a warning?\n>\n> Yea, I think for AND CHAIN we have to either error, or always start a\n> new transaction. I can see arguments for both, as long as it's\n> consistent.\n>\n> The historical behaviour of issuing only WARNINGS when issuing COMMIT or\n> ROLLBACK outside of an explicit transaction seems to weigh in favor of\n> not erroring. Given that the result of such a transaction command is not\n> an error, the AND CHAIN portion should work.\n>\n> Additionally, we actually have COMMIT; ROLLBACK; PREPARE TRANSACTION all\n> work meaningfully for implicit transactions. E.g.:\n>\n> postgres[32545][1]=# CREATE TABLE test()\\; PREPARE TRANSACTION 'frak';\n> WARNING: 25P01: there is no transaction in progress\n> LOCATION: EndTransactionBlock, xact.c:3728\n> PREPARE TRANSACTION\n> Time: 15.094 ms\n> postgres[32545][1]=# \\d test\n> Did not find any relation named \"test\".\n> postgres[32545][1]=# COMMIT PREPARED 'frak';\n> COMMIT PREPARED\n> Time: 4.727 ms\n> postgres[32545][1]=# \\d test\n> Table \"public.test\"\n> ┌────────┬──────┬───────────┬──────────┬─────────┐\n> │ Column │ Type │ Collation │ Nullable │ Default │\n> ├────────┼──────┼───────────┼──────────┼─────────┤\n> └────────┴──────┴───────────┴──────────┴─────────┘\n>\n>\n> The argument in the other direction is that not erroring out hides bugs,\n> like an accidentally already committed transaction (which is\n> particularly bad for ROLLBACK). We can't easily change that for plain\n> COMMIT/ROLLBACK due to backward compat concerns, but for COMMIT|ROLLBACK\n> AND CHAIN there's no such such concern.\n>\n> I think there's an argument that we ought to behave differently for\n> COMMIT/ROLLBACK/PREPARE in implicit transactions where multiple commands\n> exist, and ones where that's not the case. Given that they all actually\n> have an effect if there's a preceding statement in the implicit\n> transaction, the WARNING doesn't actually seem that appropriate?\n>\n> There's some arguments that it's sometimes useful to be able to force\n> committing an implicit transaction. Consider e.g. executing batch schema\n> modifications with some sensitivity to latency (and thus wanting to use\n> reduce latency by executing multiple statements via one protocol\n> message). There's a few cases where committing earlier is quite useful\n> in that scenario, e.g.:\n>\n> CREATE TYPE test_enum AS ENUM ('a', 'b', 'c');\n> CREATE TABLE uses_test_enum(v test_enum);\n>\n> without explicit commit:\n>\n> postgres[32545][1]=# ALTER TYPE test_enum ADD VALUE 'd'\\;INSERT INTO\n> uses_test_enum VALUES('d');\n> ERROR: 55P04: unsafe use of new value \"d\" of enum type test_enum\n> LINE 1: ...t_enum ADD VALUE 'd';INSERT INTO uses_test_enum VALUES('d');\n> ^\n> HINT: New enum values must be committed before they can be used.\n> LOCATION: check_safe_enum_use, enum.c:98\n>\n>\n> with explicit commit:\n>\n> postgres[32545][1]=# ALTER TYPE test_enum ADD VALUE 'd'\\;COMMIT\\;INSERT\n> INTO uses_test_enum VALUES('d');\n> WARNING: 25P01: there is no transaction in progress\n> LOCATION: EndTransactionBlock, xact.c:3728\n> INSERT 0 1\n>\n> There's also the case that one might want to batch execute statements,\n> but not have to redo them if a later command fails.\n>\n> Greetings,\n>\n> Andres Freund\n>", "msg_date": "Wed, 4 Sep 2019 23:49:46 +0900", "msg_from": "fn ln <emuser20140816@gmail.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "On 2019-09-04 16:49, fn ln wrote:\n> I made another patch for suggested behavior (COMMIT/ROLLBACK AND CHAIN\n> now gives us an error when used in an implicit block).\n\nI'm content with this patch. Better disable questionable cases now and\nmaybe re-enable them later if someone wants to make a case for it.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 5 Sep 2019 14:16:11 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "Hi,\n\n\nOn 2019-09-05 14:16:11 +0200, Peter Eisentraut wrote:\n> On 2019-09-04 16:49, fn ln wrote:\n> > I made another patch for suggested behavior (COMMIT/ROLLBACK AND CHAIN\n> > now gives us an error when used in an implicit block).\n> \n> I'm content with this patch.\n\nWould need tests.\n\n\n> Better disable questionable cases now and maybe re-enable them later\n> if someone wants to make a case for it.\n\nI do think the fact that COMMIT in multi-statement implicit transaction\nhas some usecase, is an argument for just implementing it properly...\n\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 5 Sep 2019 14:11:35 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "On Thu, Sep 05, 2019 at 02:11:35PM -0700, Andres Freund wrote:\n> On 2019-09-05 14:16:11 +0200, Peter Eisentraut wrote:\n>> I'm content with this patch.\n> \n> Would need tests.\n\nThe latest patch sends adds coverage for all the new code paths\nadded. Do you have something else in mind?\n\n>> Better disable questionable cases now and maybe re-enable them later\n>> if someone wants to make a case for it.\n> \n> I do think the fact that COMMIT in multi-statement implicit transaction\n> has some usecase, is an argument for just implementing it properly...\n\nLike Peter, I would also keep an ERROR for now, as we could always\nrelax that later on.\n\nLooking at the latest patch, the comment blocks on top of TBLOCK_STARTED\nand TBLOCK_IMPLICIT_INPROGRESS in EndTransactionBlock() need an update\nto mention the difference of behavior with chained transactions. And\nthe same comment rework should be done in UserAbortTransactionBlock()\nfor TBLOCK_IMPLICIT_INPROGRESS/TBLOCK_STARTED?\n--\nMichael", "msg_date": "Fri, 6 Sep 2019 16:54:15 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "\nHello,\n\n>> I do think the fact that COMMIT in multi-statement implicit transaction\n>> has some usecase, is an argument for just implementing it properly...\n>\n> Like Peter, I would also keep an ERROR for now, as we could always\n> relax that later on.\n\nI can agree with both warning and error, but for me the choice should be \nconsistent with the current behavior of COMMIT and ROLLBACK in the same \ncontext.\n\n pg> CREATE OR REPLACE PROCEDURE warn(msg TEXT) LANGUAGE plpgsql AS\n $$ BEGIN RAISE WARNING 'warning: %', msg ; END ; $$;\n\nThen an out-of-transaction multi-statement commit:\n\n pg> CALL warn('1') \\; COMMIT \\; CALL warn('2') ;\n WARNING: warning: 1\n WARNING: there is no transaction in progress\n WARNING: warning: 2\n CALL\n\nBut v4 creates an non uniform behavior that I find surprising and \nunwelcome:\n\n pg> CALL warn('1') \\; COMMIT AND CHAIN \\; CALL warn('2') ;\n WARNING: warning: 1\n ERROR: COMMIT AND CHAIN can only be used in transaction blocks\n\nWhy \"commit\" & \"commit and chain\" should behave differently in the same \ncontext? For me they can error or warn, but consistency implies that they \nshould do the exact same thing.\n\n From a user perspective, I really want to know if a commit did not do what \nI thought, and I'm certainly NOT expecting the stuff I sent to go on as if \nnothing happened. Basically I agree with everybody that raising an error \nis the right behavior in this case, which suggest that out-of-transaction \ncommit and rollback should error.\n\nSo my opinion is that commit & rollback issued out-of-transaction should \nalso generate an error.\n\nIf it is too much a change and potential regression, then I think that the \n\"and chain\" variants should be consistent and just raise warnings.\n\n-- \nFabien.\n\n\n", "msg_date": "Sat, 7 Sep 2019 08:54:42 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "> Looking at the latest patch, the comment blocks on top of TBLOCK_STARTED\n> and TBLOCK_IMPLICIT_INPROGRESS in EndTransactionBlock() need an update\n> to mention the difference of behavior with chained transactions. And\n> the same comment rework should be done in UserAbortTransactionBlock()\n> for TBLOCK_IMPLICIT_INPROGRESS/TBLOCK_STARTED?\nI made another patch for that.\nI don't have much confidence with my English spelling so further\nimprovements may be needed.\n\n> If it is too much a change and potential regression, then I think that the\n> \"and chain\" variants should be consistent and just raise warnings.\nWe don't have an exact answer for implicit transaction chaining behavior\nyet.\nSo I think it's better to disable this feature until someone discovers the\nuse cases for this.\nPermitting AND CHAIN without a detailed specification might cause troubles\nin future.", "msg_date": "Sat, 7 Sep 2019 18:58:20 +0900", "msg_from": "fn ln <emuser20140816@gmail.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "Hi,\n\nOn 2019-09-06 16:54:15 +0900, Michael Paquier wrote:\n> On Thu, Sep 05, 2019 at 02:11:35PM -0700, Andres Freund wrote:\n> > On 2019-09-05 14:16:11 +0200, Peter Eisentraut wrote:\n> >> I'm content with this patch.\n> > \n> > Would need tests.\n> \n> The latest patch sends adds coverage for all the new code paths\n> added. Do you have something else in mind?\n\nMissed them somehow. But I don't think they're quite sufficient. I think\nat least we also need tests that test things like multi-statement\nexec_simple-query() *with* explicit transactions and chaining.\n\n\n> >> Better disable questionable cases now and maybe re-enable them later\n> >> if someone wants to make a case for it.\n> > \n> > I do think the fact that COMMIT in multi-statement implicit transaction\n> > has some usecase, is an argument for just implementing it properly...\n> \n> Like Peter, I would also keep an ERROR for now, as we could always\n> relax that later on.\n\nI mean, I agree it's better to err that way, but it still seems\nunnecessary to design things in a way that prevents legit cases, that we\nthen may have to allow later. Error -> no error is a behavioural change\ntoo, even if obviously less likely to cause problems.\n\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sat, 7 Sep 2019 03:16:51 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "\n> I made another patch for that.\n> I don't have much confidence with my English spelling so further\n> improvements may be needed.\n>\n>> If it is too much a change and potential regression, then I think that the\n>> \"and chain\" variants should be consistent and just raise warnings.\n\n> We don't have an exact answer for implicit transaction chaining behavior\n> yet.\n\n> So I think it's better to disable this feature until someone discovers the\n> use cases for this.\n\n> Permitting AND CHAIN without a detailed specification might cause troubles\n> in future.\n\nI think that it would be too bad to remove this feature for a small \nimplementation-dependent corner case.\n\nDocumentation says that COMMIT/ROLLBACK [AND CHAIN] apply to the \"current \ntransaction\", and \"BEGIN initiates a transaction block\".\n\nIf there is no BEGIN, there is no \"current transaction\", so basically the \nbehavior is unspecified, whether AND CHAIN or not, and we are free \nsomehow.\n\nIn such case, I'm simply arguing for consistency: whatever the behavior, \nthe chain and no chain variants should behave the same.\n\nNow, I'd prefer error in all cases, no doubt about that, which might be \nconsidered a regression. A way around that could be to have a GUC decide \nbetween a strict behavior (error) and the old behavior (warning).\n\n-- \nFabien.\n\n\n", "msg_date": "Sat, 7 Sep 2019 15:23:05 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "> Missed them somehow. But I don't think they're quite sufficient. I think\n> at least we also need tests that test things like multi-statement\n> exec_simple-query() *with* explicit transactions and chaining.\nAdded a few more tests for that.\n\n> Now, I'd prefer error in all cases, no doubt about that, which might be\n> considered a regression. A way around that could be to have a GUC decide\n> between a strict behavior (error) and the old behavior (warning).\nI think it's more better to have a GUC to disable implicit transaction\n'block' feature, because that's probably the root of all issues.\n\n2019年9月7日(土) 22:23 Fabien COELHO <coelho@cri.ensmp.fr>:\n\n>\n> > I made another patch for that.\n> > I don't have much confidence with my English spelling so further\n> > improvements may be needed.\n> >\n> >> If it is too much a change and potential regression, then I think that\n> the\n> >> \"and chain\" variants should be consistent and just raise warnings.\n>\n> > We don't have an exact answer for implicit transaction chaining behavior\n> > yet.\n>\n> > So I think it's better to disable this feature until someone discovers\n> the\n> > use cases for this.\n>\n> > Permitting AND CHAIN without a detailed specification might cause\n> troubles\n> > in future.\n>\n> I think that it would be too bad to remove this feature for a small\n> implementation-dependent corner case.\n>\n> Documentation says that COMMIT/ROLLBACK [AND CHAIN] apply to the \"current\n> transaction\", and \"BEGIN initiates a transaction block\".\n>\n> If there is no BEGIN, there is no \"current transaction\", so basically the\n> behavior is unspecified, whether AND CHAIN or not, and we are free\n> somehow.\n>\n> In such case, I'm simply arguing for consistency: whatever the behavior,\n> the chain and no chain variants should behave the same.\n>\n> Now, I'd prefer error in all cases, no doubt about that, which might be\n> considered a regression. A way around that could be to have a GUC decide\n> between a strict behavior (error) and the old behavior (warning).\n>\n> --\n> Fabien.\n>", "msg_date": "Sun, 8 Sep 2019 01:32:17 +0900", "msg_from": "fn ln <emuser20140816@gmail.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": ">> Now, I'd prefer error in all cases, no doubt about that, which might be\n>> considered a regression. A way around that could be to have a GUC decide\n>> between a strict behavior (error) and the old behavior (warning).\n>\n> I think it's more better to have a GUC to disable implicit transaction\n> 'block' feature, because that's probably the root of all issues.\n\nHmmm… I'm not sure that erroring out on \"SELECT 1\" because there is no \nexplicit \"BEGIN\" is sellable, even under some GUC.\n\n-- \nFabien.", "msg_date": "Sat, 7 Sep 2019 19:04:38 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "No, but instead always do an implicit COMMIT after each statement, like\nSELECT 1; SELECT 2; (not \\;) in psql.\nThe PostgreSQL document even states that 'Issuing COMMIT when not inside a\ntransaction does no harm, but it will provoke a warning message.' for a\nlong time,\nbut in fact it have side-effect when used in an implicit transactions.\nIf we can ensure that the COMMIT/ROLLBACK really does nothing, we don't\nhave to distinguish CHAIN and NO CHAIN errors anymore.\n\n2019年9月8日(日) 2:04 Fabien COELHO <coelho@cri.ensmp.fr>:\n\n>\n> >> Now, I'd prefer error in all cases, no doubt about that, which might be\n> >> considered a regression. A way around that could be to have a GUC decide\n> >> between a strict behavior (error) and the old behavior (warning).\n> >\n> > I think it's more better to have a GUC to disable implicit transaction\n> > 'block' feature, because that's probably the root of all issues.\n>\n> Hmmm… I'm not sure that erroring out on \"SELECT 1\" because there is no\n> explicit \"BEGIN\" is sellable, even under some GUC.\n>\n> --\n> Fabien.\n\nNo, but instead always do an implicit COMMIT after each statement, like SELECT 1; SELECT 2; (not \\;) in psql.The PostgreSQL document even states that 'Issuing COMMIT when not inside a transaction does no harm, but it will provoke a warning message.' for a long time,but in fact it have side-effect when used in an implicit transactions.If we can ensure that the COMMIT/ROLLBACK really does nothing, we don't have to distinguish CHAIN and NO CHAIN errors anymore.2019年9月8日(日) 2:04 Fabien COELHO <coelho@cri.ensmp.fr>:\n>> Now, I'd prefer error in all cases, no doubt about that, which might be\n>> considered a regression. A way around that could be to have a GUC decide\n>> between a strict behavior (error) and the old behavior (warning).\n>\n> I think it's more better to have a GUC to disable implicit transaction\n> 'block' feature, because that's probably the root of all issues.\n\nHmmm… I'm not sure that erroring out on \"SELECT 1\" because there is no \nexplicit \"BEGIN\" is sellable, even under some GUC.\n\n-- \nFabien.", "msg_date": "Sun, 8 Sep 2019 02:31:58 +0900", "msg_from": "fn ln <emuser20140816@gmail.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "On 2019-09-07 18:32, fn ln wrote:\n>> Missed them somehow. But I don't think they're quite sufficient. I think\n>> at least we also need tests that test things like multi-statement\n>> exec_simple-query() *with* explicit transactions and chaining.\n> Added a few more tests for that.\n\nI committed this patch with some cosmetic changes and documentation updates.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Sun, 8 Sep 2019 22:27:49 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "Confirmed. Thank you all for your help.\n\nThe only concern is that this test:\n\n SET TRANSACTION READ WRITE\\; COMMIT AND CHAIN; -- error\n SHOW transaction_read_only;\n\n SET TRANSACTION READ WRITE\\; ROLLBACK AND CHAIN; -- error\n SHOW transaction_read_only;\n\nmakes more sense with READ ONLY because default_transaction_read_only is\noff at this point.\n\n2019年9月9日(月) 5:27 Peter Eisentraut <peter.eisentraut@2ndquadrant.com>:\n\n> On 2019-09-07 18:32, fn ln wrote:\n> >> Missed them somehow. But I don't think they're quite sufficient. I think\n> >> at least we also need tests that test things like multi-statement\n> >> exec_simple-query() *with* explicit transactions and chaining.\n> > Added a few more tests for that.\n>\n> I committed this patch with some cosmetic changes and documentation\n> updates.\n>\n> --\n> Peter Eisentraut http://www.2ndQuadrant.com/\n> PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n>\n\nConfirmed. Thank you all for your help.The only concern is that this test:   SET TRANSACTION READ WRITE\\; COMMIT AND CHAIN;  -- error   SHOW transaction_read_only;   SET TRANSACTION READ WRITE\\; ROLLBACK AND CHAIN;  -- error   SHOW transaction_read_only;makes more sense with READ ONLY because \ndefault_transaction_read_only is off at this point.2019年9月9日(月) 5:27 Peter Eisentraut <peter.eisentraut@2ndquadrant.com>:On 2019-09-07 18:32, fn ln wrote:\n>> Missed them somehow. But I don't think they're quite sufficient. I think\n>> at least we also need tests that test things like multi-statement\n>> exec_simple-query() *with* explicit transactions and chaining.\n> Added a few more tests for that.\n\nI committed this patch with some cosmetic changes and documentation updates.\n\n-- \nPeter Eisentraut              http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Mon, 9 Sep 2019 12:58:46 +0900", "msg_from": "fn ln <emuser20140816@gmail.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "On 2019-09-09 05:58, fn ln wrote:\n> Confirmed. Thank you all for your help.\n> \n> The only concern is that this test:\n> \n>    SET TRANSACTION READ WRITE\\; COMMIT AND CHAIN;  -- error\n>    SHOW transaction_read_only;\n> \n>    SET TRANSACTION READ WRITE\\; ROLLBACK AND CHAIN;  -- error\n>    SHOW transaction_read_only;\n> \n> makes more sense with READ ONLY because default_transaction_read_only is\n> off at this point.\n\nOh you're right. Fixed.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 9 Sep 2019 10:42:56 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" }, { "msg_contents": "It looks good now. Thank you again.\n\n2019年9月9日(月) 17:43 Peter Eisentraut <peter.eisentraut@2ndquadrant.com>:\n\n> On 2019-09-09 05:58, fn ln wrote:\n> > Confirmed. Thank you all for your help.\n> >\n> > The only concern is that this test:\n> >\n> > SET TRANSACTION READ WRITE\\; COMMIT AND CHAIN; -- error\n> > SHOW transaction_read_only;\n> >\n> > SET TRANSACTION READ WRITE\\; ROLLBACK AND CHAIN; -- error\n> > SHOW transaction_read_only;\n> >\n> > makes more sense with READ ONLY because default_transaction_read_only is\n> > off at this point.\n>\n> Oh you're right. Fixed.\n>\n> --\n> Peter Eisentraut http://www.2ndQuadrant.com/\n> PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n>\n\nIt looks good now. Thank you again.2019年9月9日(月) 17:43 Peter Eisentraut <peter.eisentraut@2ndquadrant.com>:On 2019-09-09 05:58, fn ln wrote:\n> Confirmed. Thank you all for your help.\n> \n> The only concern is that this test:\n> \n>    SET TRANSACTION READ WRITE\\; COMMIT AND CHAIN;  -- error\n>    SHOW transaction_read_only;\n> \n>    SET TRANSACTION READ WRITE\\; ROLLBACK AND CHAIN;  -- error\n>    SHOW transaction_read_only;\n> \n> makes more sense with READ ONLY because default_transaction_read_only is\n> off at this point.\n\nOh you're right.  Fixed.\n\n-- \nPeter Eisentraut              http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Mon, 9 Sep 2019 18:32:09 +0900", "msg_from": "fn ln <emuser20140816@gmail.com>", "msg_from_op": false, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" } ]
[ { "msg_contents": "I propose the attached patch to make pg_upgrade error out on too many\ncommand-line arguments. This makes it match the behavior of other\nPostgreSQL programs.\n\nSee [0] for an issue related to the lack of this check:\n\n[0]:\nhttps://www.postgresql.org/message-id/871sdbzizp.fsf%40jsievers.enova.com\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Sun, 25 Aug 2019 10:51:47 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "On Sun, Aug 25, 2019 at 10:52 AM Peter Eisentraut\n<peter.eisentraut@2ndquadrant.com> wrote:\n>\n> I propose the attached patch to make pg_upgrade error out on too many\n> command-line arguments. This makes it match the behavior of other\n> PostgreSQL programs.\n>\n> See [0] for an issue related to the lack of this check:\n\n+1\n\n\n", "msg_date": "Sun, 25 Aug 2019 11:01:56 +0200", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> I propose the attached patch to make pg_upgrade error out on too many\n> command-line arguments. This makes it match the behavior of other\n> PostgreSQL programs.\n\n+1 ... are we missing this anywhere else?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 25 Aug 2019 10:29:59 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "On Sun, Aug 25, 2019 at 4:30 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> > I propose the attached patch to make pg_upgrade error out on too many\n> > command-line arguments. This makes it match the behavior of other\n> > PostgreSQL programs.\n>\n> +1 ... are we missing this anywhere else?\n\nI did some searching, and oid2name.c is also missing this.\n\n\n", "msg_date": "Sun, 25 Aug 2019 17:10:47 +0200", "msg_from": "Julien Rouhaud <rjuju123@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "On Sun, Aug 25, 2019 at 8:39 PM Julien Rouhaud <rjuju123@gmail.com> wrote:\n\n> On Sun, Aug 25, 2019 at 4:30 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >\n> > Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> > > I propose the attached patch to make pg_upgrade error out on too many\n> > > command-line arguments. This makes it match the behavior of other\n> > > PostgreSQL programs.\n> >\n> > +1 ... are we missing this anywhere else?\n>\n> I did some searching, and oid2name.c is also missing this.\n>\n> Yes, \"oid2name\" missing that check too.\n\n\n\n-- \nIbrar Ahmed", "msg_date": "Sun, 25 Aug 2019 23:50:44 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "On Sun, Aug 25, 2019 at 05:10:47PM +0200, Julien Rouhaud wrote:\n> I did some searching, and oid2name.c is also missing this.\n\nAnd pgbench, no?\n--\nMichael", "msg_date": "Mon, 26 Aug 2019 13:45:13 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "On Mon, Aug 26, 2019 at 9:46 AM Michael Paquier <michael@paquier.xyz> wrote:\n\n> On Sun, Aug 25, 2019 at 05:10:47PM +0200, Julien Rouhaud wrote:\n> > I did some searching, and oid2name.c is also missing this.\n>\n> And pgbench, no?\n>\n\nYes, the patch is slightly different.\n\n\n> --\n> Michael\n>\n\n\n-- \nIbrar Ahmed", "msg_date": "Mon, 26 Aug 2019 20:45:02 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "On 2019-08-26 17:45, Ibrar Ahmed wrote:\n> On Mon, Aug 26, 2019 at 9:46 AM Michael Paquier <michael@paquier.xyz\n> <mailto:michael@paquier.xyz>> wrote:\n> \n> On Sun, Aug 25, 2019 at 05:10:47PM +0200, Julien Rouhaud wrote:\n> > I did some searching, and oid2name.c is also missing this.\n> \n> And pgbench, no?\n> \n>  \n> Yes, the patch is slightly different.\n\nThanks, pushed all that together.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 29 Aug 2019 20:52:21 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "Hello Peter,\n\n>> On Sun, Aug 25, 2019 at 05:10:47PM +0200, Julien Rouhaud wrote:\n>> > I did some searching, and oid2name.c is also missing this.\n>>\n>> And pgbench, no?\n>>  \n>> Yes, the patch is slightly different.\n>\n> Thanks, pushed all that together.\n\nGreat!\n\nCould we maintain coverage by adding a TAP test? See 1 liner attached.\n\n-- \nFabien.", "msg_date": "Fri, 30 Aug 2019 08:44:28 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "On Fri, Aug 30, 2019 at 08:44:28AM +0200, Fabien COELHO wrote:\n> Could we maintain coverage by adding a TAP test? See 1 liner attached.\n\nI don't see why not. Perhaps this could be done for pgbench and\noid2name as well?\n--\nMichael", "msg_date": "Fri, 30 Aug 2019 15:59:05 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "Bonjour Michaël,\n\n> I don't see why not. Perhaps this could be done for pgbench and\n> oid2name as well?\n\nThis is for pgbench.\n\nI did not found a TAP test in pg_upgrade, I do not think that it is worth \ncreating one for that purpose. The \"test.sh\" script does not seem \nappropriate for this kind of coverage error test.\n\nThe TAP test for oid2name only includes basic checks, options and \narguments are not even tested, and there is no infra for actual testing, \neg starting a server… Improving that would be a much more significant \neffort that the one line I added to pgbench existing TAP test.\n\n-- \nFabien.", "msg_date": "Fri, 30 Aug 2019 09:14:07 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "Fabien COELHO <coelho@cri.ensmp.fr> writes:\n> Could we maintain coverage by adding a TAP test? See 1 liner attached.\n\nIs this issue *really* worth expending test cycles on forevermore?\n\nTest cycles are not free, and I see zero reason to think that a\ncheck of this sort would ever catch any bugs. Now, if you had a\nway to detect that somebody had forgotten the case in some new\nprogram, that would be interesting.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 30 Aug 2019 09:54:13 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "Hello Tom,\n\n>> Could we maintain coverage by adding a TAP test? See 1 liner attached.\n>\n> Is this issue *really* worth expending test cycles on forevermore?\n\nWith this argument consistently applied, postgres code coverage is \nconsistently weak, with 25% of the code never executed, and 15% of \nfunctions never called. \"psql\" is abysmal, \"libpq\" is really weak.\n\n> Test cycles are not free, and I see zero reason to think that a\n> check of this sort would ever catch any bugs. Now, if you had a\n> way to detect that somebody had forgotten the case in some new\n> program, that would be interesting.\n\nIt could get broken somehow, and the test would catch it?\n\nThat would be the only command which tests this feature?\n\nThis is a TAP test, not a test run on basic \"make check\". The cost is not \nmeasurable: pgbench 533 TAP tests run in 5 wallclock seconds, and this \nadded test does not change that much.\n\nNow, if you say you are against it, then it is rejected…\n\n-- \nFabien.", "msg_date": "Fri, 30 Aug 2019 16:40:11 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "Fabien COELHO <coelho@cri.ensmp.fr> writes:\n>> Is this issue *really* worth expending test cycles on forevermore?\n\n> With this argument consistently applied, postgres code coverage is \n> consistently weak, with 25% of the code never executed, and 15% of \n> functions never called. \"psql\" is abysmal, \"libpq\" is really weak.\n\nIt's all a question of balance. If you go too far in the other\ndirection, you end up with test suites that take an hour and a half\nto run so nobody ever runs them (case in point, mysql). I'm all for\nimproving coverage in meaningful ways --- but cases like this seem\nunlikely to be worth ongoing expenditures of testing effort.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Fri, 30 Aug 2019 10:47:48 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" }, { "msg_contents": "\n>>> Is this issue *really* worth expending test cycles on forevermore?\n>\n>> With this argument consistently applied, postgres code coverage is\n>> consistently weak, with 25% of the code never executed, and 15% of\n>> functions never called. \"psql\" is abysmal, \"libpq\" is really weak.\n>\n> It's all a question of balance. If you go too far in the other\n> direction, you end up with test suites that take an hour and a half\n> to run so nobody ever runs them (case in point, mysql). I'm all for\n> improving coverage in meaningful ways --- but cases like this seem\n> unlikely to be worth ongoing expenditures of testing effort.\n\nSure.\n\nI think there is room for several classes of tests, important ones always \nrun and others run say by the farm, and I thought that is what TAP tests \nwere for, given they are quite expensive anyway (eg most TAP test create \ntheir own postgres instance).\n\nSo for me the suggestion was appropriate for a pgbench-specific TAP test.\n\n-- \nFabien.\n\n\n", "msg_date": "Fri, 30 Aug 2019 16:55:05 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: pg_upgrade: Error out on too many command-line arguments" } ]
[ { "msg_contents": "When passing an argument option with a missing argument, strcmp would\nbe called with the argv terminating NULL.\n---\n src/bin/psql/startup.c | 5 +++--\n 1 file changed, 3 insertions(+), 2 deletions(-)\n\ndiff --git a/src/bin/psql/startup.c b/src/bin/psql/startup.c\nindex 4730c73396..cffbfc864e 100644\n--- a/src/bin/psql/startup.c\n+++ b/src/bin/psql/startup.c\n@@ -667,12 +667,13 @@ parse_psql_options(int argc, char *argv[], struct adhoc_opts *options)\n \t\t\t\tbreak;\n \t\t\tcase '?':\n \t\t\t\t/* Actual help option given */\n-\t\t\t\tif (strcmp(argv[optind - 1], \"-?\") == 0)\n+\t\t\t\tif (optind <= argc &&\n+\t\t\t\t strcmp(argv[optind - 1], \"-?\") == 0)\n \t\t\t\t{\n \t\t\t\t\tusage(NOPAGER);\n \t\t\t\t\texit(EXIT_SUCCESS);\n \t\t\t\t}\n-\t\t\t\t/* unknown option reported by getopt */\n+\t\t\t\t/* unknown option or missing argument */\n \t\t\t\telse\n \t\t\t\t\tgoto unknown_option;\n \t\t\t\tbreak;\n-- \n2.23.0\n\n\n\n", "msg_date": "Sun, 25 Aug 2019 12:06:17 +0200", "msg_from": "Quentin Rameau <quinq@fifth.space>", "msg_from_op": true, "msg_subject": "[PATCH] Fix missing argument handling in psql getopt" }, { "msg_contents": "Quentin Rameau <quinq@fifth.space> writes:\n> When passing an argument option with a missing argument, strcmp would\n> be called with the argv terminating NULL.\n\nUm ... so how would control get there with optind too large?\nWhat test case/platform are you considering?\n\n(There really shouldn't be *any* case where getopt advances\noptind past argc, imo.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 25 Aug 2019 11:02:32 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Fix missing argument handling in psql getopt" }, { "msg_contents": "Hello Tom,\n\n> > When passing an argument option with a missing argument, strcmp\n> > would be called with the argv terminating NULL. \n> \n> Um ... so how would control get there with optind too large?\n\nThat's from the getopt specification[0]:\n\n“If the option was the last character in the string pointed to by an\nelement of argv, then optarg shall contain the next element of argv,\nand optind shall be incremented by 2. If the resulting value of optind\nis greater than argc, this indicates a missing option-argument, and\ngetopt() shall return an error indication.”\n\nSo in the case of “psql -h“, optarg points to argv[2] and optind is set\nto 3 (optind is initialized to 1, then incremented by 2).\n\n> What test case/platform are you considering?\n\nTest case is just running psql -h.\nThe bug has been exposed by testing psql on musl.\n\n> (There really shouldn't be *any* case where getopt advances\n> optind past argc, imo.)\n\nActually that's the typical error case, as per the specification quoted\nabove.\n\n[0] https://pubs.opengroup.org/onlinepubs/9699919799/functions/getopt.html\n\n\n", "msg_date": "Sun, 25 Aug 2019 17:53:38 +0200", "msg_from": "Quentin Rameau <quinq@fifth.space>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Fix missing argument handling in psql getopt" }, { "msg_contents": "> > Um ... so how would control get there with optind too large?\n\nSorry, I missed the simple explanation for that:\n\nAs option 'h' is missing an argument, getopt(_long) returns the\ncharacter '?' which is switched on through variable c, and the program\njumps to the '?' case handling.\n\n\n", "msg_date": "Sun, 25 Aug 2019 18:01:25 +0200", "msg_from": "Quentin Rameau <quinq@fifth.space>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Fix missing argument handling in psql getopt" }, { "msg_contents": "Quentin Rameau <quinq@fifth.space> writes:\n>> Um ... so how would control get there with optind too large?\n\n> That's from the getopt specification[0]:\n\n> “If the option was the last character in the string pointed to by an\n> element of argv, then optarg shall contain the next element of argv,\n> and optind shall be incremented by 2. If the resulting value of optind\n> is greater than argc, this indicates a missing option-argument, and\n> getopt() shall return an error indication.”\n\nHm, interesting --- glibc doesn't seem to do that (advance optind past\nargc), nor do any of the principal BSDen. I see that this could be\nread as requiring it, but it seems like musl is pretty out of step\nby reading it that way.\n\nI actually don't care for that code very much and would prefer that\nwe nuke it entirely, because I think it's assuming more than it ought to\nabout the meaning of optind: in the case of multiple option letters in one\nargv element, it's unspecified exactly when optind advances. So the other\nproblem here is that sometimes it's looking at the argv element *before*\nthe relevant one. (It's easily demonstrated that this is so with glibc's\ngetopt().) Probably that doesn't ever result in wrong behavior in\npractice, but it still seems bogus.\n\nThe normal case of \"psql -?\" is handled before we ever get to this code,\nso if we just deleted '?' entirely from this logic, it would mostly do\nwhat we want. The case that would change is, eg,\n\n\tpsql -f foo -?\n\nwhere now you get a usage message but you'd just get an \"invalid option\"\ncomplaint without the special case. Seeing that none of our other\ncommand-line programs have this special case, I'm not sure why psql\nstill does.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 25 Aug 2019 12:57:48 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Fix missing argument handling in psql getopt" }, { "msg_contents": "> > “If the option was the last character in the string pointed to by an\n> > element of argv, then optarg shall contain the next element of argv,\n> > and optind shall be incremented by 2. If the resulting value of optind\n> > is greater than argc, this indicates a missing option-argument, and\n> > getopt() shall return an error indication.” \n> \n> Hm, interesting --- glibc doesn't seem to do that (advance optind past\n> argc), nor do any of the principal BSDen. I see that this could be\n> read as requiring it, but it seems like musl is pretty out of step\n> by reading it that way.\n\nYes they don't, but the specification looks pretty clear to me, there's\nnothing ambiguous about it.\nNow it's a matter of implementation willing to adhere or not to it.\n\n> I actually don't care for that code very much and would prefer that\n> we nuke it entirely, because I think it's assuming more than it ought to\n> about the meaning of optind: in the case of multiple option letters in one\n> argv element, it's unspecified exactly when optind advances.\n\nYes, optind shouldn't be used this way here.\nBut it's specified exactly how and when optind advances, following the\nabove code, which specifies the first use case of separated option and\nargument, there's a second case for grouped option and argument:\n\n“Otherwise, optarg shall point to the string following the option\ncharacter in that element of argv, and optind shall be incremented by 1.”\n\n> So the other\n> problem here is that sometimes it's looking at the argv element *before*\n> the relevant one. (It's easily demonstrated that this is so with glibc's\n> getopt().) Probably that doesn't ever result in wrong behavior in\n> practice, but it still seems bogus.\n> \n> The normal case of \"psql -?\" is handled before we ever get to this code,\n> so if we just deleted '?' entirely from this logic, it would mostly do\n> what we want. The case that would change is, eg,\n> \n> \tpsql -f foo -?\n> \n> where now you get a usage message but you'd just get an \"invalid option\"\n> complaint without the special case. Seeing that none of our other\n> command-line programs have this special case, I'm not sure why psql\n> still does.\n\nAnother better way, I think, to fix this is to check for optopt\ninstead, which would be set to the option which caused the error, which\nif empty means there isn't an error.\n\nPatch attached.", "msg_date": "Sun, 25 Aug 2019 21:00:09 +0200", "msg_from": "Quentin Rameau <quinq@fifth.space>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Fix missing argument handling in psql getopt" }, { "msg_contents": "> Another better way, I think, to fix this is to check for optopt\n> instead, which would be set to the option which caused the error, which\n> if empty means there isn't an error.\n> \n> Patch attached.\n\nActually OpenBSD seems to set optopt to '?' by default, so the updated\nattached patch ensure we start with an empty optopt.", "msg_date": "Sun, 25 Aug 2019 21:21:36 +0200", "msg_from": "Quentin Rameau <quinq@fifth.space>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Fix missing argument handling in psql getopt" }, { "msg_contents": "Quentin Rameau <quinq@fifth.space> writes:\n> Another better way, I think, to fix this is to check for optopt\n> instead, which would be set to the option which caused the error, which\n> if empty means there isn't an error.\n\nMeh. We don't use optopt at all today, and I don't especially want\nto start doing so. A patch that's trying to remove a platform\ndependency (which is what this is, pedantic arguments that musl can\nread POSIX better than anyone else notwithstanding) should not do\nso by introducing hazards of new platform dependencies.\n\nI've pushed your original patch (with some comment-tweaking).\nIt seems unlikely to break anything.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 25 Aug 2019 15:28:12 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Fix missing argument handling in psql getopt" }, { "msg_contents": "> I've pushed your original patch (with some comment-tweaking).\n> It seems unlikely to break anything.\n\nThanks!\n\n\n", "msg_date": "Sun, 25 Aug 2019 21:45:27 +0200", "msg_from": "Quentin Rameau <quinq@fifth.space>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Fix missing argument handling in psql getopt" } ]
[ { "msg_contents": "Is there a reason why the serial pseudotypes still behave as they did\npre-v10 and don't map to GENERATED BY DEFAULT AS IDENTITY these days?\n\n\nI'm hoping it's just an oversight and I can help \"fix\" it, but maybe\nthere is an actual reason for it to be this way?\n\n-- \n\nVik Fearing\n\n\n\n", "msg_date": "Sun, 25 Aug 2019 18:40:44 +0200", "msg_from": "Vik Fearing <vik.fearing@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "The serial pseudotypes" }, { "msg_contents": "Vik Fearing <vik.fearing@2ndquadrant.com> writes:\n> Is there a reason why the serial pseudotypes still behave as they did\n> pre-v10 and don't map to GENERATED BY DEFAULT AS IDENTITY these days?\n\nBackwards compatibility?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 25 Aug 2019 12:59:00 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: The serial pseudotypes" }, { "msg_contents": "On 25/08/2019 18:59, Tom Lane wrote:\n> Vik Fearing <vik.fearing@2ndquadrant.com> writes:\n>> Is there a reason why the serial pseudotypes still behave as they did\n>> pre-v10 and don't map to GENERATED BY DEFAULT AS IDENTITY these days?\n> Backwards compatibility?\n\n\nWith what?  We don't support downgrading and I wouldn't expect this\nchange to be backported.\n\n-- \n\nVik Fearing\n\n\n\n", "msg_date": "Sun, 25 Aug 2019 19:05:28 +0200", "msg_from": "Vik Fearing <vik.fearing@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: The serial pseudotypes" }, { "msg_contents": "Vik Fearing <vik.fearing@2ndquadrant.com> writes:\n> On 25/08/2019 18:59, Tom Lane wrote:\n>> Vik Fearing <vik.fearing@2ndquadrant.com> writes:\n>>> Is there a reason why the serial pseudotypes still behave as they did\n>>> pre-v10 and don't map to GENERATED BY DEFAULT AS IDENTITY these days?\n\n>> Backwards compatibility?\n\n> With what?\n\nApplications that expect declaring a serial column to result in the same\ncatalog side-effects as before. The default expressions look different,\nand the dependencies look different. For instance, an app that expected\natthasdef to tell it something about what happens when a column's value\nis omitted would be surprised. An app that thought it could alter the\ndefault expression for a column originally declared serial would be even\nmore surprised.\n\nAdmittedly, many of these things look a lot like the sort of system\ncatalog changes we make routinely and expect applications to cope.\nBut I don't think this would be a cost-free change. Serials have acted\nthe way they do for a pretty long time.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 25 Aug 2019 13:42:27 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: The serial pseudotypes" }, { "msg_contents": "On 25/08/2019 19:42, Tom Lane wrote:\n> Vik Fearing <vik.fearing@2ndquadrant.com> writes:\n>> On 25/08/2019 18:59, Tom Lane wrote:\n>>> Vik Fearing <vik.fearing@2ndquadrant.com> writes:\n>>>> Is there a reason why the serial pseudotypes still behave as they did\n>>>> pre-v10 and don't map to GENERATED BY DEFAULT AS IDENTITY these days?\n>>> Backwards compatibility?\n>> With what?\n> Applications that expect declaring a serial column to result in the same\n> catalog side-effects as before. The default expressions look different,\n> and the dependencies look different. For instance, an app that expected\n> atthasdef to tell it something about what happens when a column's value\n> is omitted would be surprised. An app that thought it could alter the\n> default expression for a column originally declared serial would be even\n> more surprised.\n>\n> Admittedly, many of these things look a lot like the sort of system\n> catalog changes we make routinely and expect applications to cope.\n\n\nIndeed.\n\n\n> But I don't think this would be a cost-free change. Serials have acted\n> the way they do for a pretty long time.\n\n\nI guess I'll keep telling people serials are obsolete then.\n\n-- \n\nVik Fearing\n\n\n\n", "msg_date": "Sun, 25 Aug 2019 20:33:39 +0200", "msg_from": "Vik Fearing <vik.fearing@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: The serial pseudotypes" }, { "msg_contents": "On Mon, 26 Aug 2019 at 01:42, Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Vik Fearing <vik.fearing@2ndquadrant.com> writes:\n> > On 25/08/2019 18:59, Tom Lane wrote:\n> >> Vik Fearing <vik.fearing@2ndquadrant.com> writes:\n> >>> Is there a reason why the serial pseudotypes still behave as they did\n> >>> pre-v10 and don't map to GENERATED BY DEFAULT AS IDENTITY these days?\n>\n> >> Backwards compatibility?\n>\n> > With what?\n>\n> Applications that expect declaring a serial column to result in the same\n> catalog side-effects as before. The default expressions look different,\n> and the dependencies look different. For instance, an app that expected\n> atthasdef to tell it something about what happens when a column's value\n> is omitted would be surprised. An app that thought it could alter the\n> default expression for a column originally declared serial would be even\n> more surprised.\n>\n\nRight. I'd be very leery of changing this w/o a lot of checking and/or a\nsome BC to help apps that expect traditional SERIALs to work.\n\nHibernate is a rather widely used example. Not a good example mind you, but\na very widely used one.\n\nIts PostgreSQL dialect directly calls nextval(...) and expects the value\nreturned to be the next value off the sequence based on the sequence's\nincrement counter. This is true of many other ORMs etc too. To reduce\nround-trips and to give them control of when they flush dirty objects from\ntheir internal writeback cache to the DB, they tend to preallocate object\nIDs from an internal pool they populate periodically from the database\nsequence generator. This design isn't even totally unreasonable given the\naccess patterns of these tools.\n\nHibernate also has an existing (IMO awful) defect of defaulting to a\nsequence increment value is 50 in its schema configuration/generation\ntools. It fails to check the increment on pre-existing schemas and blindly\nassumes 50 so if nextval returns 500 it will merrily return values\n(450..500] from its internal sequence value assignment pool. Much mess\nensues. So lets not pretend it is good, it's kind of horrible, but like\nActiveRecord and other monstrosities it's also a very widely used product\nwe need to care about. Unfortunately ;)\n\nThis reminds me though, I want to revisit my nextval(regclass, n_ids) patch\nI have lying around somewhere. Apps should be able to request non-default\nchunk allocations from nextval so we can avoid dealing with these\nunpleasant assumptions about increment size...\n\n... or worse, the apps that try to \"fix\" this by calling nextval then\nsetval to jump the sequence to the value they think it should have next.\nAnd yes, I've seen this. In production code.\n\n-- \n Craig Ringer http://www.2ndQuadrant.com/\n 2ndQuadrant - PostgreSQL Solutions for the Enterprise\n\nOn Mon, 26 Aug 2019 at 01:42, Tom Lane <tgl@sss.pgh.pa.us> wrote:Vik Fearing <vik.fearing@2ndquadrant.com> writes:\n> On 25/08/2019 18:59, Tom Lane wrote:\n>> Vik Fearing <vik.fearing@2ndquadrant.com> writes:\n>>> Is there a reason why the serial pseudotypes still behave as they did\n>>> pre-v10 and don't map to GENERATED BY DEFAULT AS IDENTITY these days?\n\n>> Backwards compatibility?\n\n> With what?\n\nApplications that expect declaring a serial column to result in the same\ncatalog side-effects as before.  The default expressions look different,\nand the dependencies look different.  For instance, an app that expected\natthasdef to tell it something about what happens when a column's value\nis omitted would be surprised.  An app that thought it could alter the\ndefault expression for a column originally declared serial would be even\nmore surprised.Right. I'd be very leery of changing this w/o a lot of checking and/or a some BC to help apps that expect traditional SERIALs to work.Hibernate is a rather widely used example. Not a good example mind you, but a very widely used one.Its PostgreSQL dialect directly calls nextval(...) and expects the value returned to be the next value off the sequence based on the sequence's increment counter. This is true of many other ORMs etc too. To reduce round-trips and to give them control of when they flush dirty objects from their internal writeback cache to the DB, they tend to preallocate object IDs from an internal pool they populate periodically from the database sequence generator. This design isn't even totally unreasonable given the access patterns of these tools.Hibernate also has an existing (IMO awful) defect of defaulting to a sequence increment value is 50 in its schema configuration/generation tools. It fails to check the increment on pre-existing schemas and blindly assumes 50 so if nextval returns 500 it will merrily return values (450..500] from its internal sequence value assignment pool. Much mess ensues. So lets not pretend it is good, it's kind of horrible, but like ActiveRecord and other monstrosities it's also a very widely used product we need to care about. Unfortunately ;)This reminds me though, I want to revisit my nextval(regclass, n_ids) patch I have lying around somewhere. Apps should be able to request non-default chunk allocations from nextval so we can avoid dealing with these unpleasant assumptions about increment size...... or worse, the apps that try to \"fix\" this by calling nextval then setval to jump the sequence to the value they think it should have next. And yes, I've seen this. In production code.--  Craig Ringer                   http://www.2ndQuadrant.com/ 2ndQuadrant - PostgreSQL Solutions for the Enterprise", "msg_date": "Mon, 26 Aug 2019 09:46:57 +0800", "msg_from": "Craig Ringer <craig@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: The serial pseudotypes" } ]
[ { "msg_contents": "I wrote a prototype quality patch that implements what I call\n\"classic\" suffix truncation. That is, the patch makes nbtree leaf page\nsplits generate a short prefix datum for the new high key for\nvariable-length datatypes, generated using new opclass infrastructure.\nThis is useful for string-like datatypes such as text, especially when\nwe happen to be indexing long text strings, where we don't truly need\nto use long strings in internal pages. The feature is \"classic\" in the\nsense that it works in more or less the way that Bayer and Unterauer\nanticipate in the \"Prefix B-Trees\" paper. We already have a limited\nform of suffix truncation that only works at the whole-column\ngranularity. To some degree, I approached writing this patch as\nfinishing off the work that was started in Postgres 12. It started out\nthat way, at least.\n\nI believe that the prototype is representative of the benefits that\nwe'd get from a high quality implementation of the same feature. Those\nbenefits turn out to be relatively small, which is discouraging. I'm\nnot going to pursue the project any further in the near-term, because\nthere is more important work to be done, but I thought that I'd share\nwhat I found here. Highlights:\n\n* There were changes required to nbtsplitloc.c to make it work well,\nunsurprisingly. It has to be sensitive to the final size of the new\nhigh key, rather than just caring about the number of columns that can\nbe truncated. At the same time, it's important to not break the\nduplicate handling stuff. I ended up changing the penalty logic for\nleaf splits, making it give primary consideration to the discrete cost\nthat is the total number of columns that are left in the new high key,\nand secondary consideration to the continuous cost that is the exact\nfinal size of the new high key with classic suffix truncation. This\nseemed to work well, though I didn't get as far as worrying about the\nextra cycles (I only implemented classic suffix truncation for \"C\"\nlocale text).\n\n* I saw a tiny reduction in the number of leaf pages with affected\nindexes in my test suite, and small reductions in the number of\ninternal pages.\n\n* There were 2 or 3 existing indexes from my test suite that happened\nto index very large strings, such as an index on a \"notes\" column.\nThese indexes had massive reductions in the number of internal pages\n(e.g. a 5x+ reduction), along with a very small reduction in the\nnumber of leaf pages. Users that happen to have a lot of indexes that\nlook like this are likely to find classic suffix truncation\ncompelling, but that doesn't seem like a good enough reason to push\nahead with the patch.\n\n--\nPeter Geoghegan\n\n\n", "msg_date": "Sun, 25 Aug 2019 11:37:38 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "\"Classic\" nbtree suffix truncation prototype" } ]
[ { "msg_contents": "This is a minor gripe in the grand scheme of things, but I'm a little\nannoyed that we accept standard SQL but then don't spit it back out.\n\n\nFor example:\n\n\n```\n\nEXPLAIN (COSTS OFF) SELECT * FROM pg_am WHERE amname LIKE '%t%';\n\n            QUERY PLAN            \n-----------------------------------\n Seq Scan on pg_am\n   Filter: (amname ~~ '%t%'::text)\n(2 rows)\n\n```\n\n\nWhy don't we convert that back to LIKE?  Sure, if someone actually typed\n\"~~\" instead of \"LIKE\" then that wouldn't match what they wrote, but I\nmuch prefer differing in that direction than the current one.\n\n\nI am not advocating we attempt anything more complex such as \"x ~>=~ 'y'\nAND x ~<~ 'z'\", just that we output SQL where feasible.  I would like to\nfiddle with this if there is consensus that a decent patch would be\naccepted.\n\n-- \n\nVik Fearing\n\n\n\n", "msg_date": "Sun, 25 Aug 2019 20:49:11 +0200", "msg_from": "Vik Fearing <vik.fearing@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Outputting Standard SQL" }, { "msg_contents": "Vik Fearing <vik.fearing@2ndquadrant.com> writes:\n> EXPLAIN (COSTS OFF) SELECT * FROM pg_am WHERE amname LIKE '%t%';\n>             QUERY PLAN            \n> -----------------------------------\n>  Seq Scan on pg_am\n>    Filter: (amname ~~ '%t%'::text)\n> (2 rows)\n\n> Why don't we convert that back to LIKE?\n\nTrying to do so would make our schema-qualification problems worse\nnot better. See\n\nhttps://www.postgresql.org/message-id/flat/ffefc172-a487-aa87-a0e7-472bf29735c8%40gmail.com\n\nparticularly\n\nhttps://www.postgresql.org/message-id/10492.1531515255@sss.pgh.pa.us\n\nWe really need to invent some weird nonstandard syntax for IS DISTINCT\nFROM and related cases, in order to not have broken dump/reload scenarios.\nI'd just as soon not do that for LIKE, when the operator syntax serves\nwell enough.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 25 Aug 2019 15:14:46 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Outputting Standard SQL" }, { "msg_contents": "On 25/08/2019 21:14, Tom Lane wrote:\n> Vik Fearing <vik.fearing@2ndquadrant.com> writes:\n>> EXPLAIN (COSTS OFF) SELECT * FROM pg_am WHERE amname LIKE '%t%';\n>>             QUERY PLAN            \n>> -----------------------------------\n>>  Seq Scan on pg_am\n>>    Filter: (amname ~~ '%t%'::text)\n>> (2 rows)\n>> Why don't we convert that back to LIKE?\n> Trying to do so would make our schema-qualification problems worse\n> not better. See\n>\n> https://www.postgresql.org/message-id/flat/ffefc172-a487-aa87-a0e7-472bf29735c8%40gmail.com\n>\n> particularly\n>\n> https://www.postgresql.org/message-id/10492.1531515255@sss.pgh.pa.us\n\n\nOh, okay, that makes sense.  Unfortunately.\n\n\n> We really need to invent some weird nonstandard syntax for IS DISTINCT\n> FROM and related cases, in order to not have broken dump/reload scenarios.\n> I'd just as soon not do that for LIKE, when the operator syntax serves\n> well enough.\n\n\nLIKE was just an example among many others.\n\n-- \n\nVik Fearing\n\n\n\n", "msg_date": "Mon, 26 Aug 2019 04:43:52 +0200", "msg_from": "Vik Fearing <vik.fearing@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: Outputting Standard SQL" } ]
[ { "msg_contents": "Anastasia's nbtree deduplication patch [1] has an open problem that I\nwould like to find a solution for: it currently assumes that there is\nno difference between binary equality and opclass equality. That won't\nwork for opclasses such as btree/numeric, because compressing equal\nnumeric datums could destroy display scale if equal numeric datums\nwere naively lumped together (actually, the deduplication patch\ndoesn't work like that, but it has other subtle problems due to not\nhaving worked out fundamental definitional issues).\n\nWe don't need to be able to assume that binary equality is exactly the\nsame thing as opclass equality at the level of individual tuples. We\nonly need to be able to assume that the user cannot observe any\ndifferences when they are shown output for two datums that are\nopclass-equal for any opclass that supports deduplication (i.e. cases\nlike the numeric_ops case just won't work, so we shouldn't event try).\nI believe that it would be okay if we treated two IndexTuples as\nequivalent and therefore targets to store together in the same posting\nlist when they happen to have distinct binary representations due to\nthe original datums having different TOAST input state. In short, the\ndeduplication patch cannot tolerate being unable to store\nopclass-equal IndexTuples in the same posting list when the opclass\n(or the underlying type being indexed) somehow allows that equality\nisn't equivalence -- that's simply unsupportable. The opclass gets one\nchance to say whether or not it vetoes the use of deduplication: at\nCREATE INDEX time.\n\nConsumers of this new infrastructure probably won't be limited to the\ndeduplication feature; the same infrastructure will be needed for a\nB-Tree prefix compression patch (I'm thinking of a configurable CREATE\nINDEX prefix compression feature). GIN never had to solve this problem\nbecause its indexes are always lossy, and cannot support index-only\nscans. It seems likely that a scheme like the one I have in mind can\nwork for the vast majority of Postgres B-Tree indexes in practice, so\nI don't think that the user-visible restrictions I'm considering will\nmake the patch significantly less useful (it's already very useful).\nThe most notable restriction for users will almost certainly be not\nsupporting deduplication within indexes that use nondeterministic\ncollations. They were already paying a performance penalty during\nhashing, though.\n\nI would like to:\n\n* Get some buy-in on whether or not the precise distinctions I would\nlike to make are correct for deduplication in particular, and as\nuseful as possible for other cases that we may need to add later on.\n\n* Figure out the exact interface through which opclass/opfamily\nauthors can represent that their notion of equality is compatible with\ndeduplication/compression. (I think that the use of nondeterministic\ncollations should disable deduplication without explicit action from\nthe operator class -- that should just be baked in.)\n\n* Mark most existing btree operator classes as being compatible with\ndeduplication as part of making the patch committable. As I said, I\nbelieve that their semantics are already compatible with what we need\nfor deduplication to work sensibly, aside from a handful of specific\nexceptions.\n\nIn any case, I'm certain that problems like the btree/numeric display\nscale problem are simply not worth solving directly. That would add a\nhuge amount of complexity for very little benefit.\n\n[1] https://commitfest.postgresql.org/24/2202/\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Sun, 25 Aug 2019 13:29:09 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Building infrastructure for B-Tree deduplication that recognizes when\n opclass equality is also equivalence" }, { "msg_contents": "Peter Geoghegan <pg@bowt.ie> writes:\n> We don't need to be able to assume that binary equality is exactly the\n> same thing as opclass equality at the level of individual tuples. We\n> only need to be able to assume that the user cannot observe any\n> differences when they are shown output for two datums that are\n> opclass-equal for any opclass that supports deduplication (i.e. cases\n> like the numeric_ops case just won't work, so we shouldn't event try).\n\nHmm, so that would exclude the optimization for numeric, float4/float8,\nand nondeterministic text collations. Anything else?\n\nI agree that teaching opclasses to say whether this is okay is a\nreasonable approach.\n\n> Consumers of this new infrastructure probably won't be limited to the\n> deduplication feature;\n\nIndeed, we run up against this sort of thing all the time in, eg, planner\noptimizations. I think some sort of \"equality is precise\" indicator\nwould be really useful for a lot of things.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 25 Aug 2019 16:56:13 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Sun, Aug 25, 2019 at 1:56 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> Hmm, so that would exclude the optimization for numeric, float4/float8,\n> and nondeterministic text collations. Anything else?\n\nAny pseudo-type whose output function could possibly be dependent on\nthe output function of another type (in case it happens to be one of\nthe types that definitely aren't safe). Maybe we could make fine\ndistinctions about pseudo-type safety in certain contexts, but that\ndoesn't matter to the deduplication patch.\n\n> I agree that teaching opclasses to say whether this is okay is a\n> reasonable approach.\n\nGreat.\n\n> > Consumers of this new infrastructure probably won't be limited to the\n> > deduplication feature;\n>\n> Indeed, we run up against this sort of thing all the time in, eg, planner\n> optimizations. I think some sort of \"equality is precise\" indicator\n> would be really useful for a lot of things.\n\nThe case that I happened to think of was \"collation strength\nreduction\". In other words, an optimization that has the planner use a\nmerge equijoin whose joinqual involves two text columns using the \"C\"\ncollation, even though the \"C\" collation isn't otherwise usable.\nPerhaps there are far more compelling planner optimization that I\nhaven't considered, though. This idea probably has problems with\ninteresting sort orders that aren't actually that interesting.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Sun, 25 Aug 2019 14:18:12 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Sun, Aug 25, 2019 at 2:18 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> > Indeed, we run up against this sort of thing all the time in, eg, planner\n> > optimizations. I think some sort of \"equality is precise\" indicator\n> > would be really useful for a lot of things.\n>\n> The case that I happened to think of was \"collation strength\n> reduction\".\n\nI was thinking of stashing an \"equality is precise\" flag in the\nmetapage of each nbtree index, since we will only determine this once,\nat CREATE INDEX time. That would make it fairly natural for the\nplanner to ask about the \"equality is precise\"-ness of the index at\nthe same point that it calls _bt_getrootheight(): within\nget_relation_info().\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Sun, 25 Aug 2019 14:29:36 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "Peter Geoghegan <pg@bowt.ie> writes:\n> I was thinking of stashing an \"equality is precise\" flag in the\n> metapage of each nbtree index, since we will only determine this once,\n> at CREATE INDEX time.\n\nSure.\n\n> That would make it fairly natural for the\n> planner to ask about the \"equality is precise\"-ness of the index at\n> the same point that it calls _bt_getrootheight(): within\n> get_relation_info().\n\nThe planner will almost certainly want to ask the opclass directly,\nbecause most of the places where it wants to know this sort of thing\nabout operator behavior have nothing to do with indexes.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 25 Aug 2019 17:40:04 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Sun, Aug 25, 2019 at 2:40 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > I was thinking of stashing an \"equality is precise\" flag in the\n> > metapage of each nbtree index, since we will only determine this once,\n> > at CREATE INDEX time.\n>\n> Sure.\n\nI suppose that we'd add something new to CREATE OPERATOR CLASS to make\nthis work? My instinct is to avoid adding things that are only\nmeaningful for a single AM to interfaces like CREATE OPERATOR CLASS,\nbut the system already has numerous dependencies on B-Tree opclasses\nthat seem comparable to me.\n\nThere is a single case where nbtree stores a type that differs from\nthe type actually being indexed by the operator class: the \"name\"\ncase, where the underlying storage type is actually cstring. I'm not\nsure whether or not this needs to be treated as its own kind of\nspecial case. I suppose that we can ignore it completely, because\nwe're not directly concerned with the physical representation used\nwithin an index. In fact, a major goal for this new infrastructure is\nthat nbtree gets to fully own the representation (it just needs to\nknow about the high level or logical requirements).\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Sun, 25 Aug 2019 14:55:08 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Sun, Aug 25, 2019 at 2:55 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> I suppose that we'd add something new to CREATE OPERATOR CLASS to make\n> this work? My instinct is to avoid adding things that are only\n> meaningful for a single AM to interfaces like CREATE OPERATOR CLASS,\n> but the system already has numerous dependencies on B-Tree opclasses\n> that seem comparable to me.\n\nAnother question is whether or not it would be okay to define\n\"equality is precise\"-ness to be \"the system's generic equality\nfunction works perfectly as a drop-in replacement for my own equality\noperator's function\". The system's generic equality function could be\nthe recently added datum_image_eq() function -- that looks like it\nwill do exactly what I have in mind. This would be a new way of using\ndatum_image_eq(), I think, since it wouldn't be okay for it to give an\nanswer that differed from the equality operator's function. It looks\nlike existing datum_image_eq() callers can deal with false negatives\n(but not false positives, which are impossible).\n\nThis exceeds what is strictly necessary for the deduplication patch,\nbut it seems like the patch should make comparisons as fast as\npossible in the context of deduplicating items (it would be nice if it\ncould just use datum_image_eq instead of an insertion scankey when\ndoing many comparisons to deduplicate items). We can imagine a\ndatatype with undefined garbage bytes that affect the answer that\ndatum_image_eq() gives, but could be safe targets for deduplication,\nso it's not clear if being this aggressive will work. But maybe that\nisn't actually possible among types that aren't inherently unsafe for\ndeduplication. And maybe we could be more aggressive with\noptimizations in numerous other contexts by defining \"equality is\nprecise\"-ness as strict binary equality after accounting for TOAST\ncompression.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Sun, 25 Aug 2019 16:19:10 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "Peter Geoghegan <pg@bowt.ie> wrote:\n\n> Consumers of this new infrastructure probably won't be limited to the\n> deduplication feature;\n\nIt'd also solve an open problem of the aggregate push-down patch [1], in\nparticular see the mention of pg_opclass in [2]: the partial aggregate\nnode below the final join must not put multiple opclass-equal values of\nwhich are not byte-wise equal into the same group because some\ninformation needed by WHERE or JOIN/ON condition may be lost this\nway. The scale of the numeric type is the most obvious example.\n\n> I would like to:\n> \n> * Get some buy-in on whether or not the precise distinctions I would\n> like to make are correct for deduplication in particular, and as\n> useful as possible for other cases that we may need to add later on.\n> \n> * Figure out the exact interface through which opclass/opfamily\n> authors can represent that their notion of equality is compatible with\n> deduplication/compression.\n\nIt's not entirely clear to me whether opclass or opfamily should carry\nthis information. opclass probably makes more sense for index related\nproblems and the aggregate push-down patch can live with that. I don't\nsee particular reason to add any flag to opfamily. (Planner uses uses\nboth pg_opclass and pg_opfamily catalogs.)\n\nI think the fact that the aggregate push-down would benefit from this\nenhancement should affect choice of the new catalog attribute name,\ni.e. it should be not mention words as concrete as \"deduplication\" or\n\"compression\".\n\n> (I think that the use of nondeterministic collations should disable\n> deduplication without explicit action from the operator class -- that\n> should just be baked in.)\n\n(I think the aggregate push-down needs to consider the nondeterministic\ncollations too, I missed that so far.)\n\n[1] https://commitfest.postgresql.org/24/1247/\n\n[2] https://www.postgresql.org/message-id/10529.1547561178%40localhost\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com\n\n\n", "msg_date": "Mon, 26 Aug 2019 13:15:40 +0200", "msg_from": "Antonin Houska <ah@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "26.08.2019 14:15, Antonin Houska wrote:\n> Peter Geoghegan <pg@bowt.ie> wrote:\n>\n>> Consumers of this new infrastructure probably won't be limited to the\n>> deduplication feature;\n> It'd also solve an open problem of the aggregate push-down patch [1], in\n> particular see the mention of pg_opclass in [2]: the partial aggregate\n> node below the final join must not put multiple opclass-equal values of\n> which are not byte-wise equal into the same group because some\n> information needed by WHERE or JOIN/ON condition may be lost this\n> way. The scale of the numeric type is the most obvious example.\n>\n>> I would like to:\n>>\n>> * Get some buy-in on whether or not the precise distinctions I would\n>> like to make are correct for deduplication in particular, and as\n>> useful as possible for other cases that we may need to add later on.\n>>\n>> * Figure out the exact interface through which opclass/opfamily\n>> authors can represent that their notion of equality is compatible with\n>> deduplication/compression.\n> It's not entirely clear to me whether opclass or opfamily should carry\n> this information. opclass probably makes more sense for index related\n> problems and the aggregate push-down patch can live with that. I don't\n> see particular reason to add any flag to opfamily. (Planner uses uses\n> both pg_opclass and pg_opfamily catalogs.)\n>\n> I think the fact that the aggregate push-down would benefit from this\n> enhancement should affect choice of the new catalog attribute name,\n> i.e. it should be not mention words as concrete as \"deduplication\" or\n> \"compression\".\n\n\nThe patch implementing new opclass option is attached.\n\nIt adds new attribute pg_opclass.opcisbitwise, which is set to true if \nopclass equality is the same as binary equality.\nBy default it is true. It is set to false for numeric and float4, float8.\n\nDoes anyarray opclasses need special treatment?\n\nNew syntax for create opclass is  \"CREATE OPERATOR CLASS NOT BITWISE ...\"\n\nAny ideas on better names?\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Mon, 30 Sep 2019 20:03:54 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru> wrote:\n\n> The patch implementing new opclass option is attached.\n> \n> It adds new attribute pg_opclass.opcisbitwise, which is set to true if opclass\n> equality is the same as binary equality.\n> By default it is true.\n\nI think the default value should be false and we should only set it to true\nfor individual opclasses which do meet the bitwise equality requirement. Also\nextension authors should explicitly state that their data types are bitwise\nequal. Otherwise the existing opclasses, when created via pg_dump ->\npg_restore, can be used by the system incorrectly.\n\n> It is set to false for numeric and float4, float8.\n\nAre you sure about these?\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com\n\n\n", "msg_date": "Tue, 01 Oct 2019 07:41:54 +0200", "msg_from": "Antonin Houska <ah@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": ">>>>> \"Antonin\" == Antonin Houska <ah@cybertec.at> writes:\n\n >> It is set to false for numeric and float4, float8.\n\n Antonin> Are you sure about these?\n\nnumeric values can compare equal but have different display scales (see\nhash_numeric).\n\nfloat4 and float8 both have representations for -0, which compares equal\nto 0. (numeric technically has a representation for -0 too, but I\nbelieve the current code carefully avoids ever generating it.)\n\n-- \nAndrew (irc:RhodiumToad)\n\n\n", "msg_date": "Tue, 01 Oct 2019 06:55:32 +0100", "msg_from": "Andrew Gierth <andrew@tao11.riddles.org.uk>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "01.10.2019 8:41, Antonin Houska wrote:\n> Anastasia Lubennikova <a.lubennikova@postgrespro.ru> wrote:\n>\n>> The patch implementing new opclass option is attached.\n>>\n>> It adds new attribute pg_opclass.opcisbitwise, which is set to true if opclass\n>> equality is the same as binary equality.\n>> By default it is true.\n> I think the default value should be false and we should only set it to true\n> for individual opclasses which do meet the bitwise equality requirement. Also\n> extension authors should explicitly state that their data types are bitwise\n> equal. Otherwise the existing opclasses, when created via pg_dump ->\n> pg_restore, can be used by the system incorrectly.\n\nThank you for the feedback.\n\nAt first I implemented bitwise as default, because it is more common .\nThough, I agree that it's essential to avoid false positives here.\nThe new version of the patch is attached. I also updated pg_dump.\n\nA few more open questions:\n1) How to handle contrib modules that create new opclasses?\nSince default is 'not bitwise' it means that various operator classes \ncreated in extensions\nsuch as bloom, btree_gin and others, won't be able to take advantage of \nvarious optimizations\nthat require the opclass to be BITWISE.\n\n'v2-Opclass-bitwise-equality-0002' patch simply adds BITWISE keyword \nwhere necessary.\n\n2) Whether we should provide ALTER OPERATOR CLASS SET BITWISE syntax?\n\n3) Current patch modifies regression test so that it checks CREATE \nOPCLASS BITWISE syntax.\nIs there anything else worth testing? As I see it, this patch is just \nabout infrastructure changes,\nand more specific tests will be added by features that will implement \nfurther optimizations.\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Mon, 28 Oct 2019 21:11:12 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Mon, Oct 28, 2019 at 11:11 AM Anastasia Lubennikova\n<a.lubennikova@postgrespro.ru> wrote:\n> At first I implemented bitwise as default, because it is more common .\n> Though, I agree that it's essential to avoid false positives here.\n> The new version of the patch is attached. I also updated pg_dump.\n>\n> A few more open questions:\n> 1) How to handle contrib modules that create new opclasses?\n> Since default is 'not bitwise' it means that various operator classes\n> created in extensions\n> such as bloom, btree_gin and others, won't be able to take advantage of\n> various optimizations\n> that require the opclass to be BITWISE.\n\nWhat optimizations? Do we anticipate that other index AMs will benefit\nfrom BITWISE-ness?\n\n> 'v2-Opclass-bitwise-equality-0002' patch simply adds BITWISE keyword\n> where necessary.\n>\n> 2) Whether we should provide ALTER OPERATOR CLASS SET BITWISE syntax?\n\nI think that that's probably not desirable. There should at least be a\nstrong practical advantage if we go that way. This would mean ALTER\nOPERATOR CLASS could change the \"substance\" of an opclass, which is\nfundamentally different from what it can do already (it currently just\nchanges the owner, or the schema that it is stored in).\n\n> 3) Current patch modifies regression test so that it checks CREATE\n> OPCLASS BITWISE syntax.\n> Is there anything else worth testing? As I see it, this patch is just\n> about infrastructure changes,\n> and more specific tests will be added by features that will implement\n> further optimizations.\n\nI think so too -- this is really about associating a single piece of\ninformation with an operator class.\n\nBTW: No need to bump catversion when posting a patch, which I see in\n\"v2-Opclass-*0001.patch\". That is our policy. (A catversion bump is\ngenerally supposed to be done at the last minute, just as the patch is\ncommitted. This avoids unnecessary conflicts against the master branch\nover time, as a patch is developed.)\n\n--\nPeter Geoghegan\n\n\n", "msg_date": "Wed, 13 Nov 2019 13:25:27 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "14.11.2019 0:25, Peter Geoghegan wrote:\n> On Mon, Oct 28, 2019 at 11:11 AM Anastasia Lubennikova\n> <a.lubennikova@postgrespro.ru> wrote:\n>> At first I implemented bitwise as default, because it is more common .\n>> Though, I agree that it's essential to avoid false positives here.\n>> The new version of the patch is attached. I also updated pg_dump.\n>>\n>> A few more open questions:\n>> 1) How to handle contrib modules that create new opclasses?\n>> Since default is 'not bitwise' it means that various operator classes\n>> created in extensions\n>> such as bloom, btree_gin and others, won't be able to take advantage of\n>> various optimizations\n>> that require the opclass to be BITWISE.\n> What optimizations? Do we anticipate that other index AMs will benefit\n> from BITWISE-ness?\nI was thinking of possible planner optimizations, that Tom mentioned up \nthread.\nThough, I don't have any specific examples. Anyway, we can implement \nsupport for user-defined opclasses later.\n>> 3) Current patch modifies regression test so that it checks CREATE\n>> OPCLASS BITWISE syntax.\n>> Is there anything else worth testing? As I see it, this patch is just\n>> about infrastructure changes,\n>> and more specific tests will be added by features that will implement\n>> further optimizations.\n> I think so too -- this is really about associating a single piece of\n> information with an operator class.\nGreat. It seems that the patch is ready for commit.\nI attached new version with pg_opclass documentation update.\n\nOne more thing I am uncertain about  is array_ops. Arrays may contain \nbitwise and not bitwise element types.\nWhat is the correct value of opcisbitwise the array_ops itself?\n\n-- \nAnastasia Lubennikova\nPostgres Professional:http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 15 Nov 2019 15:03:13 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru> wrote:\n\n> I attached new version with pg_opclass documentation update.\n> \n> One more thing I am uncertain about  is array_ops. Arrays may contain bitwise\n> and not bitwise element types.\n> What is the correct value of opcisbitwise the array_ops itself?\n\nHow about setting opcisbitwise to false for the array_ops opclass and checking\nopcisbitwise of the element type whenever we need to know whether the array is\n\"bitwise equal\"? When checking array_eq(), I thought whether the existence of\n\"expanded array\" format is a problem but it does not seem to be: the\nconversion of \"expanded\" value to \"flat\" value and then back to the \"expanded\"\nshould not change the array contents.\n\nAnyway, in the current version of the patch I see that array_ops opclasses\nhave opcisbitwise=true. It should be false even if you don't use the approach\nof checking the element type.\n\nBesides that, I think that record_ops is similar to array_ops and therefore it\nshould not set opcisbitwise to true.\n\nI also remember that, when thinking about the problem in the context of the\naggregate push down patch, I considered some of the geometric types\nproblematic. For example, box_eq() uses this expression\n\n#define FPeq(A,B)\t\t\t\t(fabs((A) - (B)) <= EPSILON)\n\nso equality does not imply bitwise equality here. Maybe you should only set\nthe flag for btree opclasses for now.\n\n-- \nAntonin Houska\nWeb: https://www.cybertec-postgresql.com\n\n\n", "msg_date": "Thu, 19 Dec 2019 16:19:24 +0100", "msg_from": "Antonin Houska <ah@cybertec.at>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Wed, Nov 13, 2019 at 4:25 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> I think that that's probably not desirable. There should at least be a\n> strong practical advantage if we go that way. This would mean ALTER\n> OPERATOR CLASS could change the \"substance\" of an opclass, which is\n> fundamentally different from what it can do already (it currently just\n> changes the owner, or the schema that it is stored in).\n\nMy impression is that this is more of an implementation restriction\nthan a design goal. I don't really remember the details, but it seems\nto me that there were locking and/or cache invalidation problems with\nmaking ALTER OPERATOR CLASS do more substantive things -- and that it\nwas because of those problems, not a lack of desire, that we didn't\nsupport it.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 19 Dec 2019 15:05:45 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Thu, Dec 19, 2019 at 12:05 PM Robert Haas <robertmhaas@gmail.com> wrote:\n> My impression is that this is more of an implementation restriction\n> than a design goal. I don't really remember the details, but it seems\n> to me that there were locking and/or cache invalidation problems with\n> making ALTER OPERATOR CLASS do more substantive things -- and that it\n> was because of those problems, not a lack of desire, that we didn't\n> support it.\n\nI agree with you. My point was only that this is something that the\noperator class author is really expected to get right the first time\naround -- just like the behavior of B-Tree support function 1. We're\nreally only concerned about the upgrade path for external types that\ncould see a benefit from the optimization planned for nbtree (and\npossibly other such optimization). Providing a non-disruptive way to\nget that benefit after a pg_upgrade only seems like a nice-to-have to\nme, because it's not as if anything will stop working as well as it\nonce did. Also, there aren't that many external types that will be\nmade more useful by being able to use optimizations like\ndeduplication; in practice almost all B-Tree indexes only use a small\nhandful of operator classes that are shipped in core Postgres. Once\nyou're using common types like text and integer, a pg_upgrade'd\ndatabase is only a REINDEX away from being able to use deduplication\n(though I am not even sure if even that will be necessary in the final\npatch; I hope to be able to avoid even that inconvenience with indexes\nusing core operator classes).\n\nIf the underlying behavior of an operator class actually changes, then\nthat's a disaster for all the usual reasons. It doesn't make that much\nsense to reverse an earlier decision to make an operator class\nBITWISE. Better to drop everything, and recreate everything, since\nyour indexes should be considered corrupt anyway. (Also, I don't think\nthat it's that hard to get it right, so this will probably never\nhappen.)\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Thu, 19 Dec 2019 16:12:22 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "19.12.2019 18:19, Antonin Houska wrote:\n> Anastasia Lubennikova <a.lubennikova@postgrespro.ru> wrote:\n>\n>> I attached new version with pg_opclass documentation update.\n>>\n>> One more thing I am uncertain about  is array_ops. Arrays may contain bitwise\n>> and not bitwise element types.\n>> What is the correct value of opcisbitwise the array_ops itself?\n> How about setting opcisbitwise to false for the array_ops opclass and checking\n> opcisbitwise of the element type whenever we need to know whether the array is\n> \"bitwise equal\"? When checking array_eq(), I thought whether the existence of\n> \"expanded array\" format is a problem but it does not seem to be: the\n> conversion of \"expanded\" value to \"flat\" value and then back to the \"expanded\"\n> should not change the array contents.\n>\n> Anyway, in the current version of the patch I see that array_ops opclasses\n> have opcisbitwise=true. It should be false even if you don't use the approach\n> of checking the element type.\n>\n> Besides that, I think that record_ops is similar to array_ops and therefore it\n> should not set opcisbitwise to true.\n>\n> I also remember that, when thinking about the problem in the context of the\n> aggregate push down patch, I considered some of the geometric types\n> problematic. For example, box_eq() uses this expression\n>\n> #define FPeq(A,B)\t\t\t\t(fabs((A) - (B)) <= EPSILON)\n>\n> so equality does not imply bitwise equality here. Maybe you should only set\n> the flag for btree opclasses for now.\n\nThank you for pointing out at the issue with geometric opclasses.\nIf I understand it correctly, regular float types are not bitwise as well.\n\nI updated the patchset.\nThe first patch now contains only infrastructure changes\nand the second one sets opcisbitwise for btree opclasses in pg_opclass.dat.\n\nI've tried to be conservative and only mark types that are 100% bitwise \nsafe.\nSee attached v2-Opclass-isbitwise.out file.\n\nNon-atomic types, such as record, range, json and enum depend on element \ntypes.\nText can be considered bitwise (i.e. texteq uses memcmp) only when \nspecific collation clauses are satisfied.\n\nWe can make this 'opcisbitwise' parameter enum (or char) instead of \nboolean to mark\n\"always bitwise\", \"never bitwise\" and \"maybe bitwise\". Though, I doubt \nif it will be helpful in any real use case.\n\nWhat do you think?\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Tue, 24 Dec 2019 15:29:23 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "\n> @@ -106,6 +106,18 @@ CREATE OPERATOR CLASS <replaceable class=\"parameter\">name</replaceable> [ DEFAUL\n> </listitem>\n> </varlistentry>\n> \n> + <varlistentry>\n> + <term><literal>NOT BITWISE</literal></term>\n> + <listitem>\n> + <para>\n> + If present, the operator class equality is not the same as equivalence.\n> + For example, two numerics can compare equal but have different scales.\n> + Most opclasses implement bitwise equal comparison, alternative behaviour\n> + must be set explicitly.\n> + </para>\n> + </listitem>\n> + </varlistentry>\n\nAm I the only one bothered by the fact that this patch (and all\ndownstream discussion) reduces the term \"bitwise equality\" to simply\n\"bitwise\"? It reads really strange to me, both in the resulting SQL\ngrammar as well as in struct names, code comments etc. \"This operator\nclass is bitwise.\"\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 24 Dec 2019 13:08:29 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "Alvaro Herrera <alvherre@2ndquadrant.com> writes:\n> Am I the only one bothered by the fact that this patch (and all\n> downstream discussion) reduces the term \"bitwise equality\" to simply\n> \"bitwise\"? It reads really strange to me, both in the resulting SQL\n> grammar as well as in struct names, code comments etc. \"This operator\n> class is bitwise.\"\n\nI agree, that's really poor English.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 24 Dec 2019 12:35:38 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "24.12.2019 19:08, Alvaro Herrera wrote:\n>> @@ -106,6 +106,18 @@ CREATE OPERATOR CLASS <replaceable class=\"parameter\">name</replaceable> [ DEFAUL\n>> </listitem>\n>> </varlistentry>\n>> \n>> + <varlistentry>\n>> + <term><literal>NOT BITWISE</literal></term>\n>> + <listitem>\n>> + <para>\n>> + If present, the operator class equality is not the same as equivalence.\n>> + For example, two numerics can compare equal but have different scales.\n>> + Most opclasses implement bitwise equal comparison, alternative behaviour\n>> + must be set explicitly.\n>> + </para>\n>> + </listitem>\n>> + </varlistentry>\n> Am I the only one bothered by the fact that this patch (and all\n> downstream discussion) reduces the term \"bitwise equality\" to simply\n> \"bitwise\"? It reads really strange to me, both in the resulting SQL\n> grammar as well as in struct names, code comments etc. \"This operator\n> class is bitwise.\"\n>\nThank you for pointing that out.\nDo you have any suggestions on how to name it better?\nShould it rather be \"CREATE OPERATOR CLASS ... BITWISE EQUAL\" ?\n\nIn the recent version of the patch I also had a question,\nif it will be useful to do this option enum instead of boolean:\n\n> We can make this 'opcisbitwise' parameter enum (or char) instead of \n> boolean to mark\n> \"always bitwise\", \"never bitwise\" and \"maybe bitwise\". \n\nThis decision will also affect the syntax. So I'd rather agree on that \nbefore updating syntax.\nDo you have an opinion on that?\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Thu, 26 Dec 2019 16:26:34 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Tue, Dec 24, 2019 at 7:29 AM Anastasia Lubennikova\n<a.lubennikova@postgrespro.ru> wrote:\n> We can make this 'opcisbitwise' parameter enum (or char) instead of\n> boolean to mark\n> \"always bitwise\", \"never bitwise\" and \"maybe bitwise\". Though, I doubt\n> if it will be helpful in any real use case.\n\nWhat would be the difference between \"never bitwise\" and \"maybe\nbitwise\" in that scheme?\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Sat, 28 Dec 2019 18:56:41 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "29.12.2019 2:56, Robert Haas wrote:\n> On Tue, Dec 24, 2019 at 7:29 AM Anastasia Lubennikova\n> <a.lubennikova@postgrespro.ru> wrote:\n>> We can make this 'opcisbitwise' parameter enum (or char) instead of\n>> boolean to mark\n>> \"always bitwise\", \"never bitwise\" and \"maybe bitwise\". Though, I doubt\n>> if it will be helpful in any real use case.\n> What would be the difference between \"never bitwise\" and \"maybe\n> bitwise\" in that scheme?\n\nIn this design \"maybe\" category reflects the need for an extra recheck.\n\nFor example, float and numeric types are \"never bitwise equal\", while array,\ntext, and other container types are \"maybe bitwise equal\". An array of \nintegers\nor text with C collation can be treated as bitwise equal attributes, and it\nwould be too harsh to restrict them from deduplication.\n\nWhat bothers me is that this option will unlikely be helpful on its own \nand we\nshould also provide some kind of recheck function along with opclass, which\ncomplicates this idea even further and doesn't seem very clear.\n\n-- \nAnastasia Lubennikova\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n\n", "msg_date": "Mon, 30 Dec 2019 18:57:06 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Mon, Dec 30, 2019 at 10:57 AM Anastasia Lubennikova\n<a.lubennikova@postgrespro.ru> wrote:\n> In this design \"maybe\" category reflects the need for an extra recheck.\n>\n> For example, float and numeric types are \"never bitwise equal\", while array,\n> text, and other container types are \"maybe bitwise equal\". An array of\n> integers\n> or text with C collation can be treated as bitwise equal attributes, and it\n> would be too harsh to restrict them from deduplication.\n>\n> What bothers me is that this option will unlikely be helpful on its own\n> and we\n> should also provide some kind of recheck function along with opclass, which\n> complicates this idea even further and doesn't seem very clear.\n\nIt seems like the simplest thing might be to forget about the 'char'\ncolumn and just have a support function which can be used to assess\nwhether a given opclass's notion of equality is bitwise. If equality\nis always bitwise, the function can always return true. If it's\nsometimes bitwise, it can return true or false as appropriate. If it's\nnever bitwise, then it can either always return false or the support\nfunction can be omitted altogether (so that the safe value is the\ndefault).\n\nI don't think you're going to save very much by avoiding an indirect\nfunction call in the \"always\" case. It doesn't really seem worth the\ncomplexity of making that a special case.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Mon, 30 Dec 2019 12:44:53 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Mon, Dec 30, 2019 at 9:45 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > For example, float and numeric types are \"never bitwise equal\", while array,\n> > text, and other container types are \"maybe bitwise equal\". An array of\n> > integers\n> > or text with C collation can be treated as bitwise equal attributes, and it\n> > would be too harsh to restrict them from deduplication.\n\nWe might as well support container types (like array) in the first\nPostgres version that has nbtree deduplication, I suppose. Even still,\nI don't think that it actually matters much to users. B-Tree indexes\non arrays are probably very rare. Note that I don't consider text to\nbe a container type here -- obviously btree/text_ops is a very\nimportant opclass for the deduplication feature. It may be the most\nimportant opclass overall.\n\nRecursively invoking a support function for the \"contained\" data type\nin the btree/array_ops support function seems like it might be messy.\nNot sure about that, though.\n\n> > What bothers me is that this option will unlikely be helpful on its own\n> > and we\n> > should also provide some kind of recheck function along with opclass, which\n> > complicates this idea even further and doesn't seem very clear.\n>\n> It seems like the simplest thing might be to forget about the 'char'\n> column and just have a support function which can be used to assess\n> whether a given opclass's notion of equality is bitwise.\n\nI like the idea of relying only on a support function.\n\nThis approach makes collations a problem that the opclass author has\nto deal with directly, as is the case within a SortSupport support\nfunction. Also seems like it would make life easier for third party\ndata types that want to make use of these optimizations (if in fact\nthere are any).\n\nI also see little downside to this approach. The extra cycles\nshouldn't be noticeable. As far as the B-Tree deduplication logic is\nconcerned, the final boolean value (is deduplication safe?) comes from\nthe index metapage -- we pass that down through an insertion scankey.\nWe only need to determine whether or not the optimization is safe at\nCREATE INDEX time. (Actually, I don't want to commit to the idea that\nnbtree should only call this support function at CREATE INDEX time\nright now. I'm sure that it will hardly ever need to be called,\nthough.)\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 30 Dec 2019 14:40:31 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Tue, Dec 24, 2019 at 4:29 AM Anastasia Lubennikova\n<a.lubennikova@postgrespro.ru> wrote:\n> I updated the patchset.\n> The first patch now contains only infrastructure changes\n> and the second one sets opcisbitwise for btree opclasses in pg_opclass.dat.\n\nWe should try to formally define what we're trying to represent about\nB-Tree opclasses here -- the definition of\n\"opcisbitwise\"/preciseness/whatever should be tightened up. In\nparticular, it should be clear how the \"image\" binary row comparators\n[1] (i.e. \"operator *= equality\" stuff) fit in. This new concept\nshould be defined in terms of that existing concept -- we're talking\nabout exactly the same variety of \"internal binary equality\" here, I\nthink.\n\nI propose that we adopt the following definition: For an operator\nclass to be safe, its equality operator has to always agree with\ndatum_image_eq() (i.e. two datums must be bitwise equal after\ndetoasting).\n\n(Maybe we should say something about \"operator *= equality\" as well\n(or instead), since that is already documented in [1].)\n\nWe may also want to say something about foreign keys in this formal\ndefinition of \"opcisbitwise\"/preciseness. Discussion around the bug\nfixed by commit 1ffa59a85cb [1] showed that there was plenty of\nconfusion in this area. Commit 1ffa59a85cb simply solved the problem\nthat existed with foreign keys, without \"joining the dots\". It reused\nthe rowtypes.c \"operator *= equality\" stuff to fix the problem, but\nonly in an ad-hoc and undoumented way. Let's not do that again now.\n\nNote: In theory this definition is stricter than truly necessary to\nmake deduplication safe, because we can imagine a contrived case in\nwhich an operator class exists where datum_image_eq() does not always\nagree with the equality operator, even though the equality operator\nwill reliably consider two datums to be equal only when they have\nidentical outputs from the underlying type's output function. This\ncould happen when an operator class author wasn't very careful about\nzeroing padding -- this may not have mattered to the opclass author\nbecause nobody relied on that padding anyway. I think that stuff like\nthis is not worth worrying about -- it can only happen because the\ndatatype/operator class author was very sloppy.\n\nNote also: We seem to make this assumption already. Maybe this\nuninitialized bytes side issue doesn't even need to be pointed out or\ndiscussed. The comment just above VALGRIND_CHECK_MEM_IS_DEFINED()\nwithin PageAddItemExtended() seems to suggest this. The comment\nspecifically mentions datumIsEqual() (not datum_image_eq()), but it's\nexactly the same issue.\n\n[1] https://www.postgresql.org/docs/devel/functions-comparisons.html#COMPOSITE-TYPE-COMPARISON\n[2] https://www.postgresql.org/message-id/flat/3326fc2e-bc02-d4c5-e3e5-e54da466e89a%402ndquadrant.com\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 30 Dec 2019 15:57:35 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Mon, Dec 30, 2019 at 6:58 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> I propose that we adopt the following definition: For an operator\n> class to be safe, its equality operator has to always agree with\n> datum_image_eq() (i.e. two datums must be bitwise equal after\n> detoasting).\n\nI suggested using datumIsEqual() as the canonical definition. (I\nwonder why datum_image_eq() does not reuse that function?)\n\n> Note: In theory this definition is stricter than truly necessary to\n> make deduplication safe, because we can imagine a contrived case in\n> which an operator class exists where datum_image_eq() does not always\n> agree with the equality operator, even though the equality operator\n> will reliably consider two datums to be equal only when they have\n> identical outputs from the underlying type's output function. This\n> could happen when an operator class author wasn't very careful about\n> zeroing padding -- this may not have mattered to the opclass author\n> because nobody relied on that padding anyway. I think that stuff like\n> this is not worth worrying about -- it can only happen because the\n> datatype/operator class author was very sloppy.\n\n+1.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 2 Jan 2020 09:42:32 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Thu, Jan 2, 2020 at 6:42 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> On Mon, Dec 30, 2019 at 6:58 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> > I propose that we adopt the following definition: For an operator\n> > class to be safe, its equality operator has to always agree with\n> > datum_image_eq() (i.e. two datums must be bitwise equal after\n> > detoasting).\n>\n> I suggested using datumIsEqual() as the canonical definition. (I\n> wonder why datum_image_eq() does not reuse that function?)\n\nThe difference between datum_image_eq() and datumIsEqual() is that\nonly the former will consider two datums equal when they happen to\nhave different TOAST input states -- we need that here. datumIsEqual()\navoids doing this because sometimes it needs to work for callers\noperating within an aborted transaction. datum_image_eq() was\noriginally used for the \"*=, *<>, *<, *<=, *>, and *>=\" rowtype B-Tree\noperator class needed by REFRESH MATERIALIZED VIEW CONCURRENTLY.\n(Actually, that's not quite true, since datum_image_eq() is a spin-off\nof the rowtype code that was added much more recently to fix a bug in\nforeign keys.)\n\nThe B-Tree code and amcheck need to be tolerant of inconsistent TOAST\ninput states. This isn't particularly likely to happen, but it would\nbe hard to revoke the general assumption that that's okay now. Also,\nit's not that hard to deal with it directly. For example, we're not\nreliant on equal index tuples all being the same size in the\ndeduplication patch.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Thu, 2 Jan 2020 09:11:12 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Thu, Jan 2, 2020 at 12:11 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> The difference between datum_image_eq() and datumIsEqual() is that\n> only the former will consider two datums equal when they happen to\n> have different TOAST input states -- we need that here.\n\nAh, OK. Sorry for the noise.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 2 Jan 2020 12:37:13 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On 31.12.2019 01:40, Peter Geoghegan wrote:\n> On Mon, Dec 30, 2019 at 9:45 AM Robert Haas <robertmhaas@gmail.com> wrote:\n>>> For example, float and numeric types are \"never bitwise equal\", while array,\n>>> text, and other container types are \"maybe bitwise equal\". An array of\n>>> integers\n>>> or text with C collation can be treated as bitwise equal attributes, and it\n>>> would be too harsh to restrict them from deduplication.\n> We might as well support container types (like array) in the first\n> Postgres version that has nbtree deduplication, I suppose. Even still,\n> I don't think that it actually matters much to users. B-Tree indexes\n> on arrays are probably very rare. Note that I don't consider text to\n> be a container type here -- obviously btree/text_ops is a very\n> important opclass for the deduplication feature. It may be the most\n> important opclass overall.\n>\n> Recursively invoking a support function for the \"contained\" data type\n> in the btree/array_ops support function seems like it might be messy.\n> Not sure about that, though.\n>\n>>> What bothers me is that this option will unlikely be helpful on its own\n>>> and we\n>>> should also provide some kind of recheck function along with opclass, which\n>>> complicates this idea even further and doesn't seem very clear.\n>> It seems like the simplest thing might be to forget about the 'char'\n>> column and just have a support function which can be used to assess\n>> whether a given opclass's notion of equality is bitwise.\n> I like the idea of relying only on a support function.\n\nIn attachment you can find the WIP patch that adds support function for \nbtree opclasses.\nBefore continuing, I want to ensure that I understood the discussion \nabove correctly.\n\nCurrent version of the patch adds:\n\n1) new syntax, which allow to provide support function:\n\nCREATE OPERATOR CLASS int4_ops_test\nFOR TYPE int4 USING btree AS\n         OPERATOR 1 =(int4, int4),\n         FUNCTION 1 btint4cmp(int4, int4),\n         SUPPORT datum_image_eqisbitwise;\n\nWe probably can add more words to specify the purpose of the support \nfunction.\nDo you have any other objections about the place of this new element in \nCreateOplcass syntax structure?\n\n2) trivial support function that always returns true \n'datum_image_eqisbitwise'.\nIt is named after 'datum_image_eq', because we define this support \nfunction via its behavior.\n\nIf this prototype is fine, I will continue this work and add support \nfunctions for other opclasses, update pg_dump and documentation.\n\nThoughts?", "msg_date": "Mon, 13 Jan 2020 23:49:36 +0300", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Mon, Jan 13, 2020 at 12:49 PM Anastasia Lubennikova\n<a.lubennikova@postgrespro.ru> wrote:\n> In attachment you can find the WIP patch that adds support function for\n> btree opclasses.\n\nCool. Thanks!\n\n> Current version of the patch adds:\n>\n> 1) new syntax, which allow to provide support function:\n>\n> CREATE OPERATOR CLASS int4_ops_test\n> FOR TYPE int4 USING btree AS\n> OPERATOR 1 =(int4, int4),\n> FUNCTION 1 btint4cmp(int4, int4),\n> SUPPORT datum_image_eqisbitwise;\n\nHmm. Do we really need these grammar changes? If so, why? I think that\nyou wanted to make this something that could work with any opclass of\nany index access method, but I don't see that as a useful goal. (If it\nwas useful, it could be considered later, on a case by case basis.)\n\nI imagined that this infrastructure would consist of inventing a new\nvariety of B-Tree opclass support function -- something like\nsortsupport. You could generalize from the example of commit\nc6e3ac11b60, which added SortSupport functions (also known as \"B-Tree\nsupport function 2\" functions). You might also take a look at the much\nmore recent commit 0a459cec96d, which added in_range functions (also\nknown as \"B-Tree support function 3\"). Note that neither of those two\ncommits had grammar changes for CREATE OPERATOR CLASS, or anything\nlike that. What I have in mind is a \"B-Tree support function 4\",\nobviously.\n\nYou should probably add a C function that's similar to\nPrepareSortSupportFromIndexRel()/FinishSortSupportFunction() that will\nbe called from the B-Tree code. This will give a simple yes/no answer\nto the question: \"Is it safe to apply deduplication to this Relation\"?\nThis C function will know to return false for an opclass that doesn't\nhave any support function 4 set for any single attribute. It can\nprovide a general overview of what we're telling the caller about the\nopclass here, etc. Another patch could add a similar function that\nworks with a plain operator, a bit like\nPrepareSortSupportFromOrderingOp() -- but that isn't necessary now.\n\nI suppose that this approach requires something a bit like a struct\nSortSupportData, with filled-out collation information, etc. The\nnbtree code expects a simple yes/no answer based on all columns in the\nindex, so it will be necessary to serialize that information to send\nit across the SQL function interface -- the pg_proc support function\nwill have one argument of type \"internal\". And, I suppose that you'll\nalso need some basic btvalidate() validation code.\n\n> We probably can add more words to specify the purpose of the support\n> function.\n\nRight -- some documentation is needed in btree.sgml, alongside the\nexisting stuff for support functions 1, 2, and 3.\n\n> 2) trivial support function that always returns true\n> 'datum_image_eqisbitwise'.\n> It is named after 'datum_image_eq', because we define this support\n> function via its behavior.\n\nI like the idea of a generic, trivial SQL-callable function that all\nsimple scalar types can use -- one that just returns true. Maybe we\nshould call this general class of function an \"image_equal\" function,\nand refer to \"image equality\" in the btree.sgml docs. I don't think\nthat using the term \"bitwise\" is helpful, since it sounds very precise\nbut is actually slightly inaccurate (since TOASTable datums can be\n\"image equal\", but not bitwise equal according to datumIsEqual()).\n\nHow does everyone feel about \"image equality\" as a name? As I said\nbefore, it seems like a good idea to tie this new infrastructure to\nexisting infrastructure used for things like REFRESH MATERIALIZED VIEW\nCONCURRENTLY.\n\n> If this prototype is fine, I will continue this work and add support\n> functions for other opclasses, update pg_dump and documentation.\n\nIf this work is structured as a new support function, then it isn't\nreally a user-visible feature -- you won't need pg_dump support, psql\nsupport, etc. Most of the documentation will be for operator class\nauthors rather than regular users. We can document the specific\nopclasses that have support for deduplication later, if at all.\n\nI think it would be fine if the deduplication docs (not the docs for\nthis infrastructure) just pointed out specific cases that we *cannot*\nsupport -- there are not many exceptions (numeric, text with a\nnondeterministic collation, a few others like that).\n\n--\nPeter Geoghegan\n\n\n", "msg_date": "Mon, 13 Jan 2020 14:53:20 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Sun, Aug 25, 2019 at 1:56 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> I agree that teaching opclasses to say whether this is okay is a\n> reasonable approach.\n\nI've begun working on this, with help from Anastasia.\n\nMy working assumption is that I only need to care about\nopclass-declared input data types (pg_opclass.opcintype), plus the\ncorresponding collations -- the former can be used to lookup an\nappropriate pg_amproc entry (i.e. B-Tree support function 4), while\nthe latter are passed to the support function to get an answer about\nwhether or not it's okay to use deduplication. This approach seems to\nbe good enough as far as the deduplication project's needs are\nconcerned. However, I think that I probably need to take a broader\nview of the problem than that. Any guidance would be much appreciated.\n\n> > Consumers of this new infrastructure probably won't be limited to the\n> > deduplication feature;\n>\n> Indeed, we run up against this sort of thing all the time in, eg, planner\n> optimizations. I think some sort of \"equality is precise\" indicator\n> would be really useful for a lot of things.\n\nSuppose I wanted to add support for deduplication of a B-Tree index on\nan array of integers. This probably wouldn't be very compelling, but\njust suppose. It's not clear how this could work within the confines\nof the type and operator class systems.\n\nI can hardly determine that it's safe or unsafe to do so at CREATE\nINDEX time, since the opclass-declared input data type is always the\npg_type.oid corresponding to 'anyarray' -- I am forced to make a\ngeneric assumption that deduplication is not safe. I must make this\nconservative assumption since, in general, the indexed column could\nturn out to be an array of numeric datums -- a \"transitively unsafe\"\nanyarray (numeric's display scale issue could leak into anyarray). I'm\nnot actually worried about any practical downside that this may create\nfor users of the B-Tree deduplication feature; a B-Tree index on an\narray *is* a pretty niche thing. Does seem like I should make sure\nthat I get this right, though.\n\nCode like the 'anyarray' B-Tree support function 1 (i.e.\nbtarraycmp()/array_cmp()) doesn't hint at a solution -- it merely does\na lookup of the underlying type's comparator using the typcache. That\ndepends on having actual anyarray datums to do something with, which\nisn't something that this new infrastructure can rely on in any way.\n\nI suppose that the only thing that would work here would be to somehow\nlook through the pg_attribute entry for the index column, which will\nhave the details required to distinguish between (say) an array of\nintegers (which is safe, I think) from an array of numerics (which is\nunsafe). From there, the information about the element type could\n(say) be passed to the anyarray default opclass' support function 4,\nwhich could do its own internal lookup. That seems like it might be a\nsolution in search of a problem, though.\n\nBTW, I currently forbid cross-type support function 4 entries for an\nopclass, on the grounds that that isn't sensible for deduplication. Do\nyou think that that restriction is appropriate in general, given the\nlikelihood that this support function will be used in several other\nareas?\n\nThanks\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Sat, 8 Feb 2020 18:50:20 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" }, { "msg_contents": "On Sat, Feb 8, 2020 at 6:50 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> My working assumption is that I only need to care about\n> opclass-declared input data types (pg_opclass.opcintype), plus the\n> corresponding collations -- the former can be used to lookup an\n> appropriate pg_amproc entry (i.e. B-Tree support function 4), while\n> the latter are passed to the support function to get an answer about\n> whether or not it's okay to use deduplication. This approach seems to\n> be good enough as far as the deduplication project's needs are\n> concerned. However, I think that I probably need to take a broader\n> view of the problem than that. Any guidance would be much appreciated.\n\nv33 of the deduplication patch series was just posted. It included\nthis infrastructure in a separate patch, which isn't that big on its\nown. See:\n\nhttps://www.postgresql.org/message-id/CAH2-WzmQGYDDoAETGhpGtJQRv_uFHMjvQZ6JdLV-sxGoCgLBNg%40mail.gmail.com\n\nExpert review of the opclass infrastructure still seems like a good\nidea. I'm sure that it does everything that the deduplication feature\nwill ever need, but I'm a little concerned about painting myself into\na corner as far as other things that use the API are concerned. In\nparticular, I hope that I haven't failed to anticipate a requirement\nthat the planner has for the new API.\n\nThanks\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Thu, 13 Feb 2020 19:04:14 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: Building infrastructure for B-Tree deduplication that recognizes\n when opclass equality is also equivalence" } ]
[ { "msg_contents": "Hi!\n\nIn many cases GiST index can be build fast using z-order sorting.\n\nI've looked into proof of concept by Nikita Glukhov [0] and it looks very interesting.\nSo, I've implemented yet another version of B-tree-like GiST build.\nIt's main use case and benefits can be summarized with small example:\n\npostgres=# create table x as select point (random(),random()) from generate_series(1,3000000,1);\nSELECT 3000000\nTime: 5061,967 ms (00:05,062)\npostgres=# create index ON x using gist (point ) with (fast_build_sort_function=gist_point_sortsupport);\nCREATE INDEX\nTime: 6140,227 ms (00:06,140)\npostgres=# create index ON x using gist (point );\nCREATE INDEX\nTime: 32061,200 ms (00:32,061)\n\nAs you can see, Z-order build is on order of magnitude faster. Select performance is roughly the same. Also, index is significantly smaller.\n\nNikita's PoC is faster because it uses parallel build, but it intervenes into B-tree code a lot (for reuse). This patchset is GiST-isolated.\nMy biggest concern is that passing function to relation option seems a bit hacky. You can pass there any function matching sort support signature.\nEmbedding this function into opclass makes no sense: it does not affect scan anyhow.\n\nIn current version, docs and tests are not implemented. I want to discuss overall design. Do we really want yet another GiST build, if it is 3-10 times faster?\n\nThanks!\n\nBest regards, Andrey Borodin.\n\n[0] https://github.com/postgres/postgres/compare/master...glukhovn:gist_btree_build", "msg_date": "Mon, 26 Aug 2019 12:59:11 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Yet another fast GiST build" }, { "msg_contents": "Hello,\n\nThis is very interesting. In my pipeline currently GiST index rebuild is\nthe biggest time consuming step.\n\nI believe introducing optional concept of order in the GiST opclass will be\nbeneficial not only for fast build, but for other tasks later:\n - CLUSTER can order the table using that notion, in parallel way.\n - btree_gist can be even closer to btree by getting the tuples sorted\ninside page.\n - tree descend on insertion in future can traverse the list in more\nopportunistic way, calculating penalty for siblings-by-order first.\n\nI believe everywhere the idea of ordering is needed it's provided by giving\na btree opclass.\n\nHow about giving a link to btree opclass inside a gist opclass?\n\n\nOn Mon, Aug 26, 2019 at 10:59 AM Andrey Borodin <x4mmm@yandex-team.ru>\nwrote:\n\n> Hi!\n>\n> In many cases GiST index can be build fast using z-order sorting.\n>\n> I've looked into proof of concept by Nikita Glukhov [0] and it looks very\n> interesting.\n> So, I've implemented yet another version of B-tree-like GiST build.\n> It's main use case and benefits can be summarized with small example:\n>\n> postgres=# create table x as select point (random(),random()) from\n> generate_series(1,3000000,1);\n> SELECT 3000000\n> Time: 5061,967 ms (00:05,062)\n> postgres=# create index ON x using gist (point ) with\n> (fast_build_sort_function=gist_point_sortsupport);\n> CREATE INDEX\n> Time: 6140,227 ms (00:06,140)\n> postgres=# create index ON x using gist (point );\n> CREATE INDEX\n> Time: 32061,200 ms (00:32,061)\n>\n> As you can see, Z-order build is on order of magnitude faster. Select\n> performance is roughly the same. Also, index is significantly smaller.\n>\n> Nikita's PoC is faster because it uses parallel build, but it intervenes\n> into B-tree code a lot (for reuse). This patchset is GiST-isolated.\n> My biggest concern is that passing function to relation option seems a bit\n> hacky. You can pass there any function matching sort support signature.\n> Embedding this function into opclass makes no sense: it does not affect\n> scan anyhow.\n>\n> In current version, docs and tests are not implemented. I want to discuss\n> overall design. Do we really want yet another GiST build, if it is 3-10\n> times faster?\n>\n> Thanks!\n>\n> Best regards, Andrey Borodin.\n>\n> [0]\n> https://github.com/postgres/postgres/compare/master...glukhovn:gist_btree_build\n>\n>\n\n-- \nDarafei Praliaskouski\nSupport me: http://patreon.com/komzpa\n\nHello,This is very interesting. In my pipeline currently GiST index rebuild is the biggest time consuming step.I believe introducing optional concept of order in the GiST opclass will be beneficial not only for fast build, but for other tasks later: - CLUSTER can order the table using that notion, in parallel way. - btree_gist can be even closer to btree by getting the tuples sorted inside page. - tree descend on insertion in future can traverse the list in more opportunistic way, calculating penalty for siblings-by-order first.I believe everywhere the idea of ordering is needed it's provided by giving a btree opclass.How about giving a link to btree opclass inside a gist opclass?On Mon, Aug 26, 2019 at 10:59 AM Andrey Borodin <x4mmm@yandex-team.ru> wrote:Hi!\n\nIn many cases GiST index can be build fast using z-order sorting.\n\nI've looked into proof of concept by Nikita Glukhov [0] and it looks very interesting.\nSo, I've implemented yet another version of B-tree-like GiST build.\nIt's main use case and benefits can be summarized with small example:\n\npostgres=# create table x as select point (random(),random()) from generate_series(1,3000000,1);\nSELECT 3000000\nTime: 5061,967 ms (00:05,062)\npostgres=# create index ON x using gist (point ) with (fast_build_sort_function=gist_point_sortsupport);\nCREATE INDEX\nTime: 6140,227 ms (00:06,140)\npostgres=# create index ON x using gist (point );\nCREATE INDEX\nTime: 32061,200 ms (00:32,061)\n\nAs you can see, Z-order build is on order of magnitude faster. Select performance is roughly the same. Also, index is significantly smaller.\n\nNikita's PoC is faster because it uses parallel build, but it intervenes into B-tree code a lot (for reuse). This patchset is GiST-isolated.\nMy biggest concern is that passing function to relation option seems a bit hacky. You can pass there any function matching sort support signature.\nEmbedding this function into opclass makes no sense: it does not affect scan anyhow.\n\nIn current version, docs and tests are not implemented. I want to discuss overall design. Do we really want yet another GiST build, if it is 3-10 times faster?\n\nThanks!\n\nBest regards, Andrey Borodin.\n\n[0] https://github.com/postgres/postgres/compare/master...glukhovn:gist_btree_build\n\n-- Darafei PraliaskouskiSupport me: http://patreon.com/komzpa", "msg_date": "Mon, 26 Aug 2019 13:27:27 +0300", "msg_from": "=?UTF-8?Q?Darafei_=22Kom=D1=8Fpa=22_Praliaskouski?= <me@komzpa.net>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 26/08/2019 10:59, Andrey Borodin wrote:\n> Hi!\n> \n> In many cases GiST index can be build fast using z-order sorting.\n> \n> I've looked into proof of concept by Nikita Glukhov [0] and it looks very interesting.\n> So, I've implemented yet another version of B-tree-like GiST build.\n\nCool!\n\n> My biggest concern is that passing function to relation option seems\n> a bit hacky. You can pass there any function matching sort support\n> signature. Embedding this function into opclass makes no sense: it\n> does not affect scan anyhow.\n\nI think it should be a new, optional, GiST \"AM support function\", in \npg_amproc. That's how the sort support functions are defined for B-tree \nopfamilies, too.\n\n- Heikki\n\n\n", "msg_date": "Mon, 26 Aug 2019 13:47:22 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Mon, Aug 26, 2019 at 10:59 AM Andrey Borodin <x4mmm@yandex-team.ru> wrote:\n> In many cases GiST index can be build fast using z-order sorting.\n>\n> I've looked into proof of concept by Nikita Glukhov [0] and it looks very interesting.\n> So, I've implemented yet another version of B-tree-like GiST build.\n> It's main use case and benefits can be summarized with small example:\n>\n> postgres=# create table x as select point (random(),random()) from generate_series(1,3000000,1);\n> SELECT 3000000\n> Time: 5061,967 ms (00:05,062)\n> postgres=# create index ON x using gist (point ) with (fast_build_sort_function=gist_point_sortsupport);\n> CREATE INDEX\n> Time: 6140,227 ms (00:06,140)\n> postgres=# create index ON x using gist (point );\n> CREATE INDEX\n> Time: 32061,200 ms (00:32,061)\n>\n> As you can see, Z-order build is on order of magnitude faster. Select performance is roughly the same. Also, index is significantly smaller.\n\nCool! These experiments bring me to following thoughts. Can we not\nonly build, but also maintain GiST indexes in B-tree-like manner? If\nwe put Z-value together with MBR to the non-leaf keys, that should be\npossible. Maintaining it in B-tree-like manner would have a lot of\nadvantages.\n1) Binary search in non-leaf pages instead of probing each key is much faster.\n2) Split algorithm is also simpler and faster.\n3) We can refind existing index tuple in predictable time of O(log N).\nAnd this doesn't depend on MBR overlapping degree. This is valuable\nfor future table AMs, which would have notion of deleting individual\nindex tuples (for instance, zheap promises to eventually support\ndelete-marking indexes).\n\nEventually, we may come to the idea of B-tree indexes with\nuser-defined additional keys in non-leaf tuples, which could be used\nfor scanning.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Fri, 30 Aug 2019 01:47:49 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Thu, Aug 29, 2019 at 3:48 PM Alexander Korotkov\n<a.korotkov@postgrespro.ru> wrote:\n> > As you can see, Z-order build is on order of magnitude faster. Select performance is roughly the same. Also, index is significantly smaller.\n>\n> Cool! These experiments bring me to following thoughts. Can we not\n> only build, but also maintain GiST indexes in B-tree-like manner? If\n> we put Z-value together with MBR to the non-leaf keys, that should be\n> possible. Maintaining it in B-tree-like manner would have a lot of\n> advantages.\n\nI'm not an expert on GiST, but that seems like it would have a lot of\nadvantages in the long term. It is certainly theoretically appealing.\n\nCould this make it easier to use merge join with containment\noperators? I'm thinking of things like geospatial joins, which can\ngenerally only be performed as nested loop joins at the moment. This\nis often wildly inefficient.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Thu, 29 Aug 2019 16:33:48 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Fri, Aug 30, 2019 at 2:34 AM Peter Geoghegan <pg@bowt.ie> wrote:\n> On Thu, Aug 29, 2019 at 3:48 PM Alexander Korotkov\n> <a.korotkov@postgrespro.ru> wrote:\n> > > As you can see, Z-order build is on order of magnitude faster. Select performance is roughly the same. Also, index is significantly smaller.\n> >\n> > Cool! These experiments bring me to following thoughts. Can we not\n> > only build, but also maintain GiST indexes in B-tree-like manner? If\n> > we put Z-value together with MBR to the non-leaf keys, that should be\n> > possible. Maintaining it in B-tree-like manner would have a lot of\n> > advantages.\n>\n> I'm not an expert on GiST, but that seems like it would have a lot of\n> advantages in the long term. It is certainly theoretically appealing.\n>\n> Could this make it easier to use merge join with containment\n> operators? I'm thinking of things like geospatial joins, which can\n> generally only be performed as nested loop joins at the moment. This\n> is often wildly inefficient.\n\nAFAICS, spatial joins aren't going to be as easy as just merge joins\non Z-value. When searching for close points in two datasets (closer\nthan given threshold) we can scan some ranges of Z-value in one\ndataset while iterating on another. But dealing with prolonged\nspatial objects in not that easy. In order to determine if there are\nmatching values in given Z-range you also need to be aware on size of\nobjects inside that Z-range. So, before merge-like join you need to\nnot only sort, but build some index-like structure.\n\nAlternatively you can encode size in Z-value. But this increases\ndimensionality of space and decreases efficiency of join. Also,\nspatial join can be made using two indexes, even just current GiST\nwithout Z-values. We've prototyped that, see [1].\n\nLinks\n1. https://github.com/pgsphere/pgsphere/blob/crossmatch_cnode/crossmatch.c\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Fri, 30 Aug 2019 06:21:55 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Thu, Aug 29, 2019 at 8:22 PM Alexander Korotkov\n<a.korotkov@postgrespro.ru> wrote:\n> Alternatively you can encode size in Z-value. But this increases\n> dimensionality of space and decreases efficiency of join. Also,\n> spatial join can be made using two indexes, even just current GiST\n> without Z-values. We've prototyped that, see [1].\n\nI'm pretty sure that spatial joins generally need two spatial indexes\n(usually R-Trees). There seems to have been quite a lot of research in\nit in the 1990s.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Thu, 29 Aug 2019 20:28:02 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> 30 авг. 2019 г., в 3:47, Alexander Korotkov <a.korotkov@postgrespro.ru> написал(а):\n> \n> 1) Binary search in non-leaf pages instead of probing each key is much faster.\n\nThat's a neat idea, but key union breaks ordering, even for z-order.\nfor two sets of tuples X and Y\nif for any i,o from N, Xi < Yo\ndoes not guaranty union(X) < union (Y) \n\nFor example consider this z-ordered keyspace (picture attached)\n\n\nunion(5, 9) is z-order-smaller than union(4,4)\n\nI'm not even sure we can use sorted search for choosing subtree for insertion.\n\nHow do you think, should I supply GiST-build patch with docs and tests and add it to CF? Or do we need more design discussion before?\n\n\nBest regards, Andrey Borodin.", "msg_date": "Fri, 30 Aug 2019 16:44:43 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> 30 авг. 2019 г., в 16:44, Andrey Borodin <x4mmm@yandex-team.ru> написал(а):\n> \n> \n> How do you think, should I supply GiST-build patch with docs and tests and add it to CF? Or do we need more design discussion before?\n\nPFA v2: now sort support is part of opclass.\nThere's a problem with Z-ordering NaN which causes regression tests to fail. So I decided not to add patch to CF (despite having few minutes to do so).\nHow to correctly Z-order NaN? So that it would be consistent with semantics of union() and consistent() functions. If one of values is NaN, then we consider all it's bits to be 1?\n\nBTW patch uses \nunion {\n float f;\n uint32 i;\n }\nI hope it's OK, because AFAIK we do not have non-IEEE-754 platforms now.\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Sun, 1 Sep 2019 15:53:26 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Fri, Aug 30, 2019 at 2:44 PM Andrey Borodin <x4mmm@yandex-team.ru> wrote:\n>\n> 30 авг. 2019 г., в 3:47, Alexander Korotkov <a.korotkov@postgrespro.ru> написал(а):\n>\n> 1) Binary search in non-leaf pages instead of probing each key is much faster.\n>\n>\n> That's a neat idea, but key union breaks ordering, even for z-order.\n> for two sets of tuples X and Y\n> if for any i,o from N, Xi < Yo\n> does not guaranty union(X) < union (Y)\n>\n> For example consider this z-ordered keyspace (picture attached)\n>\n> union(5, 9) is z-order-smaller than union(4,4)\n>\n> I'm not even sure we can use sorted search for choosing subtree for insertion.\n\n\nSorry, I didn't explain my proposal in enough details. I didn't mean\nB-tree separator keys would be the same as union key (MBR). I mean\nB-tree on Z-values, which maintains union key in addition to separator\nkeys. So, you select downlink to insert using separator Z-values and\nthen also extend union key (if needed). It's probably still not\nenough detail yet. I'll try to spend more time for more detailed\ndescription later.\n\n>\n> How do you think, should I supply GiST-build patch with docs and tests and add it to CF? Or do we need more design discussion before?\n\n\n+1 for adding to CF.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Sun, 1 Sep 2019 20:17:48 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Fri, Aug 30, 2019 at 6:28 AM Peter Geoghegan <pg@bowt.ie> wrote:\n> On Thu, Aug 29, 2019 at 8:22 PM Alexander Korotkov\n> <a.korotkov@postgrespro.ru> wrote:\n> > Alternatively you can encode size in Z-value. But this increases\n> > dimensionality of space and decreases efficiency of join. Also,\n> > spatial join can be made using two indexes, even just current GiST\n> > without Z-values. We've prototyped that, see [1].\n>\n> I'm pretty sure that spatial joins generally need two spatial indexes\n> (usually R-Trees). There seems to have been quite a lot of research in\n> it in the 1990s.\n\nSure, our prototype was an implementation of one of such papers. My\npoint is that advantages of Z-value ordered GiST for spatial joins are\nnot yet clear for me. Except faster build and smaller index, which\nare general advantages.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Sun, 1 Sep 2019 20:20:51 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> 1 сент. 2019 г., в 15:53, Andrey Borodin <x4mmm@yandex-team.ru> написал(а):\n> \n> \n> <v2-0001-Add-sort-support-for-point-gist_point_sortsupport.patch><v2-0002-Implement-GiST-build-using-sort-support.patch>\n\nHere's V3 of the patch set.\nChanges:\n1. Added some documentation of new sort support routines\n2. Fixed bug with dirty pages\n\nI did not add sort support procs to built-in boxes, circles and polys, since it may be not optimal index for them. However, for points Z-order is quite good as a default.\n\nTests only pass with fixes for GiST KNN from Alexander in other thread.\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Sun, 8 Sep 2019 13:54:35 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Sun, Sep 08, 2019 at 01:54:35PM +0500, Andrey Borodin wrote:\n> Here's V3 of the patch set.\n> Changes:\n> 1. Added some documentation of new sort support routines\n> 2. Fixed bug with dirty pages\n> \n> I did not add sort support procs to built-in boxes, circles and\n> polys, since it may be not optimal index for them. However, for\n> points Z-order is quite good as a defaul t.\n\nThe latest patch does not apply. Could you send a rebase? I have\nmoved the patch to next CF, waiting on author for now.\n--\nMichael", "msg_date": "Sun, 1 Dec 2019 11:06:35 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> 1 дек. 2019 г., в 7:06, Michael Paquier <michael@paquier.xyz> написал(а):\n> \n> On Sun, Sep 08, 2019 at 01:54:35PM +0500, Andrey Borodin wrote:\n>> Here's V3 of the patch set.\n>> Changes:\n>> 1. Added some documentation of new sort support routines\n>> 2. Fixed bug with dirty pages\n>> \n>> I did not add sort support procs to built-in boxes, circles and\n>> polys, since it may be not optimal index for them. However, for\n>> points Z-order is quite good as a defaul t.\n> \n> The latest patch does not apply. Could you send a rebase? I have\n> moved the patch to next CF, waiting on author for now.\n\nThanks, Michael!\n\nPFA rebased patch.\n\nBest regards, Andrey Borodin.", "msg_date": "Mon, 30 Dec 2019 11:43:04 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Mon, Dec 30, 2019 at 7:43 PM Andrey Borodin <x4mmm@yandex-team.ru> wrote:\n> PFA rebased patch.\n\nHi Andrey,\n\nThis looks really interesting, and I am sure there are a lot of GIS\npeople who would love to see dramatically faster and smaller indexes\nin PG13. I don't know enough to comment on the details, but here are\nsome superficial comments:\n\n+ method is also optional and is used diring fast GiST build.\n\n-> during\n\n+ /* esteblish order between x and y */\n\n-> establish\n\n+/* Compute Z-oder for point */\n static inline uint64\n point_zorder_internal(Point *p)\n\n-> order\n\nCould this function please have a comment that explains why it works?\nI mean, just a breadcrumb... the name of the technique or something...\nso that uninitiated hackers can google their way to a clue (is it\n\"Morton encoding\"?)\n\nMSVC says:\n\nsrc/backend/access/gist/gistproc.c(1582): error C2065: 'INT32_MAX' :\nundeclared identifier\n\nGCC says:\n\ngistbuild.c: In function ‘gist_indexsortbuild’:\ngistbuild.c:256:4: error: ISO C90 forbids mixed declarations and code\n[-Werror=declaration-after-statement]\n IndexTuple *itvec = gistextractpage(lower_page, &vect_len);\n ^\n\n\n", "msg_date": "Wed, 19 Feb 2020 20:00:49 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Wed, Feb 19, 2020 at 8:00 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> Could this function please have a comment that explains why it works?\n> I mean, just a breadcrumb... the name of the technique or something...\n> so that uninitiated hackers can google their way to a clue (is it\n> \"Morton encoding\"?)\n\nOk I think I get it now after doing some homework.\n\n1. We expect floats to be in IEEE format, and the sort order of IEEE\nfloats is mostly correlated to the binary sort order of the bits\nreinterpreted as an int. It isn't in some special cases, but for this\nuse case we don't really care about that, we're just trying to\nencourage locality.\n2. We generate a Morton code that interleaves the bits of N integers\nto produce a single integer that preserves locality: things that were\nclose in the N dimensional space are close in the resulting integer.\n\nCool.\n\n+static int\n+my_fastcmp(Datum x, Datum y, SortSupport ssup)\n+{\n+ /* esteblish order between x and y */\n+\n+ return z1 == z2 ? 0 : z1 > z2 ? 1 : -1;\n+}\n\nThis example code from the documentation looks wrong, probably missing\neg int64 z1 = DatumGetInt64(x).\n\n\n", "msg_date": "Thu, 20 Feb 2020 10:14:02 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Thu, Feb 20, 2020 at 10:14 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n> 1. We expect floats to be in IEEE format, and the sort order of IEEE\n> floats is mostly correlated to the binary sort order of the bits\n> reinterpreted as an int. It isn't in some special cases, but for this\n> use case we don't really care about that, we're just trying to\n> encourage locality.\n\nI suppose there is a big jump in integer value (whether signed or\nunsigned) as you cross from positive to negative floats, and then the\nsort order is reversed. I have no idea if either of those things is a\nproblem worth fixing. That made me wonder if there might also be an\nendianness problem. It seems from some quick googling that all\ncurrent architectures have integers and floats of the same endianness.\nApparently this wasn't always the case, and some ARMs have a weird\nhalf-flipped arrangement for 64 bit floats, but not 32 bit floats as\nyou are using here.\n\n\n", "msg_date": "Mon, 24 Feb 2020 09:58:18 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Hi Thomas!\n\nThanks for looking into this! I’ll fix your notices asap.\n\n> On 24 февр. 2020 г., at 01:58, Thomas Munro <thomas.munro@gmail.com> wrote:\n> \n> On Thu, Feb 20, 2020 at 10:14 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n>> 1. We expect floats to be in IEEE format, and the sort order of IEEE\n>> floats is mostly correlated to the binary sort order of the bits\n>> reinterpreted as an int. It isn't in some special cases, but for this\n>> use case we don't really care about that, we're just trying to\n>> encourage locality.\n> \n> I suppose there is a big jump in integer value (whether signed or\n> unsigned) as you cross from positive to negative floats, and then the\n> sort order is reversed. I have no idea if either of those things is a\n> problem worth fixing. That made me wonder if there might also be an\n> endianness problem. It seems from some quick googling that all\n> current architectures have integers and floats of the same endianness.\n> Apparently this wasn't always the case, and some ARMs have a weird\n> half-flipped arrangement for 64 bit floats, but not 32 bit floats as\n> you are using here.\n\nYes, this leap is a problem for point as generic data type. And I do not know\nhow to fix it. It can cause inefficient Index Scans when searching near (0,0) and query\nwindow touches simultaneously all quadrants (4x slower).\nBut everything will be just fine when all data is in 2nd quadrant.\n\nActually, we do not need to add this hacky code to core: we can provide colum-wise\nordering or something similar as an example.\nThis feature is aimed at PostGIS and they already possess bit tricks tricks [0].\nI’ve taken this union code from PostGIS.\n\nThanks!\n\nBest regards, Andrey Borodin.\n\n\n[0] https://github.com/postgis/postgis/blob/master/postgis/gserialized_gist_nd.c#L1150\n\n", "msg_date": "Mon, 24 Feb 2020 13:50:31 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Hi!\n\n> On 24 февр. 2020 г., at 13:50, Andrey M. Borodin <x4mmm@yandex-team.ru> wrote:\n> \n> Hi Thomas!\n> \n> Thanks for looking into this! I’ll fix your notices asap.\n\nPFA v5.\nThomas, I've used your wording almost exactly with explanation how\npoint_zorder_internal() works. It has more explanation power than my attempts\nto compose good comment.\n\nThere is one design decision that worries me most:\nshould we use opclass function or index option to provide this sorting information?\nIt is needed only during index creation, actually. And having extra i-class only for fast build\nseems excessive.\nI think we can provide both ways and let opclass developers decide?\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Sat, 29 Feb 2020 17:13:20 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 2020-02-29 13:13, Andrey M. Borodin wrote:\n> Hi!\n> \n>> On 24 февр. 2020 г., at 13:50, Andrey M. Borodin \n>> <x4mmm@yandex-team.ru> wrote:\n>> \n>> Hi Thomas!\n>> \n>> Thanks for looking into this! I’ll fix your notices asap.\n> \n> PFA v5.\n> Thomas, I've used your wording almost exactly with explanation how\n> point_zorder_internal() works. It has more explanation power than my \n> attempts\n> to compose good comment.\n\nSmall typo alert:\nIn v5-0002-Implement-GiST-build-using-sort-support.patch there is:\n\n+ method is also optional and is used diring fast GiST build.\n\n'diring' should be 'during'\n\n\n\n", "msg_date": "Sat, 29 Feb 2020 13:20:02 +0100", "msg_from": "Erik Rijkers <er@xs4all.nl>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "> On 29 февр. 2020 г., at 17:20, Erik Rijkers <er@xs4all.nl> wrote:\n> \n> Small typo alert:\n> In v5-0002-Implement-GiST-build-using-sort-support.patch there is:\n> \n> + method is also optional and is used diring fast GiST build.\n> \n> 'diring' should be 'during'\n> \n\nThanks!\n\nI've fixed this and added patch with GiST reloption to provide sort support function.\n\nBest regards, Andrey Borodin.", "msg_date": "Sat, 29 Feb 2020 22:24:38 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "Hello,\n\nThanks for the patch and working on GiST infrastructure, it's really\nvaluable for PostGIS use cases and I wait to see this improvement in\nPG13.\n\nOn Sat, Feb 29, 2020 at 3:13 PM Andrey M. Borodin <x4mmm@yandex-team.ru> wrote:\n\n> Thomas, I've used your wording almost exactly with explanation how\n> point_zorder_internal() works. It has more explanation power than my attempts\n> to compose good comment.\n\nPostGIS uses this trick to ensure locality. In PostGIS 3 we enhanced\nthat trick to have the Hilbert curve instead of Z Order curve.\n\nFor visual representation have a look at these links:\n - http://blog.cleverelephant.ca/2019/08/postgis-3-sorting.html - as\nit's implemented in PostGIS btree sorting opclass\n - https://observablehq.com/@mourner/hilbert-curve-packing - to\nexplore general approach.\n\nIndeed if it feels insecure to work with bit magic that implementation\ncan be left out to extensions.\n\n> There is one design decision that worries me most:\n> should we use opclass function or index option to provide this sorting information?\n> It is needed only during index creation, actually. And having extra i-class only for fast build\n> seems excessive.\n> I think we can provide both ways and let opclass developers decide?\n\nReloption variant looks dirty. It won't cover an index on (id uuid,\ngeom geometry) where id is duplicated (say, tracked car identifier)\nbut present in every query - no way to pass such thing as reloption.\nI'm also concerned about security of passing a sortsupport function\nmanually during index creation (what if that's not from the same\nextension or even (wrong-)user defined something).\n\nWe know for sure it's a good idea for all btree_gist types and\ngeometry and I don't see a case where user would want to disable it.\nJust make it part of operator class, and that would also allow fast\ncreation of multi-column index.\n\nThanks.\n\n-- \nDarafei Praliaskouski\nSupport me: http://patreon.com/komzpa\n\n\n", "msg_date": "Sun, 1 Mar 2020 13:09:22 +0300", "msg_from": "=?UTF-8?Q?Darafei_=22Kom=D1=8Fpa=22_Praliaskouski?= <me@komzpa.net>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Awesome addition! Would it make sense to use x86's BMI2's PDEP instruction, or is the interleave computation too small of a percentage to introduce not-so-easy-to-port code? Also, I think it needs a bit more documentation to explain the logic, i.e. a link to https://stackoverflow.com/questions/39490345/interleave-bits-efficiently ? Thx for making it faster :)", "msg_date": "Fri, 03 Apr 2020 03:17:40 +0000", "msg_from": "Yuri Astrakhan <yuriastrakhan@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Hello Yuri,\n\nPDEP is indeed first thing that comes up when you start googling\nz-curve and bit interleaving :)\nWe had the code with z-curve generating PDEP instruction in PostGIS,\nand dropped it since. In sorting, we now utilize sort support / prefix\nsearch, and key generated as Hilbert curve, with fine tuning it for\ndifferent projections' geometric properties.\n\n From this patch the most valuable thing for us is the sorting build\ninfrastructure itself. Maybe to get it a bit more understandable for\npeople not deep in geometry it makes sense to first expose the\nbtree_gist datatypes to this thing? So that btree_gist index on\ninteger will be built exactly the same way the btree index on integer\nis built. This will also get everyone a reference point on the\nbottlenecks and optimality of patch.\n\nOn Fri, Apr 3, 2020 at 10:56 AM Yuri Astrakhan <yuriastrakhan@gmail.com> wrote:\n>\n> Awesome addition! Would it make sense to use x86's BMI2's PDEP instruction, or is the interleave computation too small of a percentage to introduce not-so-easy-to-port code? Also, I think it needs a bit more documentation to explain the logic, i.e. a link to https://stackoverflow.com/questions/39490345/interleave-bits-efficiently ? Thx for making it faster :)\n\n\n\n-- \nDarafei Praliaskouski\nSupport me: http://patreon.com/komzpa\n\n\n", "msg_date": "Sun, 5 Apr 2020 12:48:33 +0300", "msg_from": "=?UTF-8?Q?Darafei_=22Kom=D1=8Fpa=22_Praliaskouski?= <me@komzpa.net>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> On 29 Feb 2020, at 18:24, Andrey M. Borodin <x4mmm@yandex-team.ru> wrote:\n\n> I've fixed this and added patch with GiST reloption to provide sort support function.\n\n0002 in this patchset fails to apply, please submit a rebased version. I've\nmarked the entry Waiting for Author in the meantime.\n\ncheers ./daniel\n\n", "msg_date": "Wed, 1 Jul 2020 14:05:22 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "> 1 июля 2020 г., в 17:05, Daniel Gustafsson <daniel@yesql.se> написал(а):\n> \n>> On 29 Feb 2020, at 18:24, Andrey M. Borodin <x4mmm@yandex-team.ru> wrote:\n> \n>> I've fixed this and added patch with GiST reloption to provide sort support function.\n> \n> 0002 in this patchset fails to apply, please submit a rebased version. I've\n> marked the entry Waiting for Author in the meantime.\n\nThanks, Daniel!\n\nPFA v7.\n\nBest regards, Andrey Borodin.", "msg_date": "Mon, 6 Jul 2020 17:55:44 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "> 6 июля 2020 г., в 17:55, Andrey M. Borodin <x4mmm@yandex-team.ru> написал(а):\n> \n> \n> \n>> 1 июля 2020 г., в 17:05, Daniel Gustafsson <daniel@yesql.se> написал(а):\n>> \n>>> On 29 Feb 2020, at 18:24, Andrey M. Borodin <x4mmm@yandex-team.ru> wrote:\n>> \n>>> I've fixed this and added patch with GiST reloption to provide sort support function.\n>> \n>> 0002 in this patchset fails to apply, please submit a rebased version. I've\n>> marked the entry Waiting for Author in the meantime.\n> \n> Thanks, Daniel!\n> \n> PFA v7.\n\nOops. I've mismerged docs and did not notice this with check world. PFA v8 with fixed docs.\n\nBest regards, Andrey Borodin.", "msg_date": "Tue, 7 Jul 2020 12:03:20 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "On Tue, Jul 7, 2020 at 7:03 PM Andrey M. Borodin <x4mmm@yandex-team.ru> wrote:\n> Oops. I've mismerged docs and did not notice this with check world. PFA v8 with fixed docs.\n\nIt looks like point_zorder_internal() has the check for NaN in the wrong place.\n\n\n", "msg_date": "Fri, 10 Jul 2020 17:53:50 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "> 10 июля 2020 г., в 10:53, Thomas Munro <thomas.munro@gmail.com> написал(а):\n> \n> On Tue, Jul 7, 2020 at 7:03 PM Andrey M. Borodin <x4mmm@yandex-team.ru> wrote:\n>> Oops. I've mismerged docs and did not notice this with check world. PFA v8 with fixed docs.\n> \n> It looks like point_zorder_internal() has the check for NaN in the wrong place.\nThanks! Fixed.\n\nBest regards, Andrey Borodin.", "msg_date": "Fri, 10 Jul 2020 11:55:47 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "On Fri, Jul 10, 2020 at 6:55 PM Andrey M. Borodin <x4mmm@yandex-team.ru> wrote:\n> Thanks! Fixed.\n\nIt's not a bug, but I think those 64 bit constants should be wrapped\nin UINT64CONST(), following our convention.\n\nI'm confused about these two patches: 0001 introduces\ngist_point_fastcmp(), but then 0002 changes it to gist_bbox_fastcmp().\nMaybe you intended to keep both of them? Also 0002 seems to have\nfixups for 0001 squashed into it.\n\n\n", "msg_date": "Thu, 30 Jul 2020 13:26:42 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "> 30 июля 2020 г., в 06:26, Thomas Munro <thomas.munro@gmail.com> написал(а):\n> \n> On Fri, Jul 10, 2020 at 6:55 PM Andrey M. Borodin <x4mmm@yandex-team.ru> wrote:\n>> Thanks! Fixed.\n> \n> It's not a bug, but I think those 64 bit constants should be wrapped\n> in UINT64CONST(), following our convention.\nThanks, fixed!\n\n> I'm confused about these two patches: 0001 introduces\n> gist_point_fastcmp(), but then 0002 changes it to gist_bbox_fastcmp().\n> Maybe you intended to keep both of them? Also 0002 seems to have\n> fixups for 0001 squashed into it.\nIndeed, that were fixups: point converted to GiST representation is a bbox already, and the function expects only bboxes.\n\nAlso I've fixed some mismerges in documentation.\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Tue, 4 Aug 2020 22:28:22 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "I see this feature quite useful in concept and decided to test it.\n\nOn a real database of 7 million rows I observed speedup of 4 times in case\nof single column index on points only and 2.5 times speedup in case of\nindex on points with several included columns. Standard deviation between\nin series of measurements being of 10%. Index size saving was of 1.7-1.5\ntimes respectively. Points were in all four quadrants.\n\nOn random points same as query in the original message it was observer 3\ntimes speedup with the patch. Then I generated same points set but so they\nwill get into one quadrant didn't observe a difference with the previous\ncase. So probably anomaly in Morton curve not so big to induce noticeable\nslowdown in a whole random set. But as the ordering is done only for index\nand not used outside index it seems to me possible to introduce shifting\nfloating point coordinates respective to leftmost-bottom corner point and\nthus make all of them positive to avoid anomaly of Morton curve near\nquadrants transitions.\n\nOf course speed measurements depend on machine and configuration a lot, but\nI am sure anyway there is a noticeable difference in index build time and\nthis is quite valuable for end-user who build GiSt index on point type of\ndata. Furthermore same speedup is also for REBUILD INDEX CONCURRENTLY.\nThere short rebuild time also mean fewer user modified table rows during\nrebuild which should be integrated in a newer index after rebuild.\n\nThis patch can be also seen as a step to futher introduce the other\nordering algoritms e.g. Gilbert curve and I consider this feature is useful\nand is worth to be committed.\n\nBoth patches 0001 and 0002 when applied on version 14dev compile and work\ncleanly. Regression tests are passed.\nCode seems clean and legible for me.\n\nIn declaration I see little bit different style in similar argument\npointers/arrays:\nextern IndexTuple gistFormTuple(GISTSTATE *giststate, Relation r, Datum\n*attdata, bool *isnull, bool isleaf);\nextern IndexTuple gistCompressValusAndFormTuple(GISTSTATE *giststate,\nRelation r, Datum attdata[], bool isnull[], bool isleaf, Datum compatt[]);\nI suppose this is because gistFormTuple previously had different style in\ndeclaration and definition. Maybe it would be nice to change them to one\nstyle in all code, I propose pointers instead of [].\n\nIn a big comment\n/*\n+ * In this function we need to compute Morton codes for non-integral\n+ * components p->x and p->y. But Morton codes are defined only for\n+ * integral values.\ni don't quite caught meaning of \"non-integral\" and \"integral\" and propose\nto replace it to \"float\" and \"integers\".\n\nAlso there are some extra spaces before line\n\"prev_level_start = level_start;\"\nand after\n\"The argument is a pointer to a <structname>SortSupport</structname>\nstruct.\"\n\nOverall I see the patch useful and almost ready for commit.\n\nвт, 4 авг. 2020 г. в 21:28, Andrey M. Borodin <x4mmm@yandex-team.ru>:\n\n>\n>\n> > 30 июля 2020 г., в 06:26, Thomas Munro <thomas.munro@gmail.com>\n> написал(а):\n> >\n> > On Fri, Jul 10, 2020 at 6:55 PM Andrey M. Borodin <x4mmm@yandex-team.ru>\n> wrote:\n> >> Thanks! Fixed.\n> >\n> > It's not a bug, but I think those 64 bit constants should be wrapped\n> > in UINT64CONST(), following our convention.\n> Thanks, fixed!\n>\n> > I'm confused about these two patches: 0001 introduces\n> > gist_point_fastcmp(), but then 0002 changes it to gist_bbox_fastcmp().\n> > Maybe you intended to keep both of them? Also 0002 seems to have\n> > fixups for 0001 squashed into it.\n> Indeed, that were fixups: point converted to GiST representation is a bbox\n> already, and the function expects only bboxes.\n>\n> Also I've fixed some mismerges in documentation.\n>\n> Thanks!\n>\n> Best regards, Andrey Borodin.\n>\n>\n\n-- \nBest regards,\nPavel Borisov\n\nPostgres Professional: http://postgrespro.com <http://www.postgrespro.com>\n\nI see this feature quite useful in concept and decided to test it.On a real database of 7 million rows I observed speedup of 4 times in case of single column index on points only and 2.5 times speedup in case of index on points with several included columns. Standard deviation between in series of measurements being of 10%. Index size saving was of 1.7-1.5 times respectively. Points were in all four quadrants.On random points same as query in the original message it was observer 3 times speedup with the patch. Then I generated same points set but so they will get into one quadrant didn't observe a difference with the previous case. So probably anomaly in Morton curve not so big to induce noticeable slowdown in a whole random set. But as the ordering is done only for index and not used outside index it seems to me possible to introduce shifting floating point coordinates respective to leftmost-bottom corner point and thus make all of them positive to avoid anomaly of Morton curve near quadrants transitions.Of course speed measurements depend on machine and configuration a lot, but I am sure anyway there is a noticeable difference in index build time and this is quite valuable for end-user who build GiSt index on point type of data. Furthermore same speedup is also for REBUILD INDEX CONCURRENTLY. There short rebuild time also mean fewer user modified table rows during rebuild which should be integrated in a newer index after rebuild.This patch can be also seen as a step to futher introduce the other ordering algoritms e.g. Gilbert curve and I consider this feature is useful and is worth to be committed.Both patches 0001 and 0002 when applied on version 14dev compile and work cleanly. Regression tests are passed.Code seems clean and legible for me.In declaration I see little bit different style in similar argument pointers/arrays:extern IndexTuple gistFormTuple(GISTSTATE *giststate, Relation r, Datum *attdata, bool *isnull, bool isleaf);extern IndexTuple gistCompressValusAndFormTuple(GISTSTATE *giststate, Relation r, Datum attdata[], bool isnull[], bool isleaf, Datum compatt[]);I suppose this is because gistFormTuple previously had different style in declaration and definition. Maybe it would be nice to change them to one style in all code, I propose pointers instead of [].In a big comment /*+        * In this function we need to compute Morton codes for non-integral+        * components p->x and p->y. But Morton codes are defined only for+        * integral values.i don't quite caught meaning of \"non-integral\" and \"integral\" and propose to replace it to \"float\" and \"integers\".Also there are some extra spaces before line\"prev_level_start = level_start;\"and after\"The argument is a pointer to a <structname>SortSupport</structname> struct.\"        Overall I see the patch useful and almost ready for commit.вт, 4 авг. 2020 г. в 21:28, Andrey M. Borodin <x4mmm@yandex-team.ru>:\n\n> 30 июля 2020 г., в 06:26, Thomas Munro <thomas.munro@gmail.com> написал(а):\n> \n> On Fri, Jul 10, 2020 at 6:55 PM Andrey M. Borodin <x4mmm@yandex-team.ru> wrote:\n>> Thanks! Fixed.\n> \n> It's not a bug, but I think those 64 bit constants should be wrapped\n> in UINT64CONST(), following our convention.\nThanks, fixed!\n\n> I'm confused about these two patches: 0001 introduces\n> gist_point_fastcmp(), but then 0002 changes it to gist_bbox_fastcmp().\n> Maybe you intended to keep both of them?  Also 0002 seems to have\n> fixups for 0001 squashed into it.\nIndeed, that were fixups: point converted to GiST representation is a bbox already, and the function expects only bboxes.\n\nAlso I've fixed some mismerges in documentation.\n\nThanks!\n\nBest regards, Andrey Borodin.\n\n-- Best regards,Pavel BorisovPostgres Professional: http://postgrespro.com", "msg_date": "Fri, 14 Aug 2020 13:21:32 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "The following review has been posted through the commitfest application:\nmake installcheck-world: tested, passed\nImplements feature: tested, passed\nSpec compliant: not tested\nDocumentation: not tested\n\nI consider this patch almost ready for commit with minor corrections (see previous message)\n\nThe new status of this patch is: Waiting on Author\n", "msg_date": "Tue, 18 Aug 2020 15:57:33 +0000", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> 14 авг. 2020 г., в 14:21, Pavel Borisov <pashkin.elfe@gmail.com> написал(а):\n> \n> I see this feature quite useful in concept and decided to test it.\n\nThanks for reviewing and benchmarking, Pavel!\n\nI agree with your suggestions. PFA patch with relevant changes.\n\nThanks a lot.\n\nBest regards, Andrey Borodin.", "msg_date": "Sun, 23 Aug 2020 14:39:38 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "> 23 авг. 2020 г., в 14:39, Andrey M. Borodin <x4mmm@yandex-team.ru> написал(а):\n> \n> Thanks for reviewing and benchmarking, Pavel!\n\nPavel sent me few typos offlist. PFA v12 fixing these typos.\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Sun, 30 Aug 2020 17:04:46 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": ">\n> Pavel sent me few typos offlist. PFA v12 fixing these typos.\n> Thanks!\n>\n\nNow I consider the patch ready to be committed and mark it so on CF.\nThank you!\n\n-- \nBest regards,\nPavel Borisov\n\nPostgres Professional: http://postgrespro.com <http://www.postgrespro.com>\n\nPavel sent me few typos offlist. PFA v12 fixing these typos.\nThanks! Now I consider the patch ready to be committed and mark it so on CF. Thank you!-- Best regards,Pavel BorisovPostgres Professional: http://postgrespro.com", "msg_date": "Mon, 31 Aug 2020 16:02:22 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "On 30/08/2020 15:04, Andrey M. Borodin wrote:\n>> 23 авг. 2020 г., в 14:39, Andrey M. Borodin <x4mmm@yandex-team.ru> написал(а):\n>>\n>> Thanks for reviewing and benchmarking, Pavel!\n> \n> Pavel sent me few typos offlist. PFA v12 fixing these typos.\n\nIn gist_indexsortbuild(), you first build all the leaf pages. Then, you \nread through all the index pages you just built, to form the tuples for \nthe next level, and repeat for all the upper levels. That seems \ninefficient, it would be more better to form the tuples for the \ndownlinks as you go, when you build the leaf pages in the first place. \nThat's how nbtsort.c works. Also, you could WAL-log the pages as you go.\n\nIn gist_indexsortbuild_flush(), can't you just memcpy() the page from\nmemory to the buffer?\n\n- Heikki\n\n\n", "msg_date": "Thu, 3 Sep 2020 21:40:07 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "> 3 сент. 2020 г., в 23:40, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> On 30/08/2020 15:04, Andrey M. Borodin wrote:\n>>> 23 авг. 2020 г., в 14:39, Andrey M. Borodin <x4mmm@yandex-team.ru> написал(а):\n>>> \n>>> Thanks for reviewing and benchmarking, Pavel!\n>> Pavel sent me few typos offlist. PFA v12 fixing these typos.\n> \n> In gist_indexsortbuild(), you first build all the leaf pages. Then, you read through all the index pages you just built, to form the tuples for the next level, and repeat for all the upper levels. That seems inefficient, it would be more better to form the tuples for the downlinks as you go, when you build the leaf pages in the first place. That's how nbtsort.c works. Also, you could WAL-log the pages as you go.\n> \n> In gist_indexsortbuild_flush(), can't you just memcpy() the page from\n> memory to the buffer?\n> \n> - Heikki\nThanks for ideas, Heikki. Please see v13 with proposed changes.\nBut I've found out that logging page-by-page slows down GiST build by approximately 15% (when CPU constrained).\nThough In think that this is IO-wise.\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Sat, 5 Sep 2020 16:53:31 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "On 05/09/2020 14:53, Andrey M. Borodin wrote:\n> Thanks for ideas, Heikki. Please see v13 with proposed changes.\n\nThanks, that was quick!\n\n> But I've found out that logging page-by-page slows down GiST build by\n> approximately 15% (when CPU constrained). Though In think that this\n> is IO-wise.\nHmm, any ideas why that is? log_newpage_range() writes one WAL record \nfor 32 pages, while now you're writing one record per page, so you'll \nhave a little bit more overhead from that. But 15% seems like a lot.\n\n- Heikki\n\n\n", "msg_date": "Sun, 6 Sep 2020 16:26:08 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "> 6 сент. 2020 г., в 18:26, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> On 05/09/2020 14:53, Andrey M. Borodin wrote:\n>> Thanks for ideas, Heikki. Please see v13 with proposed changes.\n> \n> Thanks, that was quick!\n> \n>> But I've found out that logging page-by-page slows down GiST build by\n>> approximately 15% (when CPU constrained). Though In think that this\n>> is IO-wise.\n> Hmm, any ideas why that is? log_newpage_range() writes one WAL record for 32 pages, while now you're writing one record per page, so you'll have a little bit more overhead from that. But 15% seems like a lot.\nI do not know. I guess this can be some effect of pglz compression during cold stage. It can be slower and less compressive than pglz with cache table? But this is pointing into the sky.\nNevertheless, here's the patch identical to v13, but with 3rd part: log flushed pages with bunches of 32.\nThis brings CPU performance back and slightly better than before page-by-page logging.\n\nSome details about test:\nMacOS, 6-core i7\npsql -c '\\timing' -c \"create table x as select point (random(),random()) from generate_series(1,10000000,1);\" -c \"create index on x using gist (point);\"\n\nWith patch v13 this takes 20,567 seconds, with v14 18,149 seconds, v12 ~18,3s (which is closer to 10% btw, sorry for miscomputation). This was not statistically significant testing, just a quick laptop benchmark with 2-3 tests to verify stability.\n\nBest regards, Andrey Borodin.", "msg_date": "Sun, 6 Sep 2020 23:33:25 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "> 6 сент. 2020 г., в 18:26, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> On 05/09/2020 14:53, Andrey M. Borodin wrote:\n>> Thanks for ideas, Heikki. Please see v13 with proposed changes.\n> \n> Thanks, that was quick!\n> \n>> But I've found out that logging page-by-page slows down GiST build by\n>> approximately 15% (when CPU constrained). Though In think that this\n>> is IO-wise.\n> Hmm, any ideas why that is? log_newpage_range() writes one WAL record for 32 pages, while now you're writing one record per page, so you'll have a little bit more overhead from that. But 15% seems like a lot.\n\nHmm, this works for B-tree too.\nthis index creation\npsql -c '\\timing' -c \"create table x as select random() from generate_series(1,10000000,1);\" -c \"create index ON x (random );\"\ntakes 7 seconds on may machine, but with one weird patch it takes only 6 :)\n\nMaybe I'm missing something? Like forgot to log 10% of pages, or something like that...\n\nBest regards, Andrey Borodin.", "msg_date": "Mon, 7 Sep 2020 12:14:35 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "> 7 сент. 2020 г., в 12:14, Andrey M. Borodin <x4mmm@yandex-team.ru> написал(а):\n> \n> Maybe I'm missing something? Like forgot to log 10% of pages, or something like that...\n\nIndeed, there was a bug. I've fixed it, and I still observe same performance gain.\n\nBest regards, Andrey Borodin.", "msg_date": "Mon, 7 Sep 2020 13:36:46 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build (typo)" }, { "msg_contents": "On 24/02/2020 10:50, Andrey M. Borodin wrote:\n>> On 24 февр. 2020 г., at 01:58, Thomas Munro <thomas.munro@gmail.com> wrote:\n>>\n>> On Thu, Feb 20, 2020 at 10:14 AM Thomas Munro <thomas.munro@gmail.com> wrote:\n>>> 1. We expect floats to be in IEEE format, and the sort order of IEEE\n>>> floats is mostly correlated to the binary sort order of the bits\n>>> reinterpreted as an int. It isn't in some special cases, but for this\n>>> use case we don't really care about that, we're just trying to\n>>> encourage locality.\n>>\n>> I suppose there is a big jump in integer value (whether signed or\n>> unsigned) as you cross from positive to negative floats, and then the\n>> sort order is reversed. I have no idea if either of those things is a\n>> problem worth fixing. That made me wonder if there might also be an\n>> endianness problem. It seems from some quick googling that all\n>> current architectures have integers and floats of the same endianness.\n>> Apparently this wasn't always the case, and some ARMs have a weird\n>> half-flipped arrangement for 64 bit floats, but not 32 bit floats as\n>> you are using here.\n> \n> Yes, this leap is a problem for point as generic data type. And I do not know\n> how to fix it. It can cause inefficient Index Scans when searching near (0,0) and query\n> window touches simultaneously all quadrants (4x slower).\n\nI took a stab at fixing this, see attached patch (applies on top of your \npatch v14).\n\nTo evaluate this, I used the other attached patch to expose the zorder \nfunction to SQL, and plotted points around zero with gnuplot. See the \nattached two images, one with patch v14, and the other one with this patch.\n\nI'll continue looking at these patches in whole tomorrow. I think it's \ngetting close to a committable state.\n\n> But everything will be just fine when all data is in 2nd quadrant.\n\nSimon Riggs and friends would agree :-)\n\n- Heikki", "msg_date": "Mon, 7 Sep 2020 12:47:16 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": ">\n>\n> >> I suppose there is a big jump in integer value (whether signed or\n> >> unsigned) as you cross from positive to negative floats, and then the\n> >> sort order is reversed. I have no idea if either of those things is a\n> >> problem worth fixing. That made me wonder if there might also be an\n>\n> I took a stab at fixing this, see attached patch (applies on top of your\n> patch v14).\n>\n> To evaluate this, I used the other attached patch to expose the zorder\n> function to SQL, and plotted points around zero with gnuplot. See the\n> attached two images, one with patch v14, and the other one with this patch.\n>\n\nI'd made testing of sorted SpGist build in cases of points distributed only\nin 2d quadrant and points in all 4 quadrants and it appears that this\nabnormality doesn't affect as much as Andrey supposed. But Heikki's patch\nis really nice way to avoid what can be avoided and I'd like it is included\ntogether with Andrey's patch.\n\nPavel.\n\n>> I suppose there is a big jump in integer value (whether signed or\n>> unsigned) as you cross from positive to negative floats, and then the\n>> sort order is reversed.  I have no idea if either of those things is a\n>> problem worth fixing.  That made me wonder if there might also be an\nI took a stab at fixing this, see attached patch (applies on top of your \npatch v14).\n\nTo evaluate this, I used the other attached patch to expose the zorder \nfunction to SQL, and plotted points around zero with gnuplot. See the \nattached two images, one with patch v14, and the other one with this patch.I'd made testing of sorted SpGist build in cases of points distributed only in 2d quadrant and points in all 4 quadrants and it appears that this abnormality doesn't affect as much as Andrey supposed. But Heikki's patch is really nice way to avoid what can be avoided and I'd like it is included together with Andrey's patch.Pavel.", "msg_date": "Mon, 7 Sep 2020 14:59:30 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 07/09/2020 13:59, Pavel Borisov wrote:\n>>>> I suppose there is a big jump in integer value (whether signed or\n>>>> unsigned) as you cross from positive to negative floats, and then the\n>>>> sort order is reversed. I have no idea if either of those things is a\n>>>> problem worth fixing. That made me wonder if there might also be an\n>>\n>> I took a stab at fixing this, see attached patch (applies on top of your\n>> patch v14).\n>>\n>> To evaluate this, I used the other attached patch to expose the zorder\n>> function to SQL, and plotted points around zero with gnuplot. See the\n>> attached two images, one with patch v14, and the other one with this patch.\n> \n> I'd made testing of sorted SpGist build in cases of points distributed only\n> in 2d quadrant and points in all 4 quadrants and it appears that this\n> abnormality doesn't affect as much as Andrey supposed. But Heikki's patch\n> is really nice way to avoid what can be avoided and I'd like it is included\n> together with Andrey's patch.\n\nThanks! Did you measure the quality of the built index somehow? The \nordering shouldn't make any difference to the build speed, but it \naffects the shape of the resulting index and the speed of queries \nagainst it.\n\nI played with some simple queries like this:\n\nexplain (analyze, buffers) select count(*) from points_good where p <@ \nbox(point(50, 50), point(75, 75));\n\nand looking at the \"Buffers\" line for how many pages were accessed. \nThere doesn't seem to be any consistent difference between v14 and my \nfix. So I concur it doesn't seem to matter much.\n\n\nI played some more with plotting the curve. I wrote a little python \nprogram to make an animation of it, and also simulated how the points \nwould be divided into pages, assuming that each GiST page can hold 200 \ntuples (I think the real number is around 150 with default page size). \nIn the animation, the leaf pages appear as rectangles as it walks \nthrough the Z-order curve. This is just a simulation by splitting all \nthe points into batches of 200 and drawing a bounding box around each \nbatch. I haven't checked the actual pages as the GiST creates, but I \nthink this gives a good idea of how it works.\n\nThe animation shows that there's quite a lot of overlap between the \npages. It's not necessarily this patch's business to try to improve \nthat, and the non-sorting index build isn't perfect either. But it \noccurs to me that there's maybe one pretty simple trick we could do: \ninstead of blindly filling the leaf pages in Z-order, collect tuples \ninto a larger buffer, in Z-order. I'm thinking 32 pages worth of tuples, \nor something in that ballpark, or maybe go all the way up to work_mem. \nWhen the buffer fills up, call the picksplit code to divide the buffer \ninto the actual pages, and flush them to disk. If you look at the \nanimation and imagine that you would take a handful of pages in the \norder they're created, and re-divide the points with the split \nalgorithm, there would be much less overlap.\n\n- Heikki", "msg_date": "Mon, 7 Sep 2020 17:10:08 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 7 сент. 2020 г., в 19:10, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> On 07/09/2020 13:59, Pavel Borisov wrote:\n>>>>> I suppose there is a big jump in integer value (whether signed or\n>>>>> unsigned) as you cross from positive to negative floats, and then the\n>>>>> sort order is reversed. I have no idea if either of those things is a\n>>>>> problem worth fixing. That made me wonder if there might also be an\n>>> \n>>> I took a stab at fixing this, see attached patch (applies on top of your\n>>> patch v14).\n>>> \n>>> To evaluate this, I used the other attached patch to expose the zorder\n>>> function to SQL, and plotted points around zero with gnuplot. See the\n>>> attached two images, one with patch v14, and the other one with this patch.\n>> \n>> I'd made testing of sorted SpGist build in cases of points distributed only\n>> in 2d quadrant and points in all 4 quadrants and it appears that this\n>> abnormality doesn't affect as much as Andrey supposed. But Heikki's patch\n>> is really nice way to avoid what can be avoided and I'd like it is included\n>> together with Andrey's patch.\n> \n> Thanks! Did you measure the quality of the built index somehow? The \n> ordering shouldn't make any difference to the build speed, but it \n> affects the shape of the resulting index and the speed of queries \n> against it.\nI've tried to benchmark the difference between build time v14 and v15. v15 seems to be slightly slower, but with negligible difference.\n\n> I played with some simple queries like this:\n> \n> explain (analyze, buffers) select count(*) from points_good where p <@ \n> box(point(50, 50), point(75, 75));\nTo observe IndexScan difference query should touch 4 quadrants. i.e. search within ((-25,-25),point(25,25))\n\n> and looking at the \"Buffers\" line for how many pages were accessed. \n> There doesn't seem to be any consistent difference between v14 and my \n> fix. So I concur it doesn't seem to matter much.\n> \n> \n> I played some more with plotting the curve. I wrote a little python \n> program to make an animation of it, and also simulated how the points \n> would be divided into pages, assuming that each GiST page can hold 200 \n> tuples (I think the real number is around 150 with default page size). \n> In the animation, the leaf pages appear as rectangles as it walks \n> through the Z-order curve. This is just a simulation by splitting all \n> the points into batches of 200 and drawing a bounding box around each \n> batch. I haven't checked the actual pages as the GiST creates, but I \n> think this gives a good idea of how it works.\n> The animation shows that there's quite a lot of overlap between the \n> pages. It's not necessarily this patch's business to try to improve \n> that, and the non-sorting index build isn't perfect either. But it \n> occurs to me that there's maybe one pretty simple trick we could do: \n> instead of blindly filling the leaf pages in Z-order, collect tuples \n> into a larger buffer, in Z-order. I'm thinking 32 pages worth of tuples, \n> or something in that ballpark, or maybe go all the way up to work_mem. \n> When the buffer fills up, call the picksplit code to divide the buffer \n> into the actual pages, and flush them to disk. If you look at the \n> animation and imagine that you would take a handful of pages in the \n> order they're created, and re-divide the points with the split \n> algorithm, there would be much less overlap.\n\nAnimation looks cool! It really pins the inefficiency of resulting MBRs.\nBut in R*-tree one of Beckman's points was that overlap optimisation worth doing on higher levels, not lower.\nBut we can do this for splits on each level, I think. We do not know tree depth in advance to divide maintenance workmem among level.. But, probably we don't need to, let's allocate half to first level, quarter to second, 1/8 to third etc until it's one page. Should we take allocations inside picksplit() into account?\nThe more I think about it the cooler idea seem to me.\n\nBTW I've found one more bug in the patch: it writes WAL even for unlogged tables. I'm not sending a patch because changes are trivial and currently we already have lengthy patchset in different messages.\nAlso, to avoid critical section we can use log_new_page() instead of log_buffer().\n\n\nThanks!\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Mon, 7 Sep 2020 20:24:18 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": ">\n> > Thanks! Did you measure the quality of the built index somehow? The\n> > ordering shouldn't make any difference to the build speed, but it\n> > affects the shape of the resulting index and the speed of queries\n> > against it.\n\n\nAgain I've tried random select tests near axes and haven't noticed any\nperformance difference between ordinary gist build and z-ordered one. The\nsame is for selects far from axes. Theoretically, there may be a possible\nslowdown for particular points inside the MBR which crosses the axis but I\nhaven't tried to dig so deep and haven't tested performance as a function\nof coordinate.\n\nSo I feel this patch is not about select speed optimization.\n\n-- \nBest regards,\nPavel Borisov\n\nPostgres Professional: http://postgrespro.com <http://www.postgrespro.com>\n\n> Thanks! Did you measure the quality of the built index somehow? The \n> ordering shouldn't make any difference to the build speed, but it \n> affects the shape of the resulting index and the speed of queries \n> against it. Again I've tried random select tests near axes and haven't noticed any performance difference between ordinary gist build and z-ordered one. The same is for selects far from axes. Theoretically, there may be a possible slowdown for particular points inside the MBR which crosses the axis but I haven't tried to dig so deep and haven't tested performance as a function of coordinate.So I feel this patch is not about select speed optimization.-- Best regards,Pavel BorisovPostgres Professional: http://postgrespro.com", "msg_date": "Tue, 8 Sep 2020 22:33:59 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 08/09/2020 21:33, Pavel Borisov wrote:\n> > Thanks! Did you measure the quality of the built index somehow? The\n> > ordering shouldn't make any difference to the build speed, but it\n> > affects the shape of the resulting index and the speed of queries\n> > against it.\n> \n> Again I've tried random select tests near axes and haven't noticed any \n> performance difference between ordinary gist build and z-ordered one. \n> The same is for selects far from axes. Theoretically, there may be a \n> possible slowdown for particular points inside the MBR which crosses the \n> axis but I haven't tried to dig so deep and haven't tested performance \n> as a function of coordinate.\n> \n> So I feel this patch is not about select speed optimization.\n\nOk, thank for confirming.\n\nI've been reviewing the patch today. The biggest changes I've made have \nbeen in restructuring the code in gistbuild.c for readability, but there \nare a bunch of smaller changes throughout. Attached is what I've got so \nfar, squashed into one patch. I'm continuing to review it, but a couple \nof questions so far:\n\nIn the gistBuildCallback(), you're skipping the tuple if 'tupleIsAlive \n== false'. That seems fishy, surely we need to index recently-dead \ntuples, too. The normal index build path isn't skipping them either.\n\nHow does the 'sortsupport' routine interact with \n'compress'/'decompress'? Which representation is passed to the \ncomparator routine: the original value from the table, the compressed \nrepresentation, or the decompressed representation? Do the \ncomparetup_index_btree() and readtup_index() routines agree with that?\n\n- Heikki", "msg_date": "Tue, 8 Sep 2020 22:05:37 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 9 сент. 2020 г., в 00:05, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> I've been reviewing the patch today. The biggest changes I've made have been in restructuring the code in gistbuild.c for readability, but there are a bunch of smaller changes throughout. Attached is what I've got so far, squashed into one patch.\nThanks!\n\n> I'm continuing to review it, but a couple of questions so far:\n> \n> In the gistBuildCallback(), you're skipping the tuple if 'tupleIsAlive == false'. That seems fishy, surely we need to index recently-dead tuples, too. The normal index build path isn't skipping them either.\nThat's an oversight.\n> \n> How does the 'sortsupport' routine interact with 'compress'/'decompress'? Which representation is passed to the comparator routine: the original value from the table, the compressed representation, or the decompressed representation? Do the comparetup_index_btree() and readtup_index() routines agree with that?\n\nCurrently we pass compressed values, which seems not very good.\nBut there was a request from PostGIS maintainers to pass values before decompression.\nDarafei, please, correct me if I'm wrong. Also can you please provide link on PostGIS B-tree sorting functions?\n\nThanks!\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Wed, 9 Sep 2020 11:43:40 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Hi,\n\n\nOn Wed, Sep 9, 2020 at 9:43 AM Andrey M. Borodin <x4mmm@yandex-team.ru>\nwrote:\n\n>\n>\n> > 9 сент. 2020 г., в 00:05, Heikki Linnakangas <hlinnaka@iki.fi>\n> написал(а):\n> >\n> > I've been reviewing the patch today. The biggest changes I've made have\n> been in restructuring the code in gistbuild.c for readability, but there\n> are a bunch of smaller changes throughout. Attached is what I've got so\n> far, squashed into one patch.\n> Thanks!\n>\n> > I'm continuing to review it, but a couple of questions so far:\n> >\n> > In the gistBuildCallback(), you're skipping the tuple if 'tupleIsAlive\n> == false'. That seems fishy, surely we need to index recently-dead tuples,\n> too. The normal index build path isn't skipping them either.\n> That's an oversight.\n> >\n> > How does the 'sortsupport' routine interact with\n> 'compress'/'decompress'? Which representation is passed to the comparator\n> routine: the original value from the table, the compressed representation,\n> or the decompressed representation? Do the comparetup_index_btree() and\n> readtup_index() routines agree with that?\n>\n> Currently we pass compressed values, which seems not very good.\n> But there was a request from PostGIS maintainers to pass values before\n> decompression.\n> Darafei, please, correct me if I'm wrong. Also can you please provide link\n> on PostGIS B-tree sorting functions?\n>\n\nWe were expecting to reuse btree opclass for this thing. This way\nbtree_gist extension will become a lot thinner. :)\n\nCore routine for current sorting implementation is Hilbert curve, which is\nbased on 2D center of a box - and used for abbreviated sort:\nhttps://github.com/postgis/postgis/blob/2a7ebd0111b02aed3aa24752aad0ba89aef5d431/liblwgeom/gbox.c#L893\n\n\nAll the btree functions are wrappers around gserialized_cmp which just adds\na bunch of tiebreakers that don't matter in practice:\nhttps://github.com/postgis/postgis/blob/2a7ebd0111b02aed3aa24752aad0ba89aef5d431/liblwgeom/gserialized.c#L313\n\nBase representation for index compressed datatype is GIDX, which is also a\nbox. We can make it work on top of it instead of the original\nrepresentation.\nThere is no such thing as \"decompressed representation\" unfortunately as\ncompression is lossy.\n\nHi,On Wed, Sep 9, 2020 at 9:43 AM Andrey M. Borodin <x4mmm@yandex-team.ru> wrote:\n\n> 9 сент. 2020 г., в 00:05, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> I've been reviewing the patch today. The biggest changes I've made have been in restructuring the code in gistbuild.c for readability, but there are a bunch of smaller changes throughout. Attached is what I've got so far, squashed into one patch.\nThanks!\n\n> I'm continuing to review it, but a couple of questions so far:\n> \n> In the gistBuildCallback(), you're skipping the tuple if 'tupleIsAlive == false'. That seems fishy, surely we need to index recently-dead tuples, too. The normal index build path isn't skipping them either.\nThat's an oversight.\n> \n> How does the 'sortsupport' routine interact with 'compress'/'decompress'? Which representation is passed to the comparator routine: the original value from the table, the compressed representation, or the decompressed representation? Do the comparetup_index_btree() and readtup_index() routines agree with that?\n\nCurrently we pass compressed values, which seems not very good.\nBut there was a request from PostGIS maintainers to pass values before decompression.\nDarafei, please, correct me if I'm wrong. Also can you please provide link on PostGIS B-tree sorting functions?We were expecting to reuse btree opclass for this thing. This way btree_gist extension will become a lot thinner. :)Core routine for current sorting implementation is Hilbert curve, which is based on 2D center of a box - and used for abbreviated sort:https://github.com/postgis/postgis/blob/2a7ebd0111b02aed3aa24752aad0ba89aef5d431/liblwgeom/gbox.c#L893 All the btree functions are wrappers around gserialized_cmp which just adds a bunch of tiebreakers that don't matter in practice:https://github.com/postgis/postgis/blob/2a7ebd0111b02aed3aa24752aad0ba89aef5d431/liblwgeom/gserialized.c#L313Base representation for index compressed datatype is GIDX, which is also a box. We can make it work on top of it instead of the original representation.There is no such thing as \"decompressed representation\" unfortunately as compression is lossy.", "msg_date": "Wed, 9 Sep 2020 10:05:04 +0300", "msg_from": "=?UTF-8?Q?Darafei_=22Kom=D1=8Fpa=22_Praliaskouski?= <me@komzpa.net>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Thanks Darafei!\n\n> 9 сент. 2020 г., в 12:05, Darafei Komяpa Praliaskouski <me@komzpa.net> написал(а):\n> \n> > How does the 'sortsupport' routine interact with 'compress'/'decompress'? Which representation is passed to the comparator routine: the original value from the table, the compressed representation, or the decompressed representation? Do the comparetup_index_btree() and readtup_index() routines agree with that?\n> \n> Currently we pass compressed values, which seems not very good.\n> But there was a request from PostGIS maintainers to pass values before decompression.\n> Darafei, please, correct me if I'm wrong. Also can you please provide link on PostGIS B-tree sorting functions?\n> \n> We were expecting to reuse btree opclass for this thing. This way btree_gist extension will become a lot thinner. :)\n\nI think if we aim at reusing B-tree sort support functions we have to pass uncompressed values. They can be a lot bigger and slower in case of PostGIS. We will be sorting actual geometries instead of MBRs.\n\nIn my view it's better to implement GiST-specific sort support in btree_gist, rather than trying to reuse existing sort supports.\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Wed, 9 Sep 2020 15:28:43 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 09/09/2020 13:28, Andrey M. Borodin wrote:\n> Thanks Darafei!\n> \n>> 9 сент. 2020 г., в 12:05, Darafei Komяpa Praliaskouski\n>> <me@komzpa.net> написал(а):\n>> \n>>> How does the 'sortsupport' routine interact with\n>>> 'compress'/'decompress'? Which representation is passed to the\n>>> comparator routine: the original value from the table, the\n>>> compressed representation, or the decompressed representation? Do\n>>> the comparetup_index_btree() and readtup_index() routines agree\n>>> with that?\n>> \n>> Currently we pass compressed values, which seems not very good. But\n>> there was a request from PostGIS maintainers to pass values before\n>> decompression. Darafei, please, correct me if I'm wrong. Also can\n>> you please provide link on PostGIS B-tree sorting functions?\n>> \n>> We were expecting to reuse btree opclass for this thing. This way\n>> btree_gist extension will become a lot thinner. :)\n> \n> I think if we aim at reusing B-tree sort support functions we have to\n> pass uncompressed values. They can be a lot bigger and slower in case\n> of PostGIS. We will be sorting actual geometries instead of MBRs.\n> \n> In my view it's better to implement GiST-specific sort support in\n> btree_gist, rather than trying to reuse existing sort supports.\n\nYeah, I don't think reusing existing sortsupport functions directly is \nimportant. The comparison function should be short anyway for \nperformance reasons, so it won't be a lot of code to copy-paste. And if \nthere are some common subroutines, you can put them in a separate \ninternal functions for reuse.\n\nUsing the 'compressed' format seems reasonable to me. It's natural to \nthe gistbuild.c code, and the comparison routine can 'decompress' itself \nif it wishes. If the decompressions is somewhat expensive, it's \nunfortunate if you need to do it repeatedly in the comparator, but \ntuplesort.c would need pretty big changes to keep around a separate \nin-memory representation compare. However, you could use the sort \n\"abbreviation\" functionality to mitigate that.\n\nCome to think of it, the point z-order comparator could benefit a lot \nfrom key abbreviation, too. You could do the point -> zorder conversion \nin the abbreviation routine.\n\n- Heikki\n\n\n", "msg_date": "Wed, 9 Sep 2020 15:09:16 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Wed, Sep 9, 2020 at 3:09 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n\n> On 09/09/2020 13:28, Andrey M. Borodin wrote:\n> > Thanks Darafei!\n> >\n> >> 9 сент. 2020 г., в 12:05, Darafei Komяpa Praliaskouski\n> >> <me@komzpa.net> написал(а):\n> >>\n> >>> How does the 'sortsupport' routine interact with\n> >>> 'compress'/'decompress'? Which representation is passed to the\n> >>> comparator routine: the original value from the table, the\n> >>> compressed representation, or the decompressed representation? Do\n> >>> the comparetup_index_btree() and readtup_index() routines agree\n> >>> with that?\n> >>\n> ....\n>\n> Come to think of it, the point z-order comparator could benefit a lot\n> from key abbreviation, too. You could do the point -> zorder conversion\n> in the abbreviation routine.\n>\n\nThat's how it works in PostGIS, only that we moved to more\neffecient Hilbert curve:\nhttps://github.com/postgis/postgis/blob/54399b9f6b0f02e8db9444f9f042b8d4ca6d4fa4/postgis/lwgeom_btree.c#L171\n\nOn Wed, Sep 9, 2020 at 3:09 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:On 09/09/2020 13:28, Andrey M. Borodin wrote:\n> Thanks Darafei!\n> \n>> 9 сент. 2020 г., в 12:05, Darafei Komяpa Praliaskouski\n>> <me@komzpa.net> написал(а):\n>> \n>>> How does the 'sortsupport' routine interact with\n>>> 'compress'/'decompress'? Which representation is passed to the\n>>> comparator routine: the original value from the table, the\n>>> compressed representation, or the decompressed representation? Do\n>>> the comparetup_index_btree() and readtup_index() routines agree\n>>> with that?\n>> ....\n\nCome to think of it, the point z-order comparator could benefit a lot \nfrom key abbreviation, too. You could do the point -> zorder conversion \nin the abbreviation routine.That's how it works in PostGIS, only that we moved to more effecient Hilbert curve:https://github.com/postgis/postgis/blob/54399b9f6b0f02e8db9444f9f042b8d4ca6d4fa4/postgis/lwgeom_btree.c#L171", "msg_date": "Wed, 9 Sep 2020 15:20:43 +0300", "msg_from": "=?UTF-8?Q?Darafei_=22Kom=D1=8Fpa=22_Praliaskouski?= <me@komzpa.net>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 09/09/2020 15:20, Darafei \"Komяpa\" Praliaskouski wrote:\n> On Wed, Sep 9, 2020 at 3:09 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> \n>> Come to think of it, the point z-order comparator could benefit a lot\n>> from key abbreviation, too. You could do the point -> zorder conversion\n>> in the abbreviation routine.\n> \n> That's how it works in PostGIS, only that we moved to more\n> effecient Hilbert curve:\n> https://github.com/postgis/postgis/blob/54399b9f6b0f02e8db9444f9f042b8d4ca6d4fa4/postgis/lwgeom_btree.c#L171\n\nThanks, that's interesting.\n\nI implemented the abbreviated keys for the point opclass, too, and \nnoticed that the patch as it was never used it. I reworked the patch so \nthat tuplesort_begin_index_gist() is responsible for looking up the \nsortsupport function, like tuplesort_begin_index_btree() does, and uses \nabbreviation when possible.\n\nI think this is pretty much ready for commit now. I'll do a bit more \ntesting (do we have regression test coverage for this?), also on a \nSIZEOF_DATUM==4 system since the abbreviation works differently with \nthat, and push if nothing new comes up. And clarify the documentation \nand/or comments that the sortsupport function sees \"compressed\" values.\n\nI wonder if we could use sorting to also speed up building tsvector \nindexes? The values stored there are bit signatures, what would be a \ngood sort order for those?\n\n- Heikki\n\n\n", "msg_date": "Wed, 9 Sep 2020 18:39:21 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 09/09/2020 15:20, Darafei \"Komяpa\" Praliaskouski wrote:\n> On Wed, Sep 9, 2020 at 3:09 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> \n>> Come to think of it, the point z-order comparator could benefit a lot\n>> from key abbreviation, too. You could do the point -> zorder conversion\n>> in the abbreviation routine.\n> \n> That's how it works in PostGIS, only that we moved to more\n> effecient Hilbert curve:\n> https://github.com/postgis/postgis/blob/54399b9f6b0f02e8db9444f9f042b8d4ca6d4fa4/postgis/lwgeom_btree.c#L171\n\nThanks, that's interesting.\n\nI implemented the abbreviated keys for the point opclass, too, and \nnoticed that the patch as it was never used it. I reworked the patch so \nthat tuplesort_begin_index_gist() is responsible for looking up the \nsortsupport function, like tuplesort_begin_index_btree() does, and uses \nabbreviation when possible.\n\nI think this is pretty much ready for commit now. I'll do a bit more \ntesting (do we have regression test coverage for this?), also on a \nSIZEOF_DATUM==4 system since the abbreviation works differently with \nthat, and push if nothing new comes up. And clarify the documentation \nand/or comments that the sortsupport function sees \"compressed\" values.\n\nI wonder if we could use sorting to also speed up building tsvector \nindexes? The values stored there are bit signatures, what would be a \ngood sort order for those?\n\n- Heikki", "msg_date": "Wed, 9 Sep 2020 18:39:41 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 9 сент. 2020 г., в 20:39, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> On 09/09/2020 15:20, Darafei \"Komяpa\" Praliaskouski wrote:\n>> On Wed, Sep 9, 2020 at 3:09 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>>> Come to think of it, the point z-order comparator could benefit a lot\n>>> from key abbreviation, too. You could do the point -> zorder conversion\n>>> in the abbreviation routine.\n>> That's how it works in PostGIS, only that we moved to more\n>> effecient Hilbert curve:\n>> https://github.com/postgis/postgis/blob/54399b9f6b0f02e8db9444f9f042b8d4ca6d4fa4/postgis/lwgeom_btree.c#L171\n> \n> Thanks, that's interesting.\n> \n> I implemented the abbreviated keys for the point opclass, too, and noticed that the patch as it was never used it. I reworked the patch so that tuplesort_begin_index_gist() is responsible for looking up the sortsupport function, like tuplesort_begin_index_btree() does, and uses abbreviation when possible.\nWow, abbreviated sort made gist for points construction even 1.5x faster!\nbtw there is small typo in arg names in gist_bbox_zorder_cmp_abbrev(); z1,z2 -> a,b\n\n> do we have regression test coverage for this?\nYes, sorting build for points is tested in point.sql, but with small dataset. index_including_gist.sql seems to be working with boxes, but triggers point paths too.\n\n> , also on a SIZEOF_DATUM==4 system since the abbreviation works differently with that, and push if nothing new comes up. And clarify the documentation and/or comments that the sortsupport function sees \"compressed\" values.\n> \n> I wonder if we could use sorting to also speed up building tsvector indexes? The values stored there are bit signatures, what would be a good sort order for those?\nWe need an order so that nearby values have a lot of bits in common.\nWhat is the length of this signature?\nFor each 4 bytes we can compute number of 1s in it's binary representation. Then z-order these dwords as values 0-32.\n\nThis will be very inefficient grouping, but it will tend to keep empty and dense 4-byte regions apart.\n\nThanks for working on this!\n\n\nBest regards, Andrey Borodin.\n\n\n", "msg_date": "Wed, 9 Sep 2020 21:50:44 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Mon, Sep 7, 2020 at 7:50 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> On 07/09/2020 13:59, Pavel Borisov wrote:\n> >>>> I suppose there is a big jump in integer value (whether signed or\n> >>>> unsigned) as you cross from positive to negative floats, and then the\n> >>>> sort order is reversed. I have no idea if either of those things is a\n> >>>> problem worth fixing. That made me wonder if there might also be an\n> >>\n> >> I took a stab at fixing this, see attached patch (applies on top of your\n> >> patch v14).\n> >>\n> >> To evaluate this, I used the other attached patch to expose the zorder\n> >> function to SQL, and plotted points around zero with gnuplot. See the\n> >> attached two images, one with patch v14, and the other one with this patch.\n> >\n> > I'd made testing of sorted SpGist build in cases of points distributed only\n> > in 2d quadrant and points in all 4 quadrants and it appears that this\n> > abnormality doesn't affect as much as Andrey supposed. But Heikki's patch\n> > is really nice way to avoid what can be avoided and I'd like it is included\n> > together with Andrey's patch.\n>\n> Thanks! Did you measure the quality of the built index somehow? The\n> ordering shouldn't make any difference to the build speed, but it\n> affects the shape of the resulting index and the speed of queries\n> against it.\n>\n> I played with some simple queries like this:\n>\n> explain (analyze, buffers) select count(*) from points_good where p <@\n> box(point(50, 50), point(75, 75));\n>\n> and looking at the \"Buffers\" line for how many pages were accessed.\n> There doesn't seem to be any consistent difference between v14 and my\n> fix. So I concur it doesn't seem to matter much.\n>\n>\n> I played some more with plotting the curve. I wrote a little python\n> program to make an animation of it, and also simulated how the points\n> would be divided into pages, assuming that each GiST page can hold 200\n> tuples (I think the real number is around 150 with default page size).\n> In the animation, the leaf pages appear as rectangles as it walks\n> through the Z-order curve. This is just a simulation by splitting all\n> the points into batches of 200 and drawing a bounding box around each\n> batch. I haven't checked the actual pages as the GiST creates, but I\n> think this gives a good idea of how it works.\n\nHeikki, you may use our gevel extension to visualize index tree\nhttp://www.sai.msu.su/~megera/wiki/Gevel\nI used it to investigate rtree index\nhttp://www.sai.msu.su/~megera/wiki/Rtree_Index\n\n\n>\n> The animation shows that there's quite a lot of overlap between the\n> pages. It's not necessarily this patch's business to try to improve\n> that, and the non-sorting index build isn't perfect either. But it\n> occurs to me that there's maybe one pretty simple trick we could do:\n> instead of blindly filling the leaf pages in Z-order, collect tuples\n> into a larger buffer, in Z-order. I'm thinking 32 pages worth of tuples,\n> or something in that ballpark, or maybe go all the way up to work_mem.\n> When the buffer fills up, call the picksplit code to divide the buffer\n> into the actual pages, and flush them to disk. If you look at the\n> animation and imagine that you would take a handful of pages in the\n> order they're created, and re-divide the points with the split\n> algorithm, there would be much less overlap.\n\nInteresting to see also the size of index, it should be several times less.\n\n>\n> - Heikki\n\n\n\n-- \nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Thu, 10 Sep 2020 13:21:09 +0300", "msg_from": "Oleg Bartunov <obartunov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": ">\n> Interesting to see also the size of index, it should be several times less.\n>\n> I've tested this above in CF thread and got ordered GiST index ~1.7 times\nsmaller than non-ordered one for single column of real points.\n\n\n-- \nBest regards,\nPavel Borisov\n\nPostgres Professional: http://postgrespro.com <http://www.postgrespro.com>\n\nInteresting to see also the size of index, it should be several times less.I've tested this above in CF thread and got ordered GiST index ~1.7 times smaller than non-ordered one for single column of real points.-- Best regards,Pavel BorisovPostgres Professional: http://postgrespro.com", "msg_date": "Thu, 10 Sep 2020 15:19:10 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 09/09/2020 19:50, Andrey M. Borodin wrote:\n>> 9 сент. 2020 г., в 20:39, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n>>\n>> On 09/09/2020 15:20, Darafei \"Komяpa\" Praliaskouski wrote:\n>>> On Wed, Sep 9, 2020 at 3:09 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>>>> Come to think of it, the point z-order comparator could benefit a lot\n>>>> from key abbreviation, too. You could do the point -> zorder conversion\n>>>> in the abbreviation routine.\n>>> That's how it works in PostGIS, only that we moved to more\n>>> effecient Hilbert curve:\n>>> https://github.com/postgis/postgis/blob/54399b9f6b0f02e8db9444f9f042b8d4ca6d4fa4/postgis/lwgeom_btree.c#L171\n>>\n>> Thanks, that's interesting.\n>>\n>> I implemented the abbreviated keys for the point opclass, too, and noticed that the patch as it was never used it. I reworked the patch so that tuplesort_begin_index_gist() is responsible for looking up the sortsupport function, like tuplesort_begin_index_btree() does, and uses abbreviation when possible.\n> Wow, abbreviated sort made gist for points construction even 1.5x faster!\n> btw there is small typo in arg names in gist_bbox_zorder_cmp_abbrev(); z1,z2 -> a,b\n\nOne more patch version attached. I fixed some memory leaks, and fixed \nthe abbreviation on 32-bit systems, and a bunch of small comment changes \nand such.\n\n- Heikki", "msg_date": "Thu, 10 Sep 2020 15:43:11 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 10 сент. 2020 г., в 17:43, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> One more patch version attached. I fixed some memory leaks, and fixed the abbreviation on 32-bit systems, and a bunch of small comment changes and such.\n> \n> - Heikki\n> <v18-0001-Add-support-for-building-GiST-index-by-sorting.patch>\n\nThe patch looks fine to me. On my machine GiST for points is builded 10x faster than before the patch.\n\nFuture action items:\n1. Sort support for gist_btree data types\n2. Better page borders with split and fillfactor\n3. Consider sort build for tsvector\n\nI'll certainly do 1 before next CF and most probably 2.\nItem 1 is basically a lot of similar code for many many different types.\nIn Item 2 I plan to use Oleg's gevel to evaluation possibilities of MBR overlap reduction.\n\nItem 3 seems tricky and need deeper evaluation: chances are sort build will decrease IndexScan performance in this case.\n\nThanks, Heikki!\n\nBest regards, Andrey Borodin,\n\n", "msg_date": "Fri, 11 Sep 2020 11:02:06 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 11/09/2020 09:02, Andrey M. Borodin wrote:\n>> 10 сент. 2020 г., в 17:43, Heikki Linnakangas <hlinnaka@iki.fi>\n>> написал(а):\n>> \n>> One more patch version attached. I fixed some memory leaks, and\n>> fixed the abbreviation on 32-bit systems, and a bunch of small\n>> comment changes and such.\n>> \n>> <v18-0001-Add-support-for-building-GiST-index-by-sorting.patch>\n> \n> The patch looks fine to me. On my machine GiST for points is builded\n> 10x faster than before the patch.\n\nAnother patch version, fixed a few small bugs pointed out by assertion \nfailures in the regression tests.\n\n- Heikki", "msg_date": "Tue, 15 Sep 2020 14:36:15 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 15 сент. 2020 г., в 16:36, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> Another patch version, fixed a few small bugs pointed out by assertion failures in the regression tests.\n> \n> - Heikki\n> <v19-0001-Add-support-for-building-GiST-index-by-sorting.patch>\n\nThese changes in create_index.out do not seem correct to me\n\n SELECT * FROM point_tbl ORDER BY f1 <-> '0,1';\n f1 \n -------------------\n- (0,0)\n (1e-300,-1e-300)\n+ (0,0)\n\nI did not figure out the root cause yet. We do not touch anything related to distance computation..\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Tue, 15 Sep 2020 21:46:11 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 15/09/2020 19:46, Andrey M. Borodin wrote:\n> \n> \n>> 15 сент. 2020 г., в 16:36, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n>>\n>> Another patch version, fixed a few small bugs pointed out by assertion failures in the regression tests.\n>>\n>> - Heikki\n>> <v19-0001-Add-support-for-building-GiST-index-by-sorting.patch>\n> \n> These changes in create_index.out do not seem correct to me\n> \n> SELECT * FROM point_tbl ORDER BY f1 <-> '0,1';\n> f1\n> -------------------\n> - (0,0)\n> (1e-300,-1e-300)\n> + (0,0)\n> \n> I did not figure out the root cause yet. We do not touch anything related to distance computation..\n\nAh yeah, that's subtle. Those rows are considered to be equally distant \nfrom (0, 1), given the precision of the <-> operator:\n\nregression=# SELECT f1, f1 <-> '0,1' FROM point_tbl ORDER BY f1 <-> '0,1';\n f1 | ?column?\n-------------------+------------------\n (0,0) | 1\n (1e-300,-1e-300) | 1\n (-3,4) | 4.24264068711929\n (-10,0) | 10.0498756211209\n (10,10) | 13.4536240470737\n (-5,-12) | 13.9283882771841\n (5.1,34.5) | 33.885985303662\n (1e+300,Infinity) | Infinity\n (NaN,NaN) | NaN\n |\n(10 rows)\n\nIt is arbitrary which one you get first.\n\nIt's not very nice to have a not-well defined order of rows in the \nexpected output, as it could change in the future if we change the index \nbuild algorithm again. But we have plenty of cases that depend on the \nphysical row order, and it's not like this changes very often, so I \nthink it's ok to just memorize the new order in the expected output.\n\n- Heikki\n\n\n", "msg_date": "Tue, 15 Sep 2020 20:07:38 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 15 сент. 2020 г., в 22:07, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> regression=# SELECT f1, f1 <-> '0,1' FROM point_tbl ORDER BY f1 <-> '0,1';\n> f1 | ?column?\n> -------------------+------------------\n> (0,0) | 1\n> (1e-300,-1e-300) | 1\n> (-3,4) | 4.24264068711929\n> (-10,0) | 10.0498756211209\n> (10,10) | 13.4536240470737\n> (-5,-12) | 13.9283882771841\n> (5.1,34.5) | 33.885985303662\n> (1e+300,Infinity) | Infinity\n> (NaN,NaN) | NaN\n> |\n> (10 rows)\n> \n> It is arbitrary which one you get first.\n> \n> It's not very nice to have a not-well defined order of rows in the expected output, as it could change in the future if we change the index build algorithm again. But we have plenty of cases that depend on the physical row order, and it's not like this changes very often, so I think it's ok to just memorize the new order in the expected output.\n\n\nI think this is valid reasoning. GiST choose subtree algorithm is not deterministic, it calls random(), but not in tested paths. \nI was thinking that machine epsilon is near 1e-300, but I was wrong. It's actually near 1e-15.\n\nActually, I just want to understand what changes between v18 and v19 changed on-page order of items. I look into patch diff and cannot figure it out. There are only logging changes. How this affects scan?\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Wed, 16 Sep 2020 12:27:09 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 16/09/2020 10:27, Andrey M. Borodin wrote:\n> Actually, I just want to understand what changes between v18 and v19\n> changed on-page order of items. I look into patch diff and cannot\n> figure it out. There are only logging changes. How this affects\n> scan?\n\nThe test was failing with v18 too.\n\n- Heikki\n\n\n", "msg_date": "Wed, 16 Sep 2020 11:20:48 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "At Wed, 16 Sep 2020 12:27:09 +0500, \"Andrey M. Borodin\" <x4mmm@yandex-team.ru> wrote in \n> I was thinking that machine epsilon is near 1e-300, but I was\n> wrong. It's actually near 1e-15.\n\nFWIW, the mantissa of double is effectively 52+1 bits, about 15.9\ndigits. so 1+(1e-16) is basically indistincitve from\n1+(2e-16). Actually two double precisions 1+2e-16 and 1+3e-16 are\nindistinctive from each other.\n\n> Actually, I just want to understand what changes between v18 and v19 changed on-page order of items. I look into patch diff and cannot figure it out. There are only logging changes. How this affects scan?\n\nFWIW, I saw the same symptom by my another patch after adding a value\nto POINT_TBL. (But I didn't pursue the cause further..)\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Wed, 16 Sep 2020 18:09:03 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 15/09/2020 14:36, Heikki Linnakangas wrote:\n> Another patch version, fixed a few small bugs pointed out by assertion\n> failures in the regression tests.\n\nPushed. Thanks everyone!\n\n- Heikki\n\n\n", "msg_date": "Thu, 17 Sep 2020 11:38:47 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 17 сент. 2020 г., в 13:38, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> On 15/09/2020 14:36, Heikki Linnakangas wrote:\n>> Another patch version, fixed a few small bugs pointed out by assertion\n>> failures in the regression tests.\n> \n> Pushed. Thanks everyone!\n\nThat's wonderful! Thank you, Heikki!\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Thu, 17 Sep 2020 13:43:52 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Thu, Sep 17, 2020 at 11:38:47AM +0300, Heikki Linnakangas wrote:\n> On 15/09/2020 14:36, Heikki Linnakangas wrote:\n> > Another patch version, fixed a few small bugs pointed out by assertion\n> > failures in the regression tests.\n> \n> Pushed. Thanks everyone!\n\n+/* FIXME: bump this before pushing! */\n #define CATALOG_VERSION_NO 202009031\n\n\n\n", "msg_date": "Thu, 17 Sep 2020 07:11:40 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Heikki Linnakangas <hlinnaka@iki.fi> writes:\n> Pushed. Thanks everyone!\n\nIt appears that hyrax (CLOBBER_CACHE_ALWAYS) is not very happy\nwith this:\n\nhttps://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=hyrax&dt=2020-09-19%2021%3A27%3A23\n\nWe have a recent pass from prion, showing that -DRELCACHE_FORCE_RELEASE\n-DCATCACHE_FORCE_RELEASE doesn't cause a problem, so maybe hyrax's\nresult is just random cosmic rays or something. But I doubt it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 20 Sep 2020 16:41:12 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "I wrote:\n> It appears that hyrax (CLOBBER_CACHE_ALWAYS) is not very happy\n> with this:\n> https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=hyrax&dt=2020-09-19%2021%3A27%3A23\n\nI reproduced that and traced it to a missing RelationOpenSmgr call.\nFixed now.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 20 Sep 2020 17:10:05 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Sun, Sep 20, 2020 at 05:10:05PM -0400, Tom Lane wrote:\n> I wrote:\n> > It appears that hyrax (CLOBBER_CACHE_ALWAYS) is not very happy\n> > with this:\n> > https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=hyrax&dt=2020-09-19%2021%3A27%3A23\n> \n> I reproduced that and traced it to a missing RelationOpenSmgr call.\n> Fixed now.\n\nThis also appears to break checksums.\n\npostgres=# CREATE TABLE pvactst (i INT, a INT[], p POINT) with (autovacuum_enabled = off);\npostgres=# CREATE INDEX gist_pvactst ON pvactst USING gist (p);\npostgres=# INSERT INTO pvactst SELECT i, array[1,2,3], point(i, i+1) FROM generate_series(1,1000) i;\nWARNING: page verification failed, calculated checksum 34313 but expected 0\nERROR: invalid page in block 0 of relation base/12859/16389\n\nI was able to make this work like so:\n\n@@ -449,6 +450,7 @@ gist_indexsortbuild(GISTBuildState *state)\n \n /* Write out the root */\n PageSetLSN(pagestate->page, GistBuildLSN);\n+ PageSetChecksumInplace(pagestate->page, GIST_ROOT_BLKNO, state->indexrel->rd_smgr);\n smgrwrite(state->indexrel->rd_smgr, MAIN_FORKNUM, GIST_ROOT_BLKNO,\n pagestate->page, true);\n if (RelationNeedsWAL(state->indexrel))\n@@ -555,6 +557,7 @@ gist_indexsortbuild_flush_ready_pages(GISTBuildState *state)\n \n PageSetLSN(page, GistBuildLSN);\n \n+ PageSetChecksumInplace(page, state->pages_written, state->indexrel->rd_smgr);\n smgrextend(state->indexrel->rd_smgr,\n MAIN_FORKNUM,\n state->pages_written++,\n\n-- \nJustin\n\n\n", "msg_date": "Sun, 20 Sep 2020 17:44:46 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Justin Pryzby <pryzby@telsasoft.com> writes:\n> This also appears to break checksums.\n\nI was wondering about that, because the typical pattern for use of\nsmgrextend for indexes seems to be\n\n\tRelationOpenSmgr(rel);\n\tPageSetChecksumInplace(page, lastblock);\n\tsmgrextend(rel->rd_smgr, MAIN_FORKNUM, lastblock, zerobuf.data, false);\n\nand gist_indexsortbuild wasn't doing either of the first two things.\n\ngist_indexsortbuild_flush_ready_pages looks like it might be\na few bricks shy of a load too. But my local CLOBBER_CACHE_ALWAYS\nrun hasn't gotten to anything except the pretty-trivial index\nmade in point.sql, so I don't have evidence about it.\n\nAnother interesting point is that all the other index AMs seem to WAL-log\nthe new page before the smgrextend call, whereas this code is doing it\nin the other order. I strongly doubt that both patterns are equally\ncorrect. Could be that the other AMs are in the wrong though.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 20 Sep 2020 19:06:09 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 21/09/2020 02:06, Tom Lane wrote:\n> Justin Pryzby <pryzby@telsasoft.com> writes:\n>> This also appears to break checksums.\n\nThanks, I'll go fix it.\n\n> I was wondering about that, because the typical pattern for use of\n> smgrextend for indexes seems to be\n> \n> \tRelationOpenSmgr(rel);\n> \tPageSetChecksumInplace(page, lastblock);\n> \tsmgrextend(rel->rd_smgr, MAIN_FORKNUM, lastblock, zerobuf.data, false);\n> \n> and gist_indexsortbuild wasn't doing either of the first two things.\n> \n> gist_indexsortbuild_flush_ready_pages looks like it might be\n> a few bricks shy of a load too. But my local CLOBBER_CACHE_ALWAYS\n> run hasn't gotten to anything except the pretty-trivial index\n> made in point.sql, so I don't have evidence about it.\n\nI don't think a relcache invalidation can happen on the index we're \nbuilding. Other similar callers call RelationOpenSmgr(rel) before every \nwrite though (e.g. _bt_blwritepage()), so perhaps it's better to copy \nthat pattern here too.\n\n> Another interesting point is that all the other index AMs seem to WAL-log\n> the new page before the smgrextend call, whereas this code is doing it\n> in the other order. I strongly doubt that both patterns are equally\n> correct. Could be that the other AMs are in the wrong though.\n\nMy thinking was that it's better to call smgrextend() first, so that if \nyou run out of disk space, you get the error before WAL-logging it. That \nreduces the chance that WAL replay will run out of disk space. A lot of \nthings are different during WAL replay, so it's quite likely that WAL \nreplay runs out of disk space anyway if you're living on the edge, but \nstill.\n\nI didn't notice that the other callers are doing it the other way round, \nthough. I think they need to, so that they can stamp the page with the \nLSN of the WAL record. But GiST build is special in that regard, because \nit stamps all pages with GistBuildLSN.\n\n- Heikki\n\n\n", "msg_date": "Mon, 21 Sep 2020 11:08:01 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 21/09/2020 11:08, Heikki Linnakangas wrote:\n> I think they need to, so that they can stamp the page with the LSN of\n> the WAL record. But GiST build is special in that regard, because it\n> stamps all pages with GistBuildLSN.\n\nActually, don't we have a problem with that, even before this patch? \nEven though we set the LSN to the magic GistBuildLSN value when we build \nthe index, WAL replay will write the LSN of the record instead. That \nwould mess with the LSN-NSN interlock. After WAL replay (or in a \nstreaming replica), a scan on the GiST index might traverse right-links \nunnecessarily.\n\n- Heikki\n\n\n", "msg_date": "Mon, 21 Sep 2020 11:45:59 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 21 сент. 2020 г., в 13:45, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> On 21/09/2020 11:08, Heikki Linnakangas wrote:\n>> I think they need to, so that they can stamp the page with the LSN of\n>> the WAL record. But GiST build is special in that regard, because it\n>> stamps all pages with GistBuildLSN.\n> \n> Actually, don't we have a problem with that, even before this patch? Even though we set the LSN to the magic GistBuildLSN value when we build the index, WAL replay will write the LSN of the record instead. That would mess with the LSN-NSN interlock. After WAL replay (or in a streaming replica), a scan on the GiST index might traverse right-links unnecessarily.\n\nI think we don't set rightlinks during index build.\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Mon, 21 Sep 2020 14:06:47 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 21/09/2020 02:06, Tom Lane wrote:\n> Justin Pryzby <pryzby@telsasoft.com> writes:\n>> This also appears to break checksums.\n\nFixed, thanks for the report!\n\n> I was wondering about that, because the typical pattern for use of\n> smgrextend for indexes seems to be\n> \n> \tRelationOpenSmgr(rel);\n> \tPageSetChecksumInplace(page, lastblock);\n> \tsmgrextend(rel->rd_smgr, MAIN_FORKNUM, lastblock, zerobuf.data, false);\n> \n> and gist_indexsortbuild wasn't doing either of the first two things.\n> \n> gist_indexsortbuild_flush_ready_pages looks like it might be\n> a few bricks shy of a load too. But my local CLOBBER_CACHE_ALWAYS\n> run hasn't gotten to anything except the pretty-trivial index\n> made in point.sql, so I don't have evidence about it.\n\nI added a RelationOpenSmgr() call there too, although it's not needed \ncurrently. It seems to be enough to do it before the first smgrextend() \ncall. But if you removed or refactored the first call someohow, so it \nwas not the first call anymore, it would be easy to miss that you'd \nstill need the RelationOpenSmgr() call there. It's more consistent with \nthe code in nbtsort.c now, too.\n\n- Heikki\n\n\n", "msg_date": "Mon, 21 Sep 2020 14:56:44 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 21/09/2020 12:06, Andrey M. Borodin wrote:\n>> 21 сент. 2020 г., в 13:45, Heikki Linnakangas <hlinnaka@iki.fi>\n>> написал(а):\n>> \n>> Actually, don't we have a problem with that, even before this\n>> patch? Even though we set the LSN to the magic GistBuildLSN value\n>> when we build the index, WAL replay will write the LSN of the\n>> record instead. That would mess with the LSN-NSN interlock. After\n>> WAL replay (or in a streaming replica), a scan on the GiST index\n>> might traverse right-links unnecessarily.\n> \n> I think we don't set rightlinks during index build.\n\nThe new GiST sorting code does not, but the regular insert-based code does.\n\nThat's a bit questionable in the new code actually. Was that a conscious\ndecision? The right-links are only needed when there are concurrent page\nsplits, so I think it's OK, but the checks for InvalidBlockNumber in\ngistScanPage() and gistFindPage() have comment \"/* sanity check */\".\nComment changes are needed, at least.\n\n- Heikki\n\n\n", "msg_date": "Mon, 21 Sep 2020 15:15:18 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 21 сент. 2020 г., в 17:15, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> On 21/09/2020 12:06, Andrey M. Borodin wrote\n>> \n>> I think we don't set rightlinks during index build.\n> \n> The new GiST sorting code does not, but the regular insert-based code does.\n> \n> That's a bit questionable in the new code actually. Was that a conscious\n> decision? The right-links are only needed when there are concurrent page\n> splits, so I think it's OK, but the checks for InvalidBlockNumber in\n> gistScanPage() and gistFindPage() have comment \"/* sanity check */\".\n> Comment changes are needed, at least.\n\nIt was a conscious decision with incorrect motivation. I was thinking that it will help to reduce number of \"false positive\" inspecting right pages. But now I see that:\n1. There should be no such \"false positives\" that we can avoid\n2. Valid rightlinks could help to do amcheck verification in future\n\nBut thing that bothers me now: when we vacuum leaf page, we bump it's NSN. But we do not bump internal page LSN. Does this means we will follow rightlinks after vacuum? It seems superflous. And btw we did not adjust internal page tuples after vacuum...\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Mon, 21 Sep 2020 18:29:14 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> 21 сент. 2020 г., в 18:29, Andrey M. Borodin <x4mmm@yandex-team.ru> написал(а):\n> \n> It was a conscious decision with incorrect motivation. I was thinking that it will help to reduce number of \"false positive\" inspecting right pages. But now I see that:\n> 1. There should be no such \"false positives\" that we can avoid\n> 2. Valid rightlinks could help to do amcheck verification in future\n\nWell, point number 2 here is invalid. There exist one leaf page p, so that if we start traversing rightlink from p we will reach all leaf pages. But we practically have no means to find this page. This makes rightlinks not very helpful in amcheck for GiST.\n\nBut for consistency I think it worth to install them.\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Mon, 21 Sep 2020 19:19:32 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Heikki Linnakangas <hlinnaka@iki.fi> writes:\n> On 21/09/2020 02:06, Tom Lane wrote:\n>> Another interesting point is that all the other index AMs seem to WAL-log\n>> the new page before the smgrextend call, whereas this code is doing it\n>> in the other order. I strongly doubt that both patterns are equally\n>> correct. Could be that the other AMs are in the wrong though.\n\n> My thinking was that it's better to call smgrextend() first, so that if \n> you run out of disk space, you get the error before WAL-logging it. That \n> reduces the chance that WAL replay will run out of disk space. A lot of \n> things are different during WAL replay, so it's quite likely that WAL \n> replay runs out of disk space anyway if you're living on the edge, but \n> still.\n\nYeah. access/transam/README points out that such failures need to be\nplanned for, and explains what we do for heap pages;\n\n 1. Adding a disk page to an existing table.\n\n This action isn't WAL-logged at all. We extend a table by writing a page\n of zeroes at its end. We must actually do this write so that we are sure\n the filesystem has allocated the space. If the write fails we can just\n error out normally. Once the space is known allocated, we can initialize\n and fill the page via one or more normal WAL-logged actions. Because it's\n possible that we crash between extending the file and writing out the WAL\n entries, we have to treat discovery of an all-zeroes page in a table or\n index as being a non-error condition. In such cases we can just reclaim\n the space for re-use.\n\nSo GIST seems to be acting according to that design. (Someday we need\nto update this para to acknowledge that not all filesystems behave as\nit's assuming.)\n\n> I didn't notice that the other callers are doing it the other way round, \n> though. I think they need to, so that they can stamp the page with the \n> LSN of the WAL record. But GiST build is special in that regard, because \n> it stamps all pages with GistBuildLSN.\n\nKind of unpleasant; that means they risk what the README points out:\n\n In all of these cases, if WAL replay fails to redo the original action\n we must panic and abort recovery. The DBA will have to manually clean up\n (for instance, free up some disk space or fix directory permissions) and\n then restart recovery. This is part of the reason for not writing a WAL\n entry until we've successfully done the original action.\n\nI'm not sufficiently motivated to go and change it right now, though.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 21 Sep 2020 10:20:19 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\nOn 21/09/2020 16:29, Andrey M. Borodin wrote:\n> But thing that bothers me now: when we vacuum leaf page, we bump it's\n> NSN. But we do not bump internal page LSN. Does this means we will\n> follow rightlinks after vacuum? It seems superflous.\n\nSorry, I did not understand what you said above. Vacuum doesn't update \nany NSNs, only LSNs. Can you elaborate?\n\n> And btw we did not adjust internal page tuples after vacuum...\nWhat do you mean by that?\n\n- Heikki\n\n\n", "msg_date": "Mon, 28 Sep 2020 09:53:45 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 21/09/2020 17:19, Andrey M. Borodin wrote:\n>> 21 сент. 2020 г., в 18:29, Andrey M. Borodin <x4mmm@yandex-team.ru> написал(а):\n>>\n>> It was a conscious decision with incorrect motivation. I was thinking that it will help to reduce number of \"false positive\" inspecting right pages. But now I see that:\n>> 1. There should be no such \"false positives\" that we can avoid\n>> 2. Valid rightlinks could help to do amcheck verification in future\n> \n> Well, point number 2 here is invalid. There exist one leaf page p, so that if we start traversing rightlink from p we will reach all leaf pages. But we practically have no means to find this page. This makes rightlinks not very helpful in amcheck for GiST.\n\nWell, if you store all the right links in a hash table or something, you \ncan \"connect the dots\" after you have scanned all the pages to see that \nthe chain is unbroken. Probably would not be worth the trouble, since \nthe rightlinks are not actually needed after concurrent scans have \ncompleted.\n\n> But for consistency I think it worth to install them.\n\nI agree. I did some testing with your patch. It seems that the \nrightlinks are still not always set. I didn't try to debug why.\n\nI wrote a couple of 'pageinspect' function to inspect GiST pages for \nthis. See attached. I then created a test table and index like this:\n\ncreate table points (p point);\ninsert into points select point(x,y) from generate_series(-2000, 2000) \nx, generate_series(-2000, 2000) y;\ncreate index points_idx on points using gist (p);\n\nAnd this is what the root page looks like:\n\npostgres=# select * from gist_page_items(get_raw_page('points_idx', 0));\n itemoffset | ctid | itemlen\n------------+---------------+---------\n 1 | (27891,65535) | 40\n 2 | (55614,65535) | 40\n 3 | (83337,65535) | 40\n 4 | (97019,65535) | 40\n(4 rows)\n\nAnd the right links on the next level:\n\npostgres=# select * from (VALUES (27891), (55614), (83337), (97019)) b \n(blkno), lateral gist_page_opaque_info(get_raw_page('points_idx', blkno));\n blkno | lsn | nsn | rightlink | flags\n-------+-----+-----+------------+-------\n 27891 | 0/1 | 0/0 | 4294967295 | {}\n 55614 | 0/1 | 0/0 | 4294967295 | {}\n 83337 | 0/1 | 0/0 | 27891 | {}\n 97019 | 0/1 | 0/0 | 55614 | {}\n(4 rows)\n\nI expected there to be only one page with invalid right link, but there \nare two.\n\n- Heikki", "msg_date": "Mon, 28 Sep 2020 11:12:02 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> 28 сент. 2020 г., в 13:12, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> On 21/09/2020 17:19, Andrey M. Borodin wrote:\n>>> 21 сент. 2020 г., в 18:29, Andrey M. Borodin <x4mmm@yandex-team.ru> написал(а):\n>>> \n>>> It was a conscious decision with incorrect motivation. I was thinking that it will help to reduce number of \"false positive\" inspecting right pages. But now I see that:\n>>> 1. There should be no such \"false positives\" that we can avoid\n>>> 2. Valid rightlinks could help to do amcheck verification in future\n>> Well, point number 2 here is invalid. There exist one leaf page p, so that if we start traversing rightlink from p we will reach all leaf pages. But we practically have no means to find this page. This makes rightlinks not very helpful in amcheck for GiST.\n> \n> Well, if you store all the right links in a hash table or something, you can \"connect the dots\" after you have scanned all the pages to see that the chain is unbroken. Probably would not be worth the trouble, since the rightlinks are not actually needed after concurrent scans have completed.\n> \n>> But for consistency I think it worth to install them.\n> \n> I agree. I did some testing with your patch. It seems that the rightlinks are still not always set. I didn't try to debug why.\n> \n> I wrote a couple of 'pageinspect' function to inspect GiST pages for this. See attached. I then created a test table and index like this:\n> \n> create table points (p point);\n> insert into points select point(x,y) from generate_series(-2000, 2000) x, generate_series(-2000, 2000) y;\n> create index points_idx on points using gist (p);\n> \n> And this is what the root page looks like:\n> \n> postgres=# select * from gist_page_items(get_raw_page('points_idx', 0));\n> itemoffset | ctid | itemlen\n> ------------+---------------+---------\n> 1 | (27891,65535) | 40\n> 2 | (55614,65535) | 40\n> 3 | (83337,65535) | 40\n> 4 | (97019,65535) | 40\n> (4 rows)\n> \n> And the right links on the next level:\n> \n> postgres=# select * from (VALUES (27891), (55614), (83337), (97019)) b (blkno), lateral gist_page_opaque_info(get_raw_page('points_idx', blkno));\n> blkno | lsn | nsn | rightlink | flags\n> -------+-----+-----+------------+-------\n> 27891 | 0/1 | 0/0 | 4294967295 | {}\n> 55614 | 0/1 | 0/0 | 4294967295 | {}\n> 83337 | 0/1 | 0/0 | 27891 | {}\n> 97019 | 0/1 | 0/0 | 55614 | {}\n> (4 rows)\n> \n> I expected there to be only one page with invalid right link, but there are two.\n\nYes, there is a bug. Now it seems to me so obvious, yet it took some time to understand that links were shifted by one extra jump. PFA fixed rightlinks installation.\n\nBTW some one more small thing: we initialise page buffers with palloc() and palloc0(), while first one is sufficient for gistinitpage().\nAlso I'm working on btree_gist opclasses and found out that new sortsupport function is not mentioned in gistadjustmembers(). I think this can be fixed with gist_btree patch.\n\nYour pageinspect patch seems very useful. How do you think, should we provide a way to find invalid tuples in GiST within gist_page_items()? At some point we will have to ask user to reindex GiSTs with invalid tuples.\n\n\n> 28 сент. 2020 г., в 11:53, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> On 21/09/2020 16:29, Andrey M. Borodin wrote:\n>> But thing that bothers me now: when we vacuum leaf page, we bump it's\n>> NSN. But we do not bump internal page LSN. Does this means we will\n>> follow rightlinks after vacuum? It seems superflous.\n> \n> Sorry, I did not understand what you said above. Vacuum doesn't update any NSNs, only LSNs. Can you elaborate?\nI've misunderstood difference between NSN and LSN. Seems like everything is fine.\n\n> \n>> And btw we did not adjust internal page tuples after vacuum...\n> What do you mean by that?\n\nWhen we delete rows from table internal tuples in GiST stay wide.\n\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Tue, 29 Sep 2020 23:04:18 +0500", "msg_from": "\"Andrey M. Borodin\" <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 29/09/2020 21:04, Andrey M. Borodin wrote:\n> 28 сент. 2020 г., в 13:12, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n>> I did some testing with your patch. It seems that the rightlinks\n>> are still not always set. I didn't try to debug why.\n> \n> Yes, there is a bug. Now it seems to me so obvious, yet it took some \n> time to understand that links were shifted by one extra jump. PFA \n> fixed rightlinks installation.\nAh, that was simple. I propose adding a comment on it:\n\n--- a/src/backend/access/gist/gistbuild.c\n+++ b/src/backend/access/gist/gistbuild.c\n@@ -540,6 +540,19 @@ gist_indexsortbuild_pagestate_flush(GISTBuildState \n*state,\n \t/* Re-initialize the page buffer for next page on this level. */\n \tpagestate->page = palloc(BLCKSZ);\n \tgistinitpage(pagestate->page, isleaf ? F_LEAF : 0);\n+\n+\t/*\n+\t * Set the right link to point to the previous page. This is just for\n+\t * debugging purposes: GiST only follows the right link if a page is split\n+\t * concurrently to a scan, and that cannot happen during index build.\n+\t *\n+\t * It's a bit counterintuitive that we set the right link on the new page\n+\t * to point to the previous page, and not the other way round. But GiST\n+\t * pages are not ordered like B-tree pages are, so as long as the\n+\t * right-links form a chain through all the pages in the same level, the\n+\t * order doesn't matter.\n+\t */\n+\tGistPageGetOpaque(pagestate->page)->rightlink = blkno;\n }\n\n> BTW some one more small thing: we initialise page buffers with\n> palloc() and palloc0(), while first one is sufficient for\n> gistinitpage().\nHmm. Only the first one, in gist_indexsortbuild(), but that needs to be \npalloc0, because it's used to write an all-zeros placeholder for the \nroot page.\n\n> Also I'm working on btree_gist opclasses and found out that new\n> sortsupport function is not mentioned in gistadjustmembers(). I think\n> this can be fixed with gist_btree patch.\n\nThanks!\n\n> Your pageinspect patch seems very useful. How do you think, should we\n> provide a way to find invalid tuples in GiST within\n> gist_page_items()? At some point we will have to ask user to reindex\n> GiSTs with invalid tuples.\nYou mean invalid tuples created by crash on PostgreSQL version 9.0 or \nbelow, and pg_upgraded? I doubt there are any of those still around in \nthe wild. We have to keep the code to detect them, though.\n\nIt would be nice to improve gist_page_items() to display more \ninformation about the items, although I wouldn't worry much about \ninvalid tuples. The 'gevel' extension that Oleg mentioned upthread does \nmore, it would be nice to incorporate that into pageinspect somehow.\n\n- Heikki\n\n\n", "msg_date": "Tue, 29 Sep 2020 23:31:07 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "I've been making tests with memory sanitizer and got one another error in\nregression test create_index:\nCREATE INDEX gpointind ON point_tbl USING gist (f1);\nserver closed the connection unexpectedly\n\nwith logfile:\ngistproc.c:1714:28: runtime error: 1e+300 is outside the range of\nrepresentable values of type 'float'\nSUMMARY: UndefinedBehaviorSanitizer: undefined-behavior gistproc.c:1714:28\n\ngistproc.c:\n1714 z = point_zorder_internal(p->x, p->y);\n\nConsider this a minor issue but unrelated to the other issues discussed. It\nis reproduced on the last master\ncommit 0a3c864c32751fd29d021929cf70af421fd27370 after all changes into Gist\ncommitted.\n\ncflags=\"-DUSE_VALGRIND -Og -O0 -fsanitize=address -fsanitize=undefined\n-fno-sanitize-recover=all -fno-sanitize=alignment -fstack-protector\"\n\n\n-- \nBest regards,\nPavel Borisov\n\nPostgres Professional: http://postgrespro.com <http://www.postgrespro.com>\n\nI've been making tests with memory sanitizer and got one another error in regression test create_index:CREATE INDEX gpointind ON point_tbl USING gist (f1);server closed the connection unexpectedlywith logfile:gistproc.c:1714:28: runtime error: 1e+300 is outside the range of representable values of type 'float'SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior gistproc.c:1714:28gistproc.c:1714     z = point_zorder_internal(p->x, p->y);Consider this a minor issue but unrelated to the other issues discussed. It is reproduced on the last master commit 0a3c864c32751fd29d021929cf70af421fd27370 after all changes into Gist committed.cflags=\"-DUSE_VALGRIND -Og -O0 -fsanitize=address -fsanitize=undefined -fno-sanitize-recover=all -fno-sanitize=alignment -fstack-protector\"-- Best regards,Pavel BorisovPostgres Professional: http://postgrespro.com", "msg_date": "Tue, 6 Oct 2020 15:05:42 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 06/10/2020 14:05, Pavel Borisov wrote:\n> I've been making tests with memory sanitizer\n\nThanks!\n\n> and got one another error \n> in regression test create_index:\n> CREATE INDEX gpointind ON point_tbl USING gist (f1);\n> server closed the connection unexpectedly\n> \n> with logfile:\n> gistproc.c:1714:28: runtime error: 1e+300 is outside the range of \n> representable values of type 'float'\n> SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior gistproc.c:1714:28\n> \n> gistproc.c:\n> 1714     z = point_zorder_internal(p->x, p->y);\n> \n> Consider this a minor issue but unrelated to the other issues discussed. \n> It is reproduced on the last master \n> commit 0a3c864c32751fd29d021929cf70af421fd27370 after all changes into \n> Gist committed.\n> \n> cflags=\"-DUSE_VALGRIND -Og -O0 -fsanitize=address -fsanitize=undefined \n> -fno-sanitize-recover=all -fno-sanitize=alignment -fstack-protector\"\n\nYou get the same error with:\n\nselect (float8 '1e+300')::float4;\n\nfloat.c:1204:11: runtime error: 1e+300 is outside the range of \nrepresentable values of type 'float'\nSUMMARY: UndefinedBehaviorSanitizer: undefined-behavior float.c:1204:11 in\n\nIt boils down to casting a C double to float, when the value doesn't fit \nin float. I'm surprised that's undefined behavior, but I'm no C99 \nlawyer. The code in dtof() expects it to yield Inf.\n\nI'm inclined to shrug this off and say that the sanitizer is being \nover-zealous. Is there some compiler flag we should be setting, to tell \nit that we require specific behavior? Any other ideas?\n\n- Heikki\n\n\n", "msg_date": "Tue, 6 Oct 2020 16:19:31 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Heikki Linnakangas <hlinnaka@iki.fi> writes:\n> You get the same error with:\n> select (float8 '1e+300')::float4;\n> float.c:1204:11: runtime error: 1e+300 is outside the range of \n> representable values of type 'float'\n> SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior float.c:1204:11 in\n\n> It boils down to casting a C double to float, when the value doesn't fit \n> in float. I'm surprised that's undefined behavior, but I'm no C99 \n> lawyer. The code in dtof() expects it to yield Inf.\n\nI think UBSan read C99 6.3.1.5:\n\n [#2] When a double is demoted to float or a long double to\n double or float, if the value being converted is outside the\n range of values that can be represented, the behavior is\n undefined.\n\nand stopped reading at that point, which they should not have.\nIf you go on to read the portions around, particularly, <fenv.h>,\nyou get a different picture of affairs. If we're relying on IEEE\nfloat semantics in other places, which we are, we're perfectly\nentitled to assume that the cast will yield Inf (and a floating\npoint exception flag, which we ignore). I think the \"undefined\"\nhere is just meant to say that there's no single behavior promised\nacross all possible C implementations. They'd have been better to\nwrite \"implementation-defined\", though.\n\n> I'm inclined to shrug this off and say that the sanitizer is being \n> over-zealous. Is there some compiler flag we should be setting, to tell \n> it that we require specific behavior? Any other ideas?\n\nIf UBSan doesn't have a flag to tell it to assume IEEE math,\nI'd say that makes it next door to worthless for our purposes.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 06 Oct 2020 10:29:42 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "It became normal with\n-fsanitize=signed-integer-overflow,null,alignment\ninstead of\n-fsanitize=undefined\n(which is strictly a 'default' list of needed and unnecessary things to\ncheck, can be overridden anyway but needed some reading for it)\n\nThanks!\n\n-- \nBest regards,\nPavel Borisov\n\nPostgres Professional: http://postgrespro.com <http://www.postgrespro.com>\n\nIt became normal with -fsanitize=signed-integer-overflow,null,alignmentinstead of-fsanitize=undefined(which is strictly a 'default' list of needed and unnecessary things to check, can be overridden anyway but needed some reading for it)Thanks!-- Best regards,Pavel BorisovPostgres Professional: http://postgrespro.com", "msg_date": "Tue, 6 Oct 2020 19:29:29 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> 29 сент. 2020 г., в 23:04, Andrey M. Borodin <x4mmm@yandex-team.ru> написал(а):\n> \n> \n> Also I'm working on btree_gist opclasses and found out that new sortsupport function is not mentioned in gistadjustmembers(). I think this can be fixed with gist_btree patch.\n\nHere's draft patch with implementation of sortsupport for ints and floats.\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Wed, 7 Oct 2020 17:27:21 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 07/10/2020 15:27, Andrey Borodin wrote:\n> Here's draft patch with implementation of sortsupport for ints and floats.\n\n> +static int\n> +gbt_int4_cmp(Datum a, Datum b, SortSupport ssup)\n> +{\n> +\tint32KEY *ia = (int32KEY *) DatumGetPointer(a);\n> +\tint32KEY *ib = (int32KEY *) DatumGetPointer(b);\n> +\n> +\tif (ia->lower == ib->lower)\n> +\t{\n> +\t\tif (ia->upper == ib->upper)\n> +\t\t\treturn 0;\n> +\n> +\t\treturn (ia->upper > ib->upper) ? 1 : -1;\n> +\t}\n> +\n> +\treturn (ia->lower > ib->lower) ? 1 : -1;\n> +}\n\nWe're only dealing with leaf items during index build, so the 'upper' \nand 'lower' should always be equal here, right? Maybe add a comment and \nan assertion on that.\n\n(It's pretty sad that the on-disk representation is identical for leaf \nand internal items, because that wastes a lot of disk space, but that's \nway out of scope for this patch.)\n\n- Heikki\n\n\n", "msg_date": "Wed, 7 Oct 2020 15:38:20 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> 7 окт. 2020 г., в 17:38, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> On 07/10/2020 15:27, Andrey Borodin wrote:\n>> Here's draft patch with implementation of sortsupport for ints and floats.\n> \n>> +static int\n>> +gbt_int4_cmp(Datum a, Datum b, SortSupport ssup)\n>> +{\n>> +\tint32KEY *ia = (int32KEY *) DatumGetPointer(a);\n>> +\tint32KEY *ib = (int32KEY *) DatumGetPointer(b);\n>> +\n>> +\tif (ia->lower == ib->lower)\n>> +\t{\n>> +\t\tif (ia->upper == ib->upper)\n>> +\t\t\treturn 0;\n>> +\n>> +\t\treturn (ia->upper > ib->upper) ? 1 : -1;\n>> +\t}\n>> +\n>> +\treturn (ia->lower > ib->lower) ? 1 : -1;\n>> +}\n> \n> We're only dealing with leaf items during index build, so the 'upper' and 'lower' should always be equal here, right? Maybe add a comment and an assertion on that.\n> \n> (It's pretty sad that the on-disk representation is identical for leaf and internal items, because that wastes a lot of disk space, but that's way out of scope for this patch.)\n\nThanks, I've added assert() where is was easy to test equalty.\n\nPFA patch with all types.\n\nI had a plan to implement and test one type each day. I did not quite understood how rich our type system is.\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Wed, 21 Oct 2020 22:13:34 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": ">\n>\n> >> + return (ia->lower > ib->lower) ? 1 : -1;\n> >> +}\n> >\n> > We're only dealing with leaf items during index build, so the 'upper'\n> and 'lower' should always be equal here, right? Maybe add a comment and an\n> assertion on that.\n> >\n> > (It's pretty sad that the on-disk representation is identical for leaf\n> and internal items, because that wastes a lot of disk space, but that's way\n> out of scope for this patch.)\n>\n> Thanks, I've added assert() where is was easy to test equalty.\n>\n> PFA patch with all types.\n>\n> I had a plan to implement and test one type each day. I did not quite\n> understood how rich our type system is.\n>\n\nCool, thanks!\n\nBTW there is a somewhat parallel discussion on this gist patch in\npgsql-bugs which you may miss\nhttps://www.postgresql.org/message-id/flat/3dda6945-c147-5afc-7720-38ec6848dafa%40gmail.com#9be5b8a75c4921498748514cb77c6e68\n\nThe main point is that buffering build is better to be enforced with\nbuffering=on\nas otherwise buffering build becomes hard to test in the presence of sort\nsupport.\n\n-- \nBest regards,\nPavel Borisov\n\nPostgres Professional: http://postgrespro.com <http://www.postgrespro.com>\n\n\n>> +    return (ia->lower > ib->lower) ? 1 : -1;\n>> +}\n> \n> We're only dealing with leaf items during index build, so the 'upper' and 'lower' should always be equal here, right? Maybe add a comment and an assertion on that.\n> \n> (It's pretty sad that the on-disk representation is identical for leaf and internal items, because that wastes a lot of disk space, but that's way out of scope for this patch.)\n\nThanks, I've added assert() where is was easy to test equalty.\n\nPFA patch with all types.\n\nI had a plan to implement and test one type each day. I did not quite understood how rich our type system is.Cool, thanks!BTW there is a somewhat parallel discussion on this gist patch in pgsql-bugs which you may miss https://www.postgresql.org/message-id/flat/3dda6945-c147-5afc-7720-38ec6848dafa%40gmail.com#9be5b8a75c4921498748514cb77c6e68The main point is that buffering build is better to be enforced with buffering=on as otherwise buffering build becomes hard to test in the presence of sort support.  -- Best regards,Pavel BorisovPostgres Professional: http://postgrespro.com", "msg_date": "Wed, 21 Oct 2020 21:35:27 +0400", "msg_from": "Pavel Borisov <pashkin.elfe@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 21/10/2020 20:13, Andrey Borodin wrote:\n>> 7 окт. 2020 г., в 17:38, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n>>\n>> On 07/10/2020 15:27, Andrey Borodin wrote:\n>>> Here's draft patch with implementation of sortsupport for ints and floats.\n>>\n>>> +static int\n>>> +gbt_int4_cmp(Datum a, Datum b, SortSupport ssup)\n>>> +{\n>>> +\tint32KEY *ia = (int32KEY *) DatumGetPointer(a);\n>>> +\tint32KEY *ib = (int32KEY *) DatumGetPointer(b);\n>>> +\n>>> +\tif (ia->lower == ib->lower)\n>>> +\t{\n>>> +\t\tif (ia->upper == ib->upper)\n>>> +\t\t\treturn 0;\n>>> +\n>>> +\t\treturn (ia->upper > ib->upper) ? 1 : -1;\n>>> +\t}\n>>> +\n>>> +\treturn (ia->lower > ib->lower) ? 1 : -1;\n>>> +}\n>>\n>> We're only dealing with leaf items during index build, so the 'upper' and 'lower' should always be equal here, right? Maybe add a comment and an assertion on that.\n>>\n>> (It's pretty sad that the on-disk representation is identical for leaf and internal items, because that wastes a lot of disk space, but that's way out of scope for this patch.)\n> \n> Thanks, I've added assert() where is was easy to test equalty.\n> \n> PFA patch with all types.\n\ngbt_ts_cmp(), gbt_time_cmp_sort() and gbt_date_cmp_sort() still have the \nabove issue, they still compare \"upper\" for no good reason.\n\n> +static Datum\n> +gbt_bit_abbrev_convert(Datum original, SortSupport ssup)\n> +{\n> + return (Datum) 0;\n> +}\n> +\n> +static int\n> +gbt_bit_cmp_abbrev(Datum z1, Datum z2, SortSupport ssup)\n> +{\n> + return 0;\n> +}\n\nIf an abbreviated key is not useful, just don't define abbrev functions \nand don't set SortSupport->abbrev_converter in the first place.\n\n> static bool\n> gbt_inet_abbrev_abort(int memtupcount, SortSupport ssup)\n> {\n> #if SIZEOF_DATUM == 8\n> \treturn false;\n> #else\n> \treturn true;\n> #endif\n> }\n\nBetter to not set the 'abbrev_converter' function in the first place. Or \nwould it be better to cast the float8 to float4 if SIZEOF_DATUM == 4?\n\n> I had a plan to implement and test one type each day. I did not quite understood how rich our type system is.\n\n:-)\n\n- Heikki\n\n\n", "msg_date": "Tue, 27 Oct 2020 13:43:48 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Thanks!\n\n> 27 окт. 2020 г., в 16:43, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> gbt_ts_cmp(), gbt_time_cmp_sort() and gbt_date_cmp_sort() still have the above issue, they still compare \"upper\" for no good reason.\nFixed.\n\n>> +static Datum\n>> +gbt_bit_abbrev_convert(Datum original, SortSupport ssup)\n>> +{\n>> + return (Datum) 0;\n>> +}\n>> +\n>> +static int\n>> +gbt_bit_cmp_abbrev(Datum z1, Datum z2, SortSupport ssup)\n>> +{\n>> + return 0;\n>> +}\n> \n> If an abbreviated key is not useful, just don't define abbrev functions and don't set SortSupport->abbrev_converter in the first place.\nFixed.\n> \n>> static bool\n>> gbt_inet_abbrev_abort(int memtupcount, SortSupport ssup)\n>> {\n>> #if SIZEOF_DATUM == 8\n>> \treturn false;\n>> #else\n>> \treturn true;\n>> #endif\n>> }\n> \n> Better to not set the 'abbrev_converter' function in the first place. Or would it be better to cast the float8 to float4 if SIZEOF_DATUM == 4?\nOk, now for 4 bytes Datum we do return (Datum) Float4GetDatum((float) z);\n\nHow do you think, should this patch and patch with pageinspect GiST functions be registered on commitfest?\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Fri, 30 Oct 2020 23:20:58 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 30/10/2020 20:20, Andrey Borodin wrote:\n>> 27 окт. 2020 г., в 16:43, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n>>> static bool\n>>> gbt_inet_abbrev_abort(int memtupcount, SortSupport ssup)\n>>> {\n>>> #if SIZEOF_DATUM == 8\n>>> \treturn false;\n>>> #else\n>>> \treturn true;\n>>> #endif\n>>> }\n>>\n>> Better to not set the 'abbrev_converter' function in the first place. Or would it be better to cast the float8 to float4 if SIZEOF_DATUM == 4?\n> Ok, now for 4 bytes Datum we do return (Datum) Float4GetDatum((float) z);\n\nA few quick comments:\n\n* Currently with float8, you immediately abort abbreviation if \nSIZEOF_DATUM == 4. Like in the 'inet' above, you could convert the \nfloat8 to float4 instead.\n\n* Some of the ALTER OPERATOR FAMILY commands in btree_gist--1.6--1.7.sql \nare copy-pasted wrong. Here's one example:\n\nALTER OPERATOR FAMILY gist_timestamptz_ops USING gist ADD\n\tFUNCTION\t11\t(text, text) gbt_text_sortsupport;\n\n* It's easy to confuse the new comparison functions with the existing \ncomparisons used by the picksplit functions. Some comments and/or naming \nchanges would be good to clarify how they're different.\n\n* It would be straightforward to have abbreviated functions for macaddr \nand macaddr8 too.\n\n> How do you think, should this patch and patch with pageinspect GiST functions be registered on commitfest?\n\nYeah, that'd be good.\n\n- Heikki\n\n\n", "msg_date": "Mon, 2 Nov 2020 16:45:56 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 2 нояб. 2020 г., в 19:45, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n>> How do you think, should this patch and patch with pageinspect GiST functions be registered on commitfest?\n> \n> Yeah, that'd be good.\nI've registered both patches on January CF.\npageinspect patch's code looks goot to me (besides TODO item there), but it lacks docs and tests. I can add some info and calls in future reviews.\n\n> \n> On 30/10/2020 20:20, Andrey Borodin wrote:\n> A few quick comments:\n> \n> * Currently with float8, you immediately abort abbreviation if SIZEOF_DATUM == 4. Like in the 'inet' above, you could convert the float8 to float4 instead.\n> \n> * Some of the ALTER OPERATOR FAMILY commands in btree_gist--1.6--1.7.sql are copy-pasted wrong. Here's one example:\n> \n> ALTER OPERATOR FAMILY gist_timestamptz_ops USING gist ADD\n> \tFUNCTION\t11\t(text, text) gbt_text_sortsupport;\n> \n> * It's easy to confuse the new comparison functions with the existing comparisons used by the picksplit functions. Some comments and/or naming changes would be good to clarify how they're different.\n> \n> * It would be straightforward to have abbreviated functions for macaddr and macaddr8 too.\n\nI'll fix these issues soon. But things like this bother me a lot:\n> ALTER OPERATOR FAMILY gist_timestamptz_ops USING gist ADD\n> \tFUNCTION\t11\t(text, text) gbt_text_sortsupport;\n\nTo test that functions are actually called for sorting build we should support directive sorting build like \"CREATE INDEX ON A USING GIST(B) WITH(sorting=surely,and fail if not)\".\nIf we have unconditional sorting build and unconditional buffered build we can check opclasses code better.\nThe problem is current reloption is called \"buffering\". It would be strange if we gave this enum possible value like \"not buffering, but very much like buffering, just another way\".\nHow do you think, is it ok to add reloption \"buffering=sorting\" to enhance tests?\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Thu, 5 Nov 2020 22:11:52 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Thu, Nov 05, 2020 at 10:11:52PM +0500, Andrey Borodin wrote:\n> To test that functions are actually called for sorting build we should support directive sorting build like \"CREATE INDEX ON A USING GIST(B) WITH(sorting=surely,and fail if not)\".\n\nMaybe you could add a DEBUG1 message for that, and include that in regression\ntests, which would then fail if sorting wasn't used.\n\nMaybe you'd need to make it consistent by setting GUCs like work_mem /\nmax_parallel_maintenance_workers / ??\n\nSimilar to this\n\npostgres=# SET client_min_messages =debug;\npostgres=# CREATE INDEX ON A USING GIST(i) WITH(buffering=off);\nDEBUG: building index \"a_i_idx2\" on table \"a\" serially\nCREATE INDEX\n\n> If we have unconditional sorting build and unconditional buffered build we can check opclasses code better.\n> The problem is current reloption is called \"buffering\". It would be strange if we gave this enum possible value like \"not buffering, but very much like buffering, just another way\".\n> How do you think, is it ok to add reloption \"buffering=sorting\" to enhance tests?\n> \n> Best regards, Andrey Borodin.\n\n\n", "msg_date": "Thu, 5 Nov 2020 11:20:30 -0600", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> 5 нояб. 2020 г., в 22:20, Justin Pryzby <pryzby@telsasoft.com> написал(а):\n> \n> On Thu, Nov 05, 2020 at 10:11:52PM +0500, Andrey Borodin wrote:\n>> To test that functions are actually called for sorting build we should support directive sorting build like \"CREATE INDEX ON A USING GIST(B) WITH(sorting=surely,and fail if not)\".\n> \n> Maybe you could add a DEBUG1 message for that, and include that in regression\n> tests, which would then fail if sorting wasn't used.\n\nThat's a good idea. Thanks!\n> \n> Maybe you'd need to make it consistent by setting GUCs like work_mem /\n> max_parallel_maintenance_workers / ??\n> \n> Similar to this\n> \n> postgres=# SET client_min_messages =debug;\n> postgres=# CREATE INDEX ON A USING GIST(i) WITH(buffering=off);\n> DEBUG: building index \"a_i_idx2\" on table \"a\" serially\n> CREATE INDEX\n\nCurrently, only B-tree uses parallel build, so no need to tweak GUCs except client_min_messages.\nBefore these tests, actually, ~20% of opclasses were not working as expected. Despite I've checked each one by hand. I have \n\nPFA patch with fixed comments from Heikki.\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Sat, 7 Nov 2020 20:42:31 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> 28 сент. 2020 г., в 13:12, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> I wrote a couple of 'pageinspect' function to inspect GiST pages for this. See attached.\n> <0001-Add-functions-to-pageinspect-to-inspect-GiST-indexes.patch>\n\nHere's version with tests and docs. I still have no idea how to print some useful information about tuples keys.\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Mon, 7 Dec 2020 15:05:19 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Mon, Dec 7, 2020 at 2:05 AM Andrey Borodin <x4mmm@yandex-team.ru> wrote:\n> Here's version with tests and docs. I still have no idea how to print some useful information about tuples keys.\n\nI suggest calling BuildIndexValueDescription() from your own custom\ndebug instrumentation code.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 7 Dec 2020 10:56:09 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 7 дек. 2020 г., в 23:56, Peter Geoghegan <pg@bowt.ie> написал(а):\n> \n> On Mon, Dec 7, 2020 at 2:05 AM Andrey Borodin <x4mmm@yandex-team.ru> wrote:\n>> Here's version with tests and docs. I still have no idea how to print some useful information about tuples keys.\n> \n> I suggest calling BuildIndexValueDescription() from your own custom\n> debug instrumentation code.\nThanks for the hint, Peter!\nThis function does exactly what I want to do. But I have no Relation inside gist_page_items(bytea) function... probably, I'll add gist_page_items(relname, blockno) overload to fetch keys.\n\nThanks!\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Wed, 9 Dec 2020 14:47:31 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> 9 дек. 2020 г., в 14:47, Andrey Borodin <x4mmm@yandex-team.ru> написал(а):\n> \n> \n> \n>> 7 дек. 2020 г., в 23:56, Peter Geoghegan <pg@bowt.ie> написал(а):\n>> \n>> On Mon, Dec 7, 2020 at 2:05 AM Andrey Borodin <x4mmm@yandex-team.ru> wrote:\n>>> Here's version with tests and docs. I still have no idea how to print some useful information about tuples keys.\n>> \n>> I suggest calling BuildIndexValueDescription() from your own custom\n>> debug instrumentation code.\n> Thanks for the hint, Peter!\n> This function does exactly what I want to do. But I have no Relation inside gist_page_items(bytea) function... probably, I'll add gist_page_items(relname, blockno) overload to fetch keys.\n\nPFA patch with implementation.\n\nBest regards, Andrey Borodin.", "msg_date": "Thu, 10 Dec 2020 15:16:04 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 10/12/2020 12:16, Andrey Borodin wrote:\n>> 9 дек. 2020 г., в 14:47, Andrey Borodin <x4mmm@yandex-team.ru> написал(а):\n>>> 7 дек. 2020 г., в 23:56, Peter Geoghegan <pg@bowt.ie> написал(а):\n>>>\n>>> On Mon, Dec 7, 2020 at 2:05 AM Andrey Borodin <x4mmm@yandex-team.ru> wrote:\n>>>> Here's version with tests and docs. I still have no idea how to print some useful information about tuples keys.\n>>>\n>>> I suggest calling BuildIndexValueDescription() from your own custom\n>>> debug instrumentation code.\n>> Thanks for the hint, Peter!\n>> This function does exactly what I want to do. But I have no Relation inside gist_page_items(bytea) function... probably, I'll add gist_page_items(relname, blockno) overload to fetch keys.\n> \n> PFA patch with implementation.\n\nI did a bit of cleanup on the function signature. The .sql script \nclaimed that gist_page_items() took bytea as argument, but in reality it \nwas a relation name, as text. I changed it so that it takes a page image \nas argument, instead of reading the block straight from the index. \nMainly to make it consistent with brin_page_items(), if it wasn't for \nthat precedence I might've gone either way on it.\n\nFixed the docs accordingly, and ran pgindent. New patch version attached.\n\n- Heikki", "msg_date": "Tue, 12 Jan 2021 15:49:36 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 12 янв. 2021 г., в 18:49, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n>> PFA patch with implementation.\n> \n> I did a bit of cleanup on the function signature. The .sql script claimed that gist_page_items() took bytea as argument, but in reality it was a relation name, as text. I changed it so that it takes a page image as argument, instead of reading the block straight from the index. Mainly to make it consistent with brin_page_items(), if it wasn't for that precedence I might've gone either way on it.\nbt_page_items() takes relation name and block number, that was a reason for doing so. But all others *_page_items() (heap, brin, hash) are doing as in v4. So I think it's more common way.\n\n> \n> Fixed the docs accordingly, and ran pgindent. New patch version attached.\n\nThanks! Looks good to me.\n\nOne more question: will bytea tests run correctly on 32bit\\different-endian systems?\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Tue, 12 Jan 2021 21:19:44 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 12/01/2021 18:19, Andrey Borodin wrote:\n>> 12 янв. 2021 г., в 18:49, Heikki Linnakangas <hlinnaka@iki.fi>\n>> написал(а):\n>> \n>> Fixed the docs accordingly, and ran pgindent. New patch version\n>> attached.\n> \n> Thanks! Looks good to me.\n\nPushed, thanks!\n\n> One more question: will bytea tests run correctly on\n> 32bit\\different-endian systems?\n\nGood question. Somehow I thought we were printing esseantilly text \nvalues as bytea. But they are Points, which consists of float8's. Since \nI already pushed this, I'm going to just wait and see what the buildfarm \nsays, and fix if needed. I think the fix is going to be to just remove \nthe test for the bytea-variant, it doesn't seem that important to test.\n\n- Heikki\n\n\n", "msg_date": "Wed, 13 Jan 2021 10:41:44 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 13 янв. 2021 г., в 13:41, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n>> One more question: will bytea tests run correctly on\n>> 32bit\\different-endian systems?\n> \n> Good question. Somehow I thought we were printing esseantilly text values as bytea. But they are Points, which consists of float8's. Since I already pushed this, I'm going to just wait and see what the buildfarm says, and fix if needed. I think the fix is going to be to just remove the test for the bytea-variant, it doesn't seem that important to test.\n\nMaybe we can just omit key_data from tests?\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Wed, 13 Jan 2021 14:46:51 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 13/01/2021 11:46, Andrey Borodin wrote:\n>> 13 янв. 2021 г., в 13:41, Heikki Linnakangas <hlinnaka@iki.fi>\n>> написал(а):\n>> \n>>> One more question: will bytea tests run correctly on \n>>> 32bit\\different-endian systems?\n>> \n>> Good question. Somehow I thought we were printing esseantilly text\n>> values as bytea. But they are Points, which consists of float8's.\n>> Since I already pushed this, I'm going to just wait and see what\n>> the buildfarm says, and fix if needed. I think the fix is going to\n>> be to just remove the test for the bytea-variant, it doesn't seem\n>> that important to test.\n> \n> Maybe we can just omit key_data from tests?\n\nMake sense, fixed it that way. Thanks!\n\n- Heikki\n\n\n", "msg_date": "Wed, 13 Jan 2021 12:34:08 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 13/01/2021 12:34, Heikki Linnakangas wrote:\n> On 13/01/2021 11:46, Andrey Borodin wrote:\n>>> 13 янв. 2021 г., в 13:41, Heikki Linnakangas <hlinnaka@iki.fi>\n>>> написал(а):\n>>>\n>>>> One more question: will bytea tests run correctly on\n>>>> 32bit\\different-endian systems?\n>>>\n>>> Good question. Somehow I thought we were printing esseantilly text\n>>> values as bytea. But they are Points, which consists of float8's.\n>>> Since I already pushed this, I'm going to just wait and see what\n>>> the buildfarm says, and fix if needed. I think the fix is going to\n>>> be to just remove the test for the bytea-variant, it doesn't seem\n>>> that important to test.\n>>\n>> Maybe we can just omit key_data from tests?\n> \n> Make sense, fixed it that way. Thanks!\n\nBuildfarm animal thorntail is still not happy:\n\n> --- /home/nm/farm/sparc64_deb10_gcc_64_ubsan/HEAD/pgsql.build/../pgsql/contrib/pageinspect/expected/gist.out\t2021-01-13 13:38:09.721752365 +0300\n> +++ /home/nm/farm/sparc64_deb10_gcc_64_ubsan/HEAD/pgsql.build/contrib/pageinspect/results/gist.out\t2021-01-13 14:12:21.540046507 +0300\n> @@ -3,21 +3,21 @@\n> CREATE INDEX test_gist_idx ON test_gist USING gist (p);\n> -- Page 0 is the root, the rest are leaf pages\n> SELECT * FROM gist_page_opaque_info(get_raw_page('test_gist_idx', 0));\n> - lsn | nsn | rightlink | flags \n> ------+-----+------------+-------\n> - 0/1 | 0/0 | 4294967295 | {}\n> + lsn | nsn | rightlink | flags \n> +------------+-----+------------+-------\n> + 0/1B8357F8 | 0/0 | 4294967295 | {}\n> (1 row)\n\nLooks like the LSN on the page is not set to GistBuildLSN as expected. \nWeird.\n\nThorntail is a sparc64 system, so little-endian, but the other \nlittle-endian buildfarm members are not reporting this error. Any idea \nwhat might be going on?\n\n- Heikki\n\n\n", "msg_date": "Wed, 13 Jan 2021 13:53:39 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Heikki Linnakangas <hlinnaka@iki.fi> writes:\n> On 13/01/2021 11:46, Andrey Borodin wrote:\n>> Maybe we can just omit key_data from tests?\n\n> Make sense, fixed it that way. Thanks!\n\nthorntail, at least, is still unhappy.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 13 Jan 2021 11:17:47 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\nOn 13 January 2021 13:53:39 EET, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>Buildfarm animal thorntail is still not happy:\n>\n>> --- /home/nm/farm/sparc64_deb10_gcc_64_ubsan/HEAD/pgsql.build/../pgsql/contrib/pageinspect/expected/gist.out\t2021-01-13 13:38:09.721752365 +0300\n>> +++ /home/nm/farm/sparc64_deb10_gcc_64_ubsan/HEAD/pgsql.build/contrib/pageinspect/results/gist.out\t2021-01-13 14:12:21.540046507 +0300\n>> @@ -3,21 +3,21 @@\n>> CREATE INDEX test_gist_idx ON test_gist USING gist (p);\n>> -- Page 0 is the root, the rest are leaf pages\n>> SELECT * FROM gist_page_opaque_info(get_raw_page('test_gist_idx', 0));\n>> - lsn | nsn | rightlink | flags \n>> ------+-----+------------+-------\n>> - 0/1 | 0/0 | 4294967295 | {}\n>> + lsn | nsn | rightlink | flags \n>> +------------+-----+------------+-------\n>> + 0/1B8357F8 | 0/0 | 4294967295 | {}\n>> (1 row)\n>\n>Looks like the LSN on the page is not set to GistBuildLSN as expected. \n>Weird.\n>\n>Thorntail is a sparc64 system, so little-endian, but the other \n>little-endian buildfarm members are not reporting this error. Any idea \n>what might be going on?\n\nStatus update on this: I am building Postgres in a qemu sparc64 emulated virtual machine, hoping to be able to reproduce this. It's very slow, so it will take hours still to complete.\n\nI don't think this is a problem with the test, or with the new pageinspect functions, but a genuine bug in the gist building code. Or there is something special on that animal that causes the just-created index pages to be dirtied. It does seem to happen consistently on thorntail, but not on other animals.\n\n- Heikki\n\n\n", "msg_date": "Wed, 13 Jan 2021 20:04:10 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 13 January 2021 20:04:10 EET, Heikki Linnakangas <hlinnaka@gmail.com> wrote:\n>\n>\n>On 13 January 2021 13:53:39 EET, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>>Looks like the LSN on the page is not set to GistBuildLSN as expected. \n>>Weird.\n>>\n>>Thorntail is a sparc64 system, so little-endian, but the other \n>>little-endian buildfarm members are not reporting this error. Any idea \n>>what might be going on?\n>\n>Status update on this: I am building Postgres in a qemu sparc64 emulated virtual machine, hoping to be able to reproduce this. It's very slow, so it will take hours still to complete.\n>\n>I don't think this is a problem with the test, or with the new pageinspect functions, but a genuine bug in the gist building code. Or there is something special on that animal that causes the just-created index pages to be dirtied. It does seem to happen consistently on thorntail, but not on other animals.\n\nAh, silly me. Thorntail uses \"wal_level=minimal\". With that, I can readily reproduce this.\n\nI'm still not sure why it happens, but now it should be straightforward to debug.\n\n- Heikki\n\n\n", "msg_date": "Wed, 13 Jan 2021 20:16:23 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Tue, Jan 12, 2021 at 5:49 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> I did a bit of cleanup on the function signature. The .sql script\n> claimed that gist_page_items() took bytea as argument, but in reality it\n> was a relation name, as text. I changed it so that it takes a page image\n> as argument, instead of reading the block straight from the index.\n> Mainly to make it consistent with brin_page_items(), if it wasn't for\n> that precedence I might've gone either way on it.\n\nBTW it would be nice if gist_page_items() had a \"dead\" boolean output\nargument for the item's LP_DEAD bit, just like bt_page_items(). I plan\non adding some testing for GiST's opportunistic index deletion soon. I\nmay also add some of the same enhancements that nbtree got today\n(following commit d168b666).\n\nThis feature was originally heavily based on the nbtree LP_DEAD\ndeletion mechanism (now called simple deletion), and I see no reason\n(or at least no good reason) why it shouldn't be possible to keep it\nin sync (except maybe with bottom-up deletion, where that it at least\nisn't straightforward/mechanical).\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Wed, 13 Jan 2021 15:47:52 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> 14 янв. 2021 г., в 04:47, Peter Geoghegan <pg@bowt.ie> написал(а):\n> \n> On Tue, Jan 12, 2021 at 5:49 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>> I did a bit of cleanup on the function signature. The .sql script\n>> claimed that gist_page_items() took bytea as argument, but in reality it\n>> was a relation name, as text. I changed it so that it takes a page image\n>> as argument, instead of reading the block straight from the index.\n>> Mainly to make it consistent with brin_page_items(), if it wasn't for\n>> that precedence I might've gone either way on it.\n> \n> BTW it would be nice if gist_page_items() had a \"dead\" boolean output\n> argument for the item's LP_DEAD bit, just like bt_page_items().\n+1. PFA patch.\n\n> I plan\n> on adding some testing for GiST's opportunistic index deletion soon. I\n> may also add some of the same enhancements that nbtree got today\n> (following commit d168b666).\n> \n> This feature was originally heavily based on the nbtree LP_DEAD\n> deletion mechanism (now called simple deletion), and I see no reason\n> (or at least no good reason) why it shouldn't be possible to keep it\n> in sync (except maybe with bottom-up deletion, where that it at least\n> isn't straightforward/mechanical).\n\nSound great!\n\nBest regards, Andrey Borodin.", "msg_date": "Thu, 14 Jan 2021 14:52:12 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 2021-01-12 14:49, Heikki Linnakangas wrote:\n>>>> I suggest calling BuildIndexValueDescription() from your own custom\n>>>> debug instrumentation code.\n>>> Thanks for the hint, Peter!\n>>> This function does exactly what I want to do. But I have no Relation inside gist_page_items(bytea) function... probably, I'll add gist_page_items(relname, blockno) overload to fetch keys.\n>>\n>> PFA patch with implementation.\n> \n> I did a bit of cleanup on the function signature. The .sql script\n> claimed that gist_page_items() took bytea as argument, but in reality it\n> was a relation name, as text. I changed it so that it takes a page image\n> as argument, instead of reading the block straight from the index.\n> Mainly to make it consistent with brin_page_items(), if it wasn't for\n> that precedence I might've gone either way on it.\n\nI noticed this patch while working on another patch for pageinspect [0], \nand this one appears to introduce a problem similar to the one the other \npatch attempts to fix: The \"itemlen\" output parameters are declared to \nbe of type smallint, but the underlying C data is of type uint16 \n(OffsetNumber). I don't know the details of gist enough to determine \nwhether overflow is possible here. If not, perhaps a check or at least \na comment would be useful. Otherwise, these parameters should be of \ntype int in SQL.\n\n[0]: \nhttps://www.postgresql.org/message-id/09e2dd82-4eb6-bba1-271a-d2b58bf6c71f@enterprisedb.com\n\n\n", "msg_date": "Fri, 15 Jan 2021 06:24:42 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 15 янв. 2021 г., в 10:24, Peter Eisentraut <peter.eisentraut@enterprisedb.com> написал(а):\n> \n> I noticed this patch while working on another patch for pageinspect [0], and this one appears to introduce a problem similar to the one the other patch attempts to fix: The \"itemlen\" output parameters are declared to be of type smallint, but the underlying C data is of type uint16 (OffsetNumber). I don't know the details of gist enough to determine whether overflow is possible here. If not, perhaps a check or at least a comment would be useful. Otherwise, these parameters should be of type int in SQL.\n\nItem offsets cannot exceed maximum block size of 32768. And even 32768/sizeof(ItemId). Thus overflow is impossible.\nInteresting question is wether pageinspect should protect itself from corrupted input?\nGenerating description from bogus tuple, probably, can go wrong.\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Fri, 15 Jan 2021 22:05:49 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Heikki Linnakangas <hlinnaka@iki.fi> writes:\n> On 12/01/2021 18:19, Andrey Borodin wrote:\n>> Thanks! Looks good to me.\n\n> Pushed, thanks!\n\nI noticed that gist_page_items() thinks it can hold inter_call_data->rel\nopen across a series of calls. That's completely unsafe: the executor\nmight not run the call series to completion (see LIMIT), resulting in\nrelcache leak complaints. I suspect that it might have cache-flush\nhazards even without that. I think this code needs to be rewritten to do\nall the interesting work in the first call. Or maybe better, return the\nresults as a tuplestore so you don't have to do multiple calls at all.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 17 Jan 2021 15:50:31 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Sun, Jan 17, 2021 at 12:50 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> I noticed that gist_page_items() thinks it can hold inter_call_data->rel\n> open across a series of calls. That's completely unsafe: the executor\n> might not run the call series to completion (see LIMIT), resulting in\n> relcache leak complaints.\n\nIt also has the potential to run into big problems should the user\ninput a raw page image with an regclass-argument-incompatible tuple\ndescriptor. Maybe that's okay (this is a tool for experts), but it\ncertainly is a consideration.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Sun, 17 Jan 2021 14:35:18 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 18/01/2021 00:35, Peter Geoghegan wrote:\n> On Sun, Jan 17, 2021 at 12:50 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I noticed that gist_page_items() thinks it can hold inter_call_data->rel\n>> open across a series of calls. That's completely unsafe: the executor\n>> might not run the call series to completion (see LIMIT), resulting in\n>> relcache leak complaints.\n\nFixed, thanks! I changed it to return a tuplestore.\n\n> It also has the potential to run into big problems should the user\n> input a raw page image with an regclass-argument-incompatible tuple\n> descriptor. Maybe that's okay (this is a tool for experts), but it\n> certainly is a consideration.\n\nI'm not sure I understand. It's true that the raw page image can contain \ndata from a different index, or any garbage really. And the function \nwill behave badly if you do that. That's an accepted risk with \npageinspect functions, that's why they're superuser-only, although some \nof them are more tolerant of corrupt pages than others. The \ngist_page_items_bytea() variant doesn't try to parse the key data and is \nless likely to crash on bad input.\n\n- Heikki\n\n\n", "msg_date": "Mon, 18 Jan 2021 00:52:12 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Sun, Jan 17, 2021 at 2:52 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> I'm not sure I understand. It's true that the raw page image can contain\n> data from a different index, or any garbage really. And the function\n> will behave badly if you do that. That's an accepted risk with\n> pageinspect functions, that's why they're superuser-only, although some\n> of them are more tolerant of corrupt pages than others. The\n> gist_page_items_bytea() variant doesn't try to parse the key data and is\n> less likely to crash on bad input.\n\nI personally agree with you - it's not like there aren't other ways\nfor superusers to crash the server (most of which seem very similar to\nthis gist_page_items() issue, in fact). I just think that it's worth\nbeing clear about that being a trade-off that we've accepted.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Sun, 17 Jan 2021 15:04:36 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Sun, Jan 17, 2021 at 3:04 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> I personally agree with you - it's not like there aren't other ways\n> for superusers to crash the server (most of which seem very similar to\n> this gist_page_items() issue, in fact). I just think that it's worth\n> being clear about that being a trade-off that we've accepted.\n\nCan we rename gist_page_items_bytea() to gist_page_items(), and at the\nsame time rename the current gist_page_items() -- perhaps call it\ngist_page_items_output()?\n\nThat way we could add a bt_page_items_output() function later, while\nleaving everything consistent (actually not quite, since\nbt_page_items() outputs text instead of bytea -- but that seems worth\nfixing too). This also has the merit of making the unsafe \"output\"\nvariant into the special case.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Sun, 17 Jan 2021 15:10:43 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 18/01/2021 01:10, Peter Geoghegan wrote:\n> On Sun, Jan 17, 2021 at 3:04 PM Peter Geoghegan <pg@bowt.ie> wrote:\n>> I personally agree with you - it's not like there aren't other ways\n>> for superusers to crash the server (most of which seem very similar to\n>> this gist_page_items() issue, in fact). I just think that it's worth\n>> being clear about that being a trade-off that we've accepted.\n> \n> Can we rename gist_page_items_bytea() to gist_page_items(), and at the\n> same time rename the current gist_page_items() -- perhaps call it\n> gist_page_items_output()?\n> \n> That way we could add a bt_page_items_output() function later, while\n> leaving everything consistent (actually not quite, since\n> bt_page_items() outputs text instead of bytea -- but that seems worth\n> fixing too). This also has the merit of making the unsafe \"output\"\n> variant into the special case.\n\nbt_page_items() and bt_page_items_bytea() exist already. And \nbrin_page_items() also calls the output functions (there's no bytea \nversion of that). Perhaps it would've been better to make the \nbytea-variants the default, but I'm afraid that ship has already sailed.\n\nWe're not terribly consistent; heap_page_items(), hash_page_items() and \ngin_page_items() don't attempt to call the output functions.\n\nThen again, I don't think we need to worry much about backwards \ncompatibility in pageinspect, so I guess we could rename them all. It \ndoesn't bother me enough to make me do it, but I won't object if you \nwant to.\n\n- Heikki\n\n\n", "msg_date": "Mon, 18 Jan 2021 14:40:02 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Mon, Jan 18, 2021 at 3:52 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n\n> On 18/01/2021 00:35, Peter Geoghegan wrote:\n> > On Sun, Jan 17, 2021 at 12:50 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> I noticed that gist_page_items() thinks it can hold inter_call_data->rel\n> >> open across a series of calls. That's completely unsafe: the executor\n> >> might not run the call series to completion (see LIMIT), resulting in\n> >> relcache leak complaints.\n>\n> Fixed, thanks! I changed it to return a tuplestore.\n>\n> > It also has the potential to run into big problems should the user\n> > input a raw page image with an regclass-argument-incompatible tuple\n> > descriptor. Maybe that's okay (this is a tool for experts), but it\n> > certainly is a consideration.\n>\n> I'm not sure I understand. It's true that the raw page image can contain\n> data from a different index, or any garbage really. And the function\n> will behave badly if you do that. That's an accepted risk with\n> pageinspect functions, that's why they're superuser-only, although some\n> of them are more tolerant of corrupt pages than others. The\n> gist_page_items_bytea() variant doesn't try to parse the key data and is\n> less likely to crash on bad input.\n>\n> - Heikki\n>\n>\n> The patch (0001-Add-bool-column-for-LP_DEAF-flag-to-GiST-pageinspect.patch\n)\ndoes not apply successfully and has multiple hanks failed.\n\nhttp://cfbot.cputube.org/patch_32_2824.log\n\npatching file contrib/pageinspect/gistfuncs.c\nHunk #1 FAILED at 151.\nHunk #2 FAILED at 175.\nHunk #3 FAILED at 245.\nHunk #4 FAILED at 271.\n\n...\n\nCan we get a rebase?\n\nI am marking the patch \"Waiting on Author\"\n\n-- \nIbrar Ahmed\n\nOn Mon, Jan 18, 2021 at 3:52 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:On 18/01/2021 00:35, Peter Geoghegan wrote:\n> On Sun, Jan 17, 2021 at 12:50 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I noticed that gist_page_items() thinks it can hold inter_call_data->rel\n>> open across a series of calls.  That's completely unsafe: the executor\n>> might not run the call series to completion (see LIMIT), resulting in\n>> relcache leak complaints.\n\nFixed, thanks! I changed it to return a tuplestore.\n\n> It also has the potential to run into big problems should the user\n> input a raw page image with an regclass-argument-incompatible tuple\n> descriptor. Maybe that's okay (this is a tool for experts), but it\n> certainly is a consideration.\n\nI'm not sure I understand. It's true that the raw page image can contain \ndata from a different index, or any garbage really. And the function \nwill behave badly if you do that. That's an accepted risk with \npageinspect functions, that's why they're superuser-only, although some \nof them are more tolerant of corrupt pages than others. The \ngist_page_items_bytea() variant doesn't try to parse the key data and is \nless likely to crash on bad input.\n\n- Heikki\n\n\nThe patch (0001-Add-bool-column-for-LP_DEAF-flag-to-GiST-pageinspect.patch) does not apply successfully and has multiple hanks failed. http://cfbot.cputube.org/patch_32_2824.logpatching file contrib/pageinspect/gistfuncs.c\nHunk #1 FAILED at 151.\nHunk #2 FAILED at 175.\nHunk #3 FAILED at 245.\nHunk #4 FAILED at 271....Can we get a rebase? I am marking the patch \"Waiting on Author\"-- Ibrar Ahmed", "msg_date": "Mon, 8 Mar 2021 19:41:16 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Mon, Mar 8, 2021 at 6:41 AM Ibrar Ahmed <ibrar.ahmad@gmail.com> wrote:\n> The patch (0001-Add-bool-column-for-LP_DEAF-flag-to-GiST-pageinspect.patch)\n> does not apply successfully and has multiple hanks failed.\n\nThat's because it was committed.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 8 Mar 2021 07:59:01 -0800", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On Mon, Mar 8, 2021 at 8:59 PM Peter Geoghegan <pg@bowt.ie> wrote:\n\n> On Mon, Mar 8, 2021 at 6:41 AM Ibrar Ahmed <ibrar.ahmad@gmail.com> wrote:\n> > The patch\n> (0001-Add-bool-column-for-LP_DEAF-flag-to-GiST-pageinspect.patch)\n> > does not apply successfully and has multiple hanks failed.\n>\n> That's because it was committed.\n>\n> Thanks for the clarification, its status was not changed which confused me\n:)\n\n\n\n> --\n> Peter Geoghegan\n>\n\n\n-- \nIbrar Ahmed\n\nOn Mon, Mar 8, 2021 at 8:59 PM Peter Geoghegan <pg@bowt.ie> wrote:On Mon, Mar 8, 2021 at 6:41 AM Ibrar Ahmed <ibrar.ahmad@gmail.com> wrote:\n> The patch (0001-Add-bool-column-for-LP_DEAF-flag-to-GiST-pageinspect.patch)\n> does not apply successfully and has multiple hanks failed.\n\nThat's because it was committed.\nThanks for the clarification, its status was not changed which confused me :)  \n-- \nPeter Geoghegan\n-- Ibrar Ahmed", "msg_date": "Mon, 8 Mar 2021 21:15:53 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Thanks, Ibrar!\n\n> 8 марта 2021 г., в 21:15, Ibrar Ahmed <ibrar.ahmad@gmail.com> написал(а):\n> \n> \n> \n> On Mon, Mar 8, 2021 at 8:59 PM Peter Geoghegan <pg@bowt.ie> wrote:\n> On Mon, Mar 8, 2021 at 6:41 AM Ibrar Ahmed <ibrar.ahmad@gmail.com> wrote:\n> > The patch (0001-Add-bool-column-for-LP_DEAF-flag-to-GiST-pageinspect.patch)\n> > does not apply successfully and has multiple hanks failed.\n> \n> That's because it was committed.\n> \n> Thanks for the clarification, its status was not changed which confused me :)\n> \n\nThere were numerous GiST-build-related patches in this thread. Yet uncommitted is a patch with sortsupport routines for btree_gist contrib module.\nHere's its version which needs review.\n\nThanks for bringing this up!\n\nBest regards, Andrey Borodin.", "msg_date": "Mon, 8 Mar 2021 22:06:32 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 08/03/2021 19:06, Andrey Borodin wrote:\n> There were numerous GiST-build-related patches in this thread. Yet uncommitted is a patch with sortsupport routines for btree_gist contrib module.\n> Here's its version which needs review.\n\nReviewing this now again. One thing caught my eye:\n\n> +static int\n> +gbt_bit_sort_build_cmp(Datum a, Datum b, SortSupport ssup)\n> +{\n> +\treturn DatumGetInt32(DirectFunctionCall2(byteacmp,\n> +\t\t\t\t\t\t\t\t\t\t\t PointerGetDatum(a),\n> +\t\t\t\t\t\t\t\t\t\t\t PointerGetDatum(b)));\n> +}\n\nThat doesn't quite match the sort order used by the comparison \nfunctions, gbt_bitlt and such. The comparison functions compare the bits \nfirst, and use the length as a tie-breaker. Using byteacmp() will \ncompare the \"bit length\" first. However, gbt_bitcmp() also uses \nbyteacmp(), so I'm a bit confused. So, huh?\n\n- Heikki\n\n\n", "msg_date": "Wed, 7 Apr 2021 09:00:10 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 07/04/2021 09:00, Heikki Linnakangas wrote:\n> On 08/03/2021 19:06, Andrey Borodin wrote:\n>> There were numerous GiST-build-related patches in this thread. Yet uncommitted is a patch with sortsupport routines for btree_gist contrib module.\n>> Here's its version which needs review.\n\nCommitted with small fixes. I changed the all functions to use \n*GetDatum() and DatumGet*() macros, instead of just comparing Datums \nwith < and >. Datum is unsigned, while int2, int4, int8 and money are \nsigned, so that changes the sort order around 0 for those types to be \nthe same as the picksplit and picksplit functions use. Not a correctness \nissue, the sorting only affects the quality of the index, but let's be tidy.\n\nThis issue remains:\n\n> Reviewing this now again. One thing caught my eye:\n> \n>> +static int\n>> +gbt_bit_sort_build_cmp(Datum a, Datum b, SortSupport ssup)\n>> +{\n>> +\treturn DatumGetInt32(DirectFunctionCall2(byteacmp,\n>> +\t\t\t\t\t\t\t\t\t\t\t PointerGetDatum(a),\n>> +\t\t\t\t\t\t\t\t\t\t\t PointerGetDatum(b)));\n>> +}\n> \n> That doesn't quite match the sort order used by the comparison\n> functions, gbt_bitlt and such. The comparison functions compare the bits\n> first, and use the length as a tie-breaker. Using byteacmp() will\n> compare the \"bit length\" first. However, gbt_bitcmp() also uses\n> byteacmp(), so I'm a bit confused. So, huh?\n\nSince we used byteacmp() previously for picksplit, too, this is \nconsistent with the order you got previously. It still seems wrong to me \nand should be investigated, but it doesn't need to block this patch.\n\n- Heikki\n\n\n", "msg_date": "Wed, 7 Apr 2021 13:23:42 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 07/04/2021 09:00, Heikki Linnakangas wrote:\n> On 08/03/2021 19:06, Andrey Borodin wrote:\n>> There were numerous GiST-build-related patches in this thread. Yet uncommitted is a patch with sortsupport routines for btree_gist contrib module.\n>> Here's its version which needs review.\n> \n> Reviewing this now again. One thing caught my eye:\n> \n>> +static int\n>> +gbt_bit_sort_build_cmp(Datum a, Datum b, SortSupport ssup)\n>> +{\n>> +\treturn DatumGetInt32(DirectFunctionCall2(byteacmp,\n>> +\t\t\t\t\t\t\t\t\t\t\t PointerGetDatum(a),\n>> +\t\t\t\t\t\t\t\t\t\t\t PointerGetDatum(b)));\n>> +}\n> \n> That doesn't quite match the sort order used by the comparison\n> functions, gbt_bitlt and such. The comparison functions compare the bits\n> first, and use the length as a tie-breaker. Using byteacmp() will\n> compare the \"bit length\" first. However, gbt_bitcmp() also uses\n> byteacmp(), so I'm a bit confused. So, huh?\n\nOk, I think I understand that now. In btree_gist, the *_cmp() function \noperates on non-leaf values, and *_lt(), *_gt() et al operate on leaf \nvalues. For all other datatypes, the leaf and non-leaf representation is \nthe same, but for bit/varbit, the non-leaf representation is different. \nThe leaf representation is VarBit, and non-leaf is just the bits without \nthe 'bit_len' field. That's why it is indeed correct for gbt_bitcmp() to \njust use byteacmp(), whereas gbt_bitlt() et al compares the 'bit_len' \nfield separately. That's subtle, and 100% uncommented.\n\nWhat that means for this patch is that gbt_bit_sort_build_cmp() should \n*not* call byteacmp(), but bitcmp(). Because it operates on the original \ndatatype stored in the table.\n\n- Heikki\n\n\n", "msg_date": "Wed, 7 Apr 2021 14:56:42 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 7 апр. 2021 г., в 13:23, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> Committed with small fixes.\n\nThanks!\n\n> 7 апр. 2021 г., в 14:56, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n> Ok, I think I understand that now. In btree_gist, the *_cmp() function operates on non-leaf values, and *_lt(), *_gt() et al operate on leaf values. For all other datatypes, the leaf and non-leaf representation is the same, but for bit/varbit, the non-leaf representation is different. The leaf representation is VarBit, and non-leaf is just the bits without the 'bit_len' field. That's why it is indeed correct for gbt_bitcmp() to just use byteacmp(), whereas gbt_bitlt() et al compares the 'bit_len' field separately. That's subtle, and 100% uncommented.\n> \n> What that means for this patch is that gbt_bit_sort_build_cmp() should *not* call byteacmp(), but bitcmp(). Because it operates on the original datatype stored in the table.\n\n+1\nThanks for investigating this.\nIf I understand things right, adding test values with different lengths of bit sequences would not uncover the problem anyway?\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Wed, 7 Apr 2021 15:12:21 +0300", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 07/04/2021 15:12, Andrey Borodin wrote:\n>> 7 апр. 2021 г., в 14:56, Heikki Linnakangas <hlinnaka@iki.fi>\n>> написал(а):\n>> \n>> Ok, I think I understand that now. In btree_gist, the *_cmp()\n>> function operates on non-leaf values, and *_lt(), *_gt() et al\n>> operate on leaf values. For all other datatypes, the leaf and\n>> non-leaf representation is the same, but for bit/varbit, the\n>> non-leaf representation is different. The leaf representation is\n>> VarBit, and non-leaf is just the bits without the 'bit_len' field.\n>> That's why it is indeed correct for gbt_bitcmp() to just use\n>> byteacmp(), whereas gbt_bitlt() et al compares the 'bit_len' field\n>> separately. That's subtle, and 100% uncommented.\n>> \n>> What that means for this patch is that gbt_bit_sort_build_cmp()\n>> should *not* call byteacmp(), but bitcmp(). Because it operates on\n>> the original datatype stored in the table.\n> \n> +1 Thanks for investigating this. If I understand things right,\n> adding test values with different lengths of bit sequences would not\n> uncover the problem anyway?\n\nThat's right, the only consequence of a \"wrong\" sort order is that the \nquality of the tree suffers, and scans need to scan more pages \nunnecessarily.\n\nI tried to investigate this by creating a varbit index with and without \nsorting, and compared them with pageinspect, but in quick testing, I \nwasn't able to find cases where the sorted version was badly ordered. I \nguess I didn't find the right data set yet.\n\n- Heikki\n\n\n", "msg_date": "Wed, 7 Apr 2021 16:18:53 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 7 апр. 2021 г., в 16:18, Heikki Linnakangas <hlinnaka@iki.fi> написал(а):\n> \n\nI see there is a problem with \"SET client_min_messages = DEBUG1;\" on buildfarm. I think these checks were necessary to make sure test paths are triggered. When we know that code paths are tested, maybe we can omit checks?\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Wed, 7 Apr 2021 22:41:29 +0300", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "On 07/04/2021 22:41, Andrey Borodin wrote:\n> I see there is a problem with \"SET client_min_messages = DEBUG1;\" on\n> buildfarm. I think these checks were necessary to make sure test\n> paths are triggered. When we know that code paths are tested, maybe\n> we can omit checks?\nYeah. We don't have very reliable coverage of different GiST build \nmethods, as noted earlier in this thread. But that's not this patch's fault.\n\nI've been investigating the varbit issue, and realized that all the \ncomparison functions in this patch for varlen datatypes are broken. The \nrepresentation that the sortsupport function sees is the one that the \n'compress' function returns. The fixed-length versions got this right, \nbut the varlen versions assume that the input is a Datum of the original \ndatatype. It happens to not crash, because the representation returned \nby gbt_var_compress() is also a varlena, and all of the comparison \nfunctions tolerate the garbage inputs, but it's bogus. The correct \npattern would be something like this (without the debugging NOTICE, of \ncourse):\n\n> static int\n> gbt_text_sort_build_cmp(Datum a, Datum b, SortSupport ssup)\n> {\n> \tGBT_VARKEY_R ra = gbt_var_key_readable((GBT_VARKEY *) PG_DETOAST_DATUM(a));\n> \tGBT_VARKEY_R rb = gbt_var_key_readable((GBT_VARKEY *) PG_DETOAST_DATUM(b));\n> \n> \tint x = DatumGetInt32(DirectFunctionCall2Coll(bttextcmp,\n> \t\t\t\t\t\t\t\t\t\t\t\t ssup->ssup_collation,\n> \t\t\t\t\t\t\t\t\t\t\t\t PointerGetDatum(a),\n> \t\t\t\t\t\t\t\t\t\t\t\t PointerGetDatum(b)));\n> \telog(NOTICE, \"cmp: %s vs %s: %d\",\n> \t\t TextDatumGetCString(ra.lower),\n> \t\t TextDatumGetCString(rb.lower),\n> \t\t x);\n> \treturn x;\n> }\n- Heikki\n\n\n", "msg_date": "Wed, 7 Apr 2021 23:18:26 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Thanks for the investigation, Heikki.\n\n> 8 апр. 2021 г., в 01:18, Heikki Linnakangas <hlinnaka@iki.fi> написThe correct pattern would be something like this (without the debugging NOTICE, of course):\n> \n>> static int\n>> gbt_text_sort_build_cmp(Datum a, Datum b, SortSupport ssup)\n>> {\n>> \tGBT_VARKEY_R ra = gbt_var_key_readable((GBT_VARKEY *) PG_DETOAST_DATUM(a));\n>> \tGBT_VARKEY_R rb = gbt_var_key_readable((GBT_VARKEY *) PG_DETOAST_DATUM(b));\n>> \tint x = DatumGetInt32(DirectFunctionCall2Coll(bttextcmp,\n>> \t\t\t\t\t\t\t\t\t\t\t\t ssup->ssup_collation,\n>> \t\t\t\t\t\t\t\t\t\t\t\t PointerGetDatum(a),\n>> \t\t\t\t\t\t\t\t\t\t\t\t PointerGetDatum(b)));\n>> \telog(NOTICE, \"cmp: %s vs %s: %d\",\n>> \t\t TextDatumGetCString(ra.lower),\n>> \t\t TextDatumGetCString(rb.lower),\n>> \t\t x);\n>> \treturn x;\n>> }\n> \n\nIn this pattern I flipped PointerGetDatum(a) to PointerGetDatum(ra.lower), because it seems to me correct. I've followed rule of thumb: every sort function must extract and user \"lower\" somehow. Though I suspect numeric a bit. Is it regular varlena?\nPFA patchset with v6 intact + two fixes of discovered issues.\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Fri, 7 May 2021 18:05:41 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "I tried reviewing the remaining patches. It seems to work correctly,\nand passes the tests on my laptop.\n\n> In this pattern I flipped PointerGetDatum(a) to PointerGetDatum(ra.lower), because it seems to me correct. I've followed rule of thumb: every sort function must extract and use \"lower\" somehow. Though I suspect numeric a bit. Is it regular varlena?\n\nAs far as I understand, we cannot use the sortsupport functions from\nthe btree operator classes because the btree_gist extension handles\nthings differently. This is unfortunate and a source of bugs [1], but\nwe cannot do anything about it.\n\nGiven that the lower and upper datums must be the same for the leaf\nnodes, it makes sense to me to compare one of them.\n\nUsing numeric_cmp() for numeric in line with using bttextcmp() for text.\n\n> + /*\n> + * Numeric has abbreviation routines in numeric.c, but we don't try to use\n> + * them here. Maybe later.\n> + */\n\nThis is also true for text. Perhaps we should also add a comment there.\n\n> PFA patchset with v6 intact + two fixes of discovered issues.\n\n> + /* Use byteacmp(), like gbt_bitcmp() does */\n\nWe can improve this comment by incorporating Heikki's previous email:\n\n> Ok, I think I understand that now. In btree_gist, the *_cmp() function\n> operates on non-leaf values, and *_lt(), *_gt() et al operate on leaf\n> values. For all other datatypes, the leaf and non-leaf representation is\n> the same, but for bit/varbit, the non-leaf representation is different.\n> The leaf representation is VarBit, and non-leaf is just the bits without\n> the 'bit_len' field. That's why it is indeed correct for gbt_bitcmp() to\n> just use byteacmp(), whereas gbt_bitlt() et al compares the 'bit_len'\n> field separately. That's subtle, and 100% uncommented.\n\nI think patch number 3 should be squashed to patch number 1.\n\nI couldn't understand patch number 2 \"Remove DEBUG1 verification\". It\nseems like something rather useful.\n\n[1] https://www.postgresql.org/message-id/flat/201010112055.o9BKtZf7011251%40wwwmaster.postgresql.org\n\n\n", "msg_date": "Mon, 5 Jul 2021 09:27:50 +0300", "msg_from": "Emre Hasegeli <emre@hasegeli.com>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "> On 5 Jul 2021, at 08:27, Emre Hasegeli <emre@hasegeli.com> wrote:\n\n> ...\n> \n> I couldn't understand patch number 2 \"Remove DEBUG1 verification\". It\n> seems like something rather useful.\n\nThese questions have gone unanswered since July, and the patch fails to apply\nanymore. Is there an updated version on the way?\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Wed, 17 Nov 2021 14:33:41 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "\n\n> 17 нояб. 2021 г., в 16:33, Daniel Gustafsson <daniel@yesql.se> написал(а):\n> \n>> On 5 Jul 2021, at 08:27, Emre Hasegeli <emre@hasegeli.com> wrote:\n> \n>> ...\n>> \n>> I couldn't understand patch number 2 \"Remove DEBUG1 verification\". It\n>> seems like something rather useful.\n\nEmre, thanks for the review! And sorry for this delay. Properly answering questions is still in my queue.\n\n> \n> These questions have gone unanswered since July, and the patch fails to apply\n> anymore. Is there an updated version on the way?\n\nYes. In future versions I also want to address IOS vs pinned buffers issue[0]. And, probably, sort items on leaf pages. And, maybe, split pages more intelligently.\nI hope to get to this in December.\n\nI'll post rebased version ASAP.\n\nBest regards, Andrey Borodin.\n\n[0] https://www.postgresql.org/message-id/CAH2-Wz=PqOziyRSrnN5jAtfXWXY7-BJcHz9S355LH8Dt=5qxWQ@mail.gmail.com\n\n", "msg_date": "Thu, 25 Nov 2021 16:38:01 +0300", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" }, { "msg_contents": "Hi Emre!\n\nThank you for the review.\n\n> I tried reviewing the remaining patches. It seems to work correctly,\n> and passes the tests on my laptop.\n> \n>> In this pattern I flipped PointerGetDatum(a) to PointerGetDatum(ra.lower), because it seems to me correct. I've followed rule of thumb: every sort function must extract and use \"lower\" somehow. Though I suspect numeric a bit. Is it regular varlena?\n> \n> As far as I understand, we cannot use the sortsupport functions from\n> the btree operator classes because the btree_gist extension handles\n> things differently. This is unfortunate and a source of bugs [1], but\n> we cannot do anything about it.\n> \n> Given that the lower and upper datums must be the same for the leaf\n> nodes, it makes sense to me to compare one of them.\n> \n> Using numeric_cmp() for numeric in line with using bttextcmp() for text.\nOK.\n\n>> + /*\n>> + * Numeric has abbreviation routines in numeric.c, but we don't try to use\n>> + * them here. Maybe later.\n>> + */\n> \n> This is also true for text. Perhaps we should also add a comment there.\nDone.\n\n> \n>> PFA patchset with v6 intact + two fixes of discovered issues.\n> \n>> + /* Use byteacmp(), like gbt_bitcmp() does */\n> \n> We can improve this comment by incorporating Heikki's previous email:\n> \n>> Ok, I think I understand that now. In btree_gist, the *_cmp() function\n>> operates on non-leaf values, and *_lt(), *_gt() et al operate on leaf\n>> values. For all other datatypes, the leaf and non-leaf representation is\n>> the same, but for bit/varbit, the non-leaf representation is different.\n>> The leaf representation is VarBit, and non-leaf is just the bits without\n>> the 'bit_len' field. That's why it is indeed correct for gbt_bitcmp() to\n>> just use byteacmp(), whereas gbt_bitlt() et al compares the 'bit_len'\n>> field separately. That's subtle, and 100% uncommented.\n> \nDone.\n\n> I think patch number 3 should be squashed to patch number 1.\nAll patches in the patchset expected to be squashed into 1 during commit.\n\n> \n> I couldn't understand patch number 2 \"Remove DEBUG1 verification\". It\n> seems like something rather useful.\nIf failed on buildfarm on some nodes. There were somewhat extroneous error messages.\nCurrently Step 1 and 2 are separete to ensure that opclasses are used correctly.\n\nThanks!\n\nBest regards, Andrey Borodin.", "msg_date": "Thu, 16 Dec 2021 14:18:52 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": true, "msg_subject": "Re: Yet another fast GiST build" } ]
[ { "msg_contents": "Hi All,\n\nTo generate partitionwise join, we need to make sure there exists an\nequi-join condition for each pair of partition keys, which is performed\nby have_partkey_equi_join(). This makes sense and works well.\n\nBut if, let's say, one certain pair of partition keys (foo.k = bar.k)\nhas formed an equivalence class containing consts, no join clause would\nbe generated for it, since we have already generated 'foo.k = const' and\n'bar.k = const' and pushed them into the proper restrictions earlier.\n\nThis will make partitionwise join fail to be planned if there are\nmultiple partition keys and the pushed-down restrictions 'xxx = const'\nfail to prune away any partitions.\n\nConsider the examples below:\n\ncreate table p (k1 int, k2 int, val int) partition by range(k1,k2);\ncreate table p_1 partition of p for values from (1,1) to (10,100);\ncreate table p_2 partition of p for values from (10,100) to (20,200);\n\nIf we are joining on each pair of partition keys, we can generate\npartitionwise join:\n\n# explain (costs off)\nselect * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 = bar.k2;\n QUERY PLAN\n----------------------------------------------------------------------\n Append\n -> Hash Join\n Hash Cond: ((foo.k1 = bar.k1) AND (foo.k2 = bar.k2))\n -> Seq Scan on p_1 foo\n -> Hash\n -> Seq Scan on p_1 bar\n -> Hash Join\n Hash Cond: ((foo_1.k1 = bar_1.k1) AND (foo_1.k2 = bar_1.k2))\n -> Seq Scan on p_2 foo_1\n -> Hash\n -> Seq Scan on p_2 bar_1\n(11 rows)\n\nBut if we add another qual 'foo.k2 = const', we will be unable to\ngenerate partitionwise join any more, because have_partkey_equi_join()\nthinks not every partition key has an equi-join condition.\n\n# explain (costs off)\nselect * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 = bar.k2\nand foo.k2 = 16;\n QUERY PLAN\n-----------------------------------------\n Hash Join\n Hash Cond: (foo.k1 = bar.k1)\n -> Append\n -> Seq Scan on p_1 foo\n Filter: (k2 = 16)\n -> Seq Scan on p_2 foo_1\n Filter: (k2 = 16)\n -> Hash\n -> Append\n -> Seq Scan on p_1 bar\n Filter: (k2 = 16)\n -> Seq Scan on p_2 bar_1\n Filter: (k2 = 16)\n(13 rows)\n\nIs this a problem?\n\nThanks\nRichard\n\nHi All,To generate partitionwise join, we need to make sure there exists anequi-join condition for each pair of partition keys, which is performedby have_partkey_equi_join(). This makes sense and works well.But if, let's say, one certain pair of partition keys (foo.k = bar.k)has formed an equivalence class containing consts, no join clause wouldbe generated for it, since we have already generated 'foo.k = const' and'bar.k = const' and pushed them into the proper restrictions earlier.This will make partitionwise join fail to be planned if there aremultiple partition keys and the pushed-down restrictions 'xxx = const'fail to prune away any partitions.Consider the examples below:create table p (k1 int, k2 int, val int) partition by range(k1,k2);create table p_1 partition of p for values from (1,1) to (10,100);create table p_2 partition of p for values from (10,100) to (20,200);If we are joining on each pair of partition keys, we can generatepartitionwise join:# explain (costs off)select * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 = bar.k2;                              QUERY PLAN---------------------------------------------------------------------- Append   ->  Hash Join         Hash Cond: ((foo.k1 = bar.k1) AND (foo.k2 = bar.k2))         ->  Seq Scan on p_1 foo         ->  Hash               ->  Seq Scan on p_1 bar   ->  Hash Join         Hash Cond: ((foo_1.k1 = bar_1.k1) AND (foo_1.k2 = bar_1.k2))         ->  Seq Scan on p_2 foo_1         ->  Hash               ->  Seq Scan on p_2 bar_1(11 rows)But if we add another qual 'foo.k2 = const', we will be unable togenerate partitionwise join any more, because have_partkey_equi_join()thinks not every partition key has an equi-join condition.# explain (costs off)select * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 = bar.k2 and foo.k2 = 16;               QUERY PLAN----------------------------------------- Hash Join   Hash Cond: (foo.k1 = bar.k1)   ->  Append         ->  Seq Scan on p_1 foo               Filter: (k2 = 16)         ->  Seq Scan on p_2 foo_1               Filter: (k2 = 16)   ->  Hash         ->  Append               ->  Seq Scan on p_1 bar                     Filter: (k2 = 16)               ->  Seq Scan on p_2 bar_1                     Filter: (k2 = 16)(13 rows)Is this a problem?ThanksRichard", "msg_date": "Mon, 26 Aug 2019 17:32:48 +0800", "msg_from": "Richard Guo <riguo@pivotal.io>", "msg_from_op": true, "msg_subject": "A problem about partitionwise join" }, { "msg_contents": "Hi Richard,\n\nOn Mon, Aug 26, 2019 at 6:33 PM Richard Guo <riguo@pivotal.io> wrote:\n>\n> Hi All,\n>\n> To generate partitionwise join, we need to make sure there exists an\n> equi-join condition for each pair of partition keys, which is performed\n> by have_partkey_equi_join(). This makes sense and works well.\n>\n> But if, let's say, one certain pair of partition keys (foo.k = bar.k)\n> has formed an equivalence class containing consts, no join clause would\n> be generated for it, since we have already generated 'foo.k = const' and\n> 'bar.k = const' and pushed them into the proper restrictions earlier.\n>\n> This will make partitionwise join fail to be planned if there are\n> multiple partition keys and the pushed-down restrictions 'xxx = const'\n> fail to prune away any partitions.\n>\n> Consider the examples below:\n>\n> create table p (k1 int, k2 int, val int) partition by range(k1,k2);\n> create table p_1 partition of p for values from (1,1) to (10,100);\n> create table p_2 partition of p for values from (10,100) to (20,200);\n>\n> If we are joining on each pair of partition keys, we can generate\n> partitionwise join:\n>\n> # explain (costs off)\n> select * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 = bar.k2;\n> QUERY PLAN\n> ----------------------------------------------------------------------\n> Append\n> -> Hash Join\n> Hash Cond: ((foo.k1 = bar.k1) AND (foo.k2 = bar.k2))\n> -> Seq Scan on p_1 foo\n> -> Hash\n> -> Seq Scan on p_1 bar\n> -> Hash Join\n> Hash Cond: ((foo_1.k1 = bar_1.k1) AND (foo_1.k2 = bar_1.k2))\n> -> Seq Scan on p_2 foo_1\n> -> Hash\n> -> Seq Scan on p_2 bar_1\n> (11 rows)\n>\n> But if we add another qual 'foo.k2 = const', we will be unable to\n> generate partitionwise join any more, because have_partkey_equi_join()\n> thinks not every partition key has an equi-join condition.\n>\n> # explain (costs off)\n> select * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 = bar.k2 and foo.k2 = 16;\n> QUERY PLAN\n> -----------------------------------------\n> Hash Join\n> Hash Cond: (foo.k1 = bar.k1)\n> -> Append\n> -> Seq Scan on p_1 foo\n> Filter: (k2 = 16)\n> -> Seq Scan on p_2 foo_1\n> Filter: (k2 = 16)\n> -> Hash\n> -> Append\n> -> Seq Scan on p_1 bar\n> Filter: (k2 = 16)\n> -> Seq Scan on p_2 bar_1\n> Filter: (k2 = 16)\n> (13 rows)\n>\n> Is this a problem?\n\nPerhaps. Maybe it has to do with the way have_partkey_equi_join() has\nbeen coded. If it was coded such that it figured out on its own that\nthe equivalence (foo.k2, bar.k2, ...) does exist, then that would\nallow partitionwise join to occur, which I think would be OK to do.\nBut maybe I'm missing something.\n\nThanks,\nAmit\n\n\n", "msg_date": "Tue, 27 Aug 2019 09:51:36 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Tue, Aug 27, 2019 at 8:51 AM Amit Langote <amitlangote09@gmail.com>\nwrote:\n\n> Hi Richard,\n>\n> On Mon, Aug 26, 2019 at 6:33 PM Richard Guo <riguo@pivotal.io> wrote:\n> >\n> > Hi All,\n> >\n> > To generate partitionwise join, we need to make sure there exists an\n> > equi-join condition for each pair of partition keys, which is performed\n> > by have_partkey_equi_join(). This makes sense and works well.\n> >\n> > But if, let's say, one certain pair of partition keys (foo.k = bar.k)\n> > has formed an equivalence class containing consts, no join clause would\n> > be generated for it, since we have already generated 'foo.k = const' and\n> > 'bar.k = const' and pushed them into the proper restrictions earlier.\n> >\n> > This will make partitionwise join fail to be planned if there are\n> > multiple partition keys and the pushed-down restrictions 'xxx = const'\n> > fail to prune away any partitions.\n> >\n> > Consider the examples below:\n> >\n> > create table p (k1 int, k2 int, val int) partition by range(k1,k2);\n> > create table p_1 partition of p for values from (1,1) to (10,100);\n> > create table p_2 partition of p for values from (10,100) to (20,200);\n> >\n> > If we are joining on each pair of partition keys, we can generate\n> > partitionwise join:\n> >\n> > # explain (costs off)\n> > select * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 =\n> bar.k2;\n> > QUERY PLAN\n> > ----------------------------------------------------------------------\n> > Append\n> > -> Hash Join\n> > Hash Cond: ((foo.k1 = bar.k1) AND (foo.k2 = bar.k2))\n> > -> Seq Scan on p_1 foo\n> > -> Hash\n> > -> Seq Scan on p_1 bar\n> > -> Hash Join\n> > Hash Cond: ((foo_1.k1 = bar_1.k1) AND (foo_1.k2 = bar_1.k2))\n> > -> Seq Scan on p_2 foo_1\n> > -> Hash\n> > -> Seq Scan on p_2 bar_1\n> > (11 rows)\n> >\n> > But if we add another qual 'foo.k2 = const', we will be unable to\n> > generate partitionwise join any more, because have_partkey_equi_join()\n> > thinks not every partition key has an equi-join condition.\n> >\n> > # explain (costs off)\n> > select * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 =\n> bar.k2 and foo.k2 = 16;\n> > QUERY PLAN\n> > -----------------------------------------\n> > Hash Join\n> > Hash Cond: (foo.k1 = bar.k1)\n> > -> Append\n> > -> Seq Scan on p_1 foo\n> > Filter: (k2 = 16)\n> > -> Seq Scan on p_2 foo_1\n> > Filter: (k2 = 16)\n> > -> Hash\n> > -> Append\n> > -> Seq Scan on p_1 bar\n> > Filter: (k2 = 16)\n> > -> Seq Scan on p_2 bar_1\n> > Filter: (k2 = 16)\n> > (13 rows)\n> >\n> > Is this a problem?\n>\n> Perhaps. Maybe it has to do with the way have_partkey_equi_join() has\n> been coded. If it was coded such that it figured out on its own that\n> the equivalence (foo.k2, bar.k2, ...) does exist, then that would\n> allow partitionwise join to occur, which I think would be OK to do.\n> But maybe I'm missing something.\n>\n>\nThis should be caused by how we deduce join clauses from equivalence\nclasses. ECs containing consts will not be considered so we cannot\ngenerate (foo.k2 = bar.k2) for the query above.\n\nIn addition, when generating join clauses from equivalence classes, we\nonly select the joinclause with the 'best score', or the first\njoinclause with a score of 3. This may make us miss some joinclause on\npartition keys.\n\nCheck the query below as a more illustrative example:\n\ncreate table p (k int, val int) partition by range(k);\ncreate table p_1 partition of p for values from (1) to (10);\ncreate table p_2 partition of p for values from (10) to (100);\n\nIf we use quals 'foo.k = bar.k and foo.k = bar.val', we can generate\npartitionwise join:\n\n# explain (costs off)\nselect * from p as foo join p as bar on foo.k = bar.k and foo.k = bar.val;\n QUERY PLAN\n-----------------------------------------\n Append\n -> Hash Join\n Hash Cond: (foo.k = bar.k)\n -> Seq Scan on p_1 foo\n -> Hash\n -> Seq Scan on p_1 bar\n Filter: (k = val)\n -> Hash Join\n Hash Cond: (foo_1.k = bar_1.k)\n -> Seq Scan on p_2 foo_1\n -> Hash\n -> Seq Scan on p_2 bar_1\n Filter: (k = val)\n(13 rows)\n\nBut if we exchange the order of the two quals to 'foo.k = bar.val and\nfoo.k = bar.k', then partitionwise join cannot be generated any more,\nbecause we only have joinclause 'foo.k = bar.val' as it first reached\nscore of 3. We have missed the joinclause on the partition key although\nit does exist.\n\n# explain (costs off)\nselect * from p as foo join p as bar on foo.k = bar.val and foo.k = bar.k;\n QUERY PLAN\n-----------------------------------------\n Hash Join\n Hash Cond: (foo.k = bar.val)\n -> Append\n -> Seq Scan on p_1 foo\n -> Seq Scan on p_2 foo_1\n -> Hash\n -> Append\n -> Seq Scan on p_1 bar\n Filter: (val = k)\n -> Seq Scan on p_2 bar_1\n Filter: (val = k)\n(11 rows)\n\nThanks\nRichard\n\nOn Tue, Aug 27, 2019 at 8:51 AM Amit Langote <amitlangote09@gmail.com> wrote:Hi Richard,\n\nOn Mon, Aug 26, 2019 at 6:33 PM Richard Guo <riguo@pivotal.io> wrote:\n>\n> Hi All,\n>\n> To generate partitionwise join, we need to make sure there exists an\n> equi-join condition for each pair of partition keys, which is performed\n> by have_partkey_equi_join(). This makes sense and works well.\n>\n> But if, let's say, one certain pair of partition keys (foo.k = bar.k)\n> has formed an equivalence class containing consts, no join clause would\n> be generated for it, since we have already generated 'foo.k = const' and\n> 'bar.k = const' and pushed them into the proper restrictions earlier.\n>\n> This will make partitionwise join fail to be planned if there are\n> multiple partition keys and the pushed-down restrictions 'xxx = const'\n> fail to prune away any partitions.\n>\n> Consider the examples below:\n>\n> create table p (k1 int, k2 int, val int) partition by range(k1,k2);\n> create table p_1 partition of p for values from (1,1) to (10,100);\n> create table p_2 partition of p for values from (10,100) to (20,200);\n>\n> If we are joining on each pair of partition keys, we can generate\n> partitionwise join:\n>\n> # explain (costs off)\n> select * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 = bar.k2;\n>                               QUERY PLAN\n> ----------------------------------------------------------------------\n>  Append\n>    ->  Hash Join\n>          Hash Cond: ((foo.k1 = bar.k1) AND (foo.k2 = bar.k2))\n>          ->  Seq Scan on p_1 foo\n>          ->  Hash\n>                ->  Seq Scan on p_1 bar\n>    ->  Hash Join\n>          Hash Cond: ((foo_1.k1 = bar_1.k1) AND (foo_1.k2 = bar_1.k2))\n>          ->  Seq Scan on p_2 foo_1\n>          ->  Hash\n>                ->  Seq Scan on p_2 bar_1\n> (11 rows)\n>\n> But if we add another qual 'foo.k2 = const', we will be unable to\n> generate partitionwise join any more, because have_partkey_equi_join()\n> thinks not every partition key has an equi-join condition.\n>\n> # explain (costs off)\n> select * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 = bar.k2 and foo.k2 = 16;\n>                QUERY PLAN\n> -----------------------------------------\n>  Hash Join\n>    Hash Cond: (foo.k1 = bar.k1)\n>    ->  Append\n>          ->  Seq Scan on p_1 foo\n>                Filter: (k2 = 16)\n>          ->  Seq Scan on p_2 foo_1\n>                Filter: (k2 = 16)\n>    ->  Hash\n>          ->  Append\n>                ->  Seq Scan on p_1 bar\n>                      Filter: (k2 = 16)\n>                ->  Seq Scan on p_2 bar_1\n>                      Filter: (k2 = 16)\n> (13 rows)\n>\n> Is this a problem?\n\nPerhaps.  Maybe it has to do with the way have_partkey_equi_join() has\nbeen coded.  If it was coded such that it figured out on its own that\nthe equivalence (foo.k2, bar.k2, ...) does exist, then that would\nallow partitionwise join to occur, which I think would be OK to do.\nBut maybe I'm missing something.This should be caused by how we deduce join clauses from equivalenceclasses. ECs containing consts will not be considered so we cannotgenerate (foo.k2 = bar.k2) for the query above.In addition, when generating join clauses from equivalence classes, weonly select the joinclause with the 'best score', or the firstjoinclause with a score of 3. This may make us miss some joinclause onpartition keys.Check the query below as a more illustrative example:create table p (k int, val int) partition by range(k);create table p_1 partition of p for values from (1) to (10);create table p_2 partition of p for values from (10) to (100);If we use quals 'foo.k = bar.k and foo.k = bar.val', we can generatepartitionwise join:# explain (costs off)select * from p as foo join p as bar on foo.k = bar.k and foo.k = bar.val;               QUERY PLAN----------------------------------------- Append   ->  Hash Join         Hash Cond: (foo.k = bar.k)         ->  Seq Scan on p_1 foo         ->  Hash               ->  Seq Scan on p_1 bar                     Filter: (k = val)   ->  Hash Join         Hash Cond: (foo_1.k = bar_1.k)         ->  Seq Scan on p_2 foo_1         ->  Hash               ->  Seq Scan on p_2 bar_1                     Filter: (k = val)(13 rows)But if we exchange the order of the two quals to 'foo.k = bar.val andfoo.k = bar.k', then partitionwise join cannot be generated any more,because we only have joinclause 'foo.k = bar.val' as it first reachedscore of 3. We have missed the joinclause on the partition key althoughit does exist.# explain (costs off)select * from p as foo join p as bar on foo.k = bar.val and foo.k = bar.k;               QUERY PLAN----------------------------------------- Hash Join   Hash Cond: (foo.k = bar.val)   ->  Append         ->  Seq Scan on p_1 foo         ->  Seq Scan on p_2 foo_1   ->  Hash         ->  Append               ->  Seq Scan on p_1 bar                     Filter: (val = k)               ->  Seq Scan on p_2 bar_1                     Filter: (val = k)(11 rows) ThanksRichard", "msg_date": "Tue, 27 Aug 2019 15:56:59 +0800", "msg_from": "Richard Guo <riguo@pivotal.io>", "msg_from_op": true, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "Hi,\n\nOn Tue, Aug 27, 2019 at 4:57 PM Richard Guo <riguo@pivotal.io> wrote:\n> Check the query below as a more illustrative example:\n>\n> create table p (k int, val int) partition by range(k);\n> create table p_1 partition of p for values from (1) to (10);\n> create table p_2 partition of p for values from (10) to (100);\n>\n> If we use quals 'foo.k = bar.k and foo.k = bar.val', we can generate\n> partitionwise join:\n>\n> # explain (costs off)\n> select * from p as foo join p as bar on foo.k = bar.k and foo.k = bar.val;\n> QUERY PLAN\n> -----------------------------------------\n> Append\n> -> Hash Join\n> Hash Cond: (foo.k = bar.k)\n> -> Seq Scan on p_1 foo\n> -> Hash\n> -> Seq Scan on p_1 bar\n> Filter: (k = val)\n> -> Hash Join\n> Hash Cond: (foo_1.k = bar_1.k)\n> -> Seq Scan on p_2 foo_1\n> -> Hash\n> -> Seq Scan on p_2 bar_1\n> Filter: (k = val)\n> (13 rows)\n>\n> But if we exchange the order of the two quals to 'foo.k = bar.val and\n> foo.k = bar.k', then partitionwise join cannot be generated any more,\n> because we only have joinclause 'foo.k = bar.val' as it first reached\n> score of 3. We have missed the joinclause on the partition key although\n> it does exist.\n>\n> # explain (costs off)\n> select * from p as foo join p as bar on foo.k = bar.val and foo.k = bar.k;\n> QUERY PLAN\n> -----------------------------------------\n> Hash Join\n> Hash Cond: (foo.k = bar.val)\n> -> Append\n> -> Seq Scan on p_1 foo\n> -> Seq Scan on p_2 foo_1\n> -> Hash\n> -> Append\n> -> Seq Scan on p_1 bar\n> Filter: (val = k)\n> -> Seq Scan on p_2 bar_1\n> Filter: (val = k)\n> (11 rows)\n\nI think it would be nice if we can address this issue.\n\nBest regards,\nEtsuro Fujita\n\n\n", "msg_date": "Wed, 28 Aug 2019 19:49:17 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Wed, Aug 28, 2019 at 6:49 PM Etsuro Fujita <etsuro.fujita@gmail.com>\nwrote:\n\n> Hi,\n>\n> On Tue, Aug 27, 2019 at 4:57 PM Richard Guo <riguo@pivotal.io> wrote:\n> > Check the query below as a more illustrative example:\n> >\n> > create table p (k int, val int) partition by range(k);\n> > create table p_1 partition of p for values from (1) to (10);\n> > create table p_2 partition of p for values from (10) to (100);\n> >\n> > If we use quals 'foo.k = bar.k and foo.k = bar.val', we can generate\n> > partitionwise join:\n> >\n> > # explain (costs off)\n> > select * from p as foo join p as bar on foo.k = bar.k and foo.k =\n> bar.val;\n> > QUERY PLAN\n> > -----------------------------------------\n> > Append\n> > -> Hash Join\n> > Hash Cond: (foo.k = bar.k)\n> > -> Seq Scan on p_1 foo\n> > -> Hash\n> > -> Seq Scan on p_1 bar\n> > Filter: (k = val)\n> > -> Hash Join\n> > Hash Cond: (foo_1.k = bar_1.k)\n> > -> Seq Scan on p_2 foo_1\n> > -> Hash\n> > -> Seq Scan on p_2 bar_1\n> > Filter: (k = val)\n> > (13 rows)\n> >\n> > But if we exchange the order of the two quals to 'foo.k = bar.val and\n> > foo.k = bar.k', then partitionwise join cannot be generated any more,\n> > because we only have joinclause 'foo.k = bar.val' as it first reached\n> > score of 3. We have missed the joinclause on the partition key although\n> > it does exist.\n> >\n> > # explain (costs off)\n> > select * from p as foo join p as bar on foo.k = bar.val and foo.k =\n> bar.k;\n> > QUERY PLAN\n> > -----------------------------------------\n> > Hash Join\n> > Hash Cond: (foo.k = bar.val)\n> > -> Append\n> > -> Seq Scan on p_1 foo\n> > -> Seq Scan on p_2 foo_1\n> > -> Hash\n> > -> Append\n> > -> Seq Scan on p_1 bar\n> > Filter: (val = k)\n> > -> Seq Scan on p_2 bar_1\n> > Filter: (val = k)\n> > (11 rows)\n>\n> I think it would be nice if we can address this issue.\n>\n\nThank you.\n\nAttached is a patch as an attempt to address this issue. The idea is\nquite straightforward. When building partition info for joinrel, we\ngenerate any possible EC-derived joinclauses of form 'outer_em =\ninner_em', which will be used together with the original restrictlist to\ncheck if there exists an equi-join condition for each pair of partition\nkeys.\n\nAny comments are welcome!\n\nThanks\nRichard", "msg_date": "Thu, 29 Aug 2019 17:44:53 +0800", "msg_from": "Richard Guo <riguo@pivotal.io>", "msg_from_op": true, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Thu, Aug 29, 2019 at 6:45 PM Richard Guo <riguo@pivotal.io> wrote:\n> On Wed, Aug 28, 2019 at 6:49 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:\n>> On Tue, Aug 27, 2019 at 4:57 PM Richard Guo <riguo@pivotal.io> wrote:\n>> > Check the query below as a more illustrative example:\n>> >\n>> > create table p (k int, val int) partition by range(k);\n>> > create table p_1 partition of p for values from (1) to (10);\n>> > create table p_2 partition of p for values from (10) to (100);\n>> >\n>> > If we use quals 'foo.k = bar.k and foo.k = bar.val', we can generate\n>> > partitionwise join:\n>> >\n>> > # explain (costs off)\n>> > select * from p as foo join p as bar on foo.k = bar.k and foo.k = bar.val;\n>> > QUERY PLAN\n>> > -----------------------------------------\n>> > Append\n>> > -> Hash Join\n>> > Hash Cond: (foo.k = bar.k)\n>> > -> Seq Scan on p_1 foo\n>> > -> Hash\n>> > -> Seq Scan on p_1 bar\n>> > Filter: (k = val)\n>> > -> Hash Join\n>> > Hash Cond: (foo_1.k = bar_1.k)\n>> > -> Seq Scan on p_2 foo_1\n>> > -> Hash\n>> > -> Seq Scan on p_2 bar_1\n>> > Filter: (k = val)\n>> > (13 rows)\n>> >\n>> > But if we exchange the order of the two quals to 'foo.k = bar.val and\n>> > foo.k = bar.k', then partitionwise join cannot be generated any more,\n>> > because we only have joinclause 'foo.k = bar.val' as it first reached\n>> > score of 3. We have missed the joinclause on the partition key although\n>> > it does exist.\n>> >\n>> > # explain (costs off)\n>> > select * from p as foo join p as bar on foo.k = bar.val and foo.k = bar.k;\n>> > QUERY PLAN\n>> > -----------------------------------------\n>> > Hash Join\n>> > Hash Cond: (foo.k = bar.val)\n>> > -> Append\n>> > -> Seq Scan on p_1 foo\n>> > -> Seq Scan on p_2 foo_1\n>> > -> Hash\n>> > -> Append\n>> > -> Seq Scan on p_1 bar\n>> > Filter: (val = k)\n>> > -> Seq Scan on p_2 bar_1\n>> > Filter: (val = k)\n>> > (11 rows)\n>>\n>> I think it would be nice if we can address this issue.\n\n> Attached is a patch as an attempt to address this issue. The idea is\n> quite straightforward. When building partition info for joinrel, we\n> generate any possible EC-derived joinclauses of form 'outer_em =\n> inner_em', which will be used together with the original restrictlist to\n> check if there exists an equi-join condition for each pair of partition\n> keys.\n\nThank you for the patch! Will review. Could you add the patch to the\nupcoming CF so that it doesn’t get lost?\n\nBest regards,\nEtsuro Fujita\n\n\n", "msg_date": "Fri, 30 Aug 2019 03:08:27 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Fri, Aug 30, 2019 at 2:08 AM Etsuro Fujita <etsuro.fujita@gmail.com>\nwrote:\n\n> On Thu, Aug 29, 2019 at 6:45 PM Richard Guo <riguo@pivotal.io> wrote:\n> > On Wed, Aug 28, 2019 at 6:49 PM Etsuro Fujita <etsuro.fujita@gmail.com>\n> wrote:\n> >> On Tue, Aug 27, 2019 at 4:57 PM Richard Guo <riguo@pivotal.io> wrote:\n> >> > Check the query below as a more illustrative example:\n> >> >\n> >> > create table p (k int, val int) partition by range(k);\n> >> > create table p_1 partition of p for values from (1) to (10);\n> >> > create table p_2 partition of p for values from (10) to (100);\n> >> >\n> >> > If we use quals 'foo.k = bar.k and foo.k = bar.val', we can generate\n> >> > partitionwise join:\n> >> >\n> >> > # explain (costs off)\n> >> > select * from p as foo join p as bar on foo.k = bar.k and foo.k =\n> bar.val;\n> >> > QUERY PLAN\n> >> > -----------------------------------------\n> >> > Append\n> >> > -> Hash Join\n> >> > Hash Cond: (foo.k = bar.k)\n> >> > -> Seq Scan on p_1 foo\n> >> > -> Hash\n> >> > -> Seq Scan on p_1 bar\n> >> > Filter: (k = val)\n> >> > -> Hash Join\n> >> > Hash Cond: (foo_1.k = bar_1.k)\n> >> > -> Seq Scan on p_2 foo_1\n> >> > -> Hash\n> >> > -> Seq Scan on p_2 bar_1\n> >> > Filter: (k = val)\n> >> > (13 rows)\n> >> >\n> >> > But if we exchange the order of the two quals to 'foo.k = bar.val and\n> >> > foo.k = bar.k', then partitionwise join cannot be generated any more,\n> >> > because we only have joinclause 'foo.k = bar.val' as it first reached\n> >> > score of 3. We have missed the joinclause on the partition key\n> although\n> >> > it does exist.\n> >> >\n> >> > # explain (costs off)\n> >> > select * from p as foo join p as bar on foo.k = bar.val and foo.k =\n> bar.k;\n> >> > QUERY PLAN\n> >> > -----------------------------------------\n> >> > Hash Join\n> >> > Hash Cond: (foo.k = bar.val)\n> >> > -> Append\n> >> > -> Seq Scan on p_1 foo\n> >> > -> Seq Scan on p_2 foo_1\n> >> > -> Hash\n> >> > -> Append\n> >> > -> Seq Scan on p_1 bar\n> >> > Filter: (val = k)\n> >> > -> Seq Scan on p_2 bar_1\n> >> > Filter: (val = k)\n> >> > (11 rows)\n> >>\n> >> I think it would be nice if we can address this issue.\n>\n> > Attached is a patch as an attempt to address this issue. The idea is\n> > quite straightforward. When building partition info for joinrel, we\n> > generate any possible EC-derived joinclauses of form 'outer_em =\n> > inner_em', which will be used together with the original restrictlist to\n> > check if there exists an equi-join condition for each pair of partition\n> > keys.\n>\n> Thank you for the patch! Will review. Could you add the patch to the\n> upcoming CF so that it doesn’t get lost?\n>\n\nAdded this patch: https://commitfest.postgresql.org/24/2266/\n\nThanks\nRichard\n\nOn Fri, Aug 30, 2019 at 2:08 AM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:On Thu, Aug 29, 2019 at 6:45 PM Richard Guo <riguo@pivotal.io> wrote:\n> On Wed, Aug 28, 2019 at 6:49 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:\n>> On Tue, Aug 27, 2019 at 4:57 PM Richard Guo <riguo@pivotal.io> wrote:\n>> > Check the query below as a more illustrative example:\n>> >\n>> > create table p (k int, val int) partition by range(k);\n>> > create table p_1 partition of p for values from (1) to (10);\n>> > create table p_2 partition of p for values from (10) to (100);\n>> >\n>> > If we use quals 'foo.k = bar.k and foo.k = bar.val', we can generate\n>> > partitionwise join:\n>> >\n>> > # explain (costs off)\n>> > select * from p as foo join p as bar on foo.k = bar.k and foo.k = bar.val;\n>> >                QUERY PLAN\n>> > -----------------------------------------\n>> >  Append\n>> >    ->  Hash Join\n>> >          Hash Cond: (foo.k = bar.k)\n>> >          ->  Seq Scan on p_1 foo\n>> >          ->  Hash\n>> >                ->  Seq Scan on p_1 bar\n>> >                      Filter: (k = val)\n>> >    ->  Hash Join\n>> >          Hash Cond: (foo_1.k = bar_1.k)\n>> >          ->  Seq Scan on p_2 foo_1\n>> >          ->  Hash\n>> >                ->  Seq Scan on p_2 bar_1\n>> >                      Filter: (k = val)\n>> > (13 rows)\n>> >\n>> > But if we exchange the order of the two quals to 'foo.k = bar.val and\n>> > foo.k = bar.k', then partitionwise join cannot be generated any more,\n>> > because we only have joinclause 'foo.k = bar.val' as it first reached\n>> > score of 3. We have missed the joinclause on the partition key although\n>> > it does exist.\n>> >\n>> > # explain (costs off)\n>> > select * from p as foo join p as bar on foo.k = bar.val and foo.k = bar.k;\n>> >                QUERY PLAN\n>> > -----------------------------------------\n>> >  Hash Join\n>> >    Hash Cond: (foo.k = bar.val)\n>> >    ->  Append\n>> >          ->  Seq Scan on p_1 foo\n>> >          ->  Seq Scan on p_2 foo_1\n>> >    ->  Hash\n>> >          ->  Append\n>> >                ->  Seq Scan on p_1 bar\n>> >                      Filter: (val = k)\n>> >                ->  Seq Scan on p_2 bar_1\n>> >                      Filter: (val = k)\n>> > (11 rows)\n>>\n>> I think it would be nice if we can address this issue.\n\n> Attached is a patch as an attempt to address this issue. The idea is\n> quite straightforward. When building partition info for joinrel, we\n> generate any possible EC-derived joinclauses of form 'outer_em =\n> inner_em', which will be used together with the original restrictlist to\n> check if there exists an equi-join condition for each pair of partition\n> keys.\n\nThank you for the patch!  Will review.  Could you add the patch to the\nupcoming CF so that it doesn’t get lost?Added this patch: https://commitfest.postgresql.org/24/2266/ThanksRichard", "msg_date": "Fri, 30 Aug 2019 11:15:37 +0800", "msg_from": "Richard Guo <riguo@pivotal.io>", "msg_from_op": true, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Fri, Aug 30, 2019 at 12:15 PM Richard Guo <riguo@pivotal.io> wrote:\n> On Fri, Aug 30, 2019 at 2:08 AM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:\n>> On Thu, Aug 29, 2019 at 6:45 PM Richard Guo <riguo@pivotal.io> wrote:\n>> > Attached is a patch as an attempt to address this issue. The idea is\n>> > quite straightforward. When building partition info for joinrel, we\n>> > generate any possible EC-derived joinclauses of form 'outer_em =\n>> > inner_em', which will be used together with the original restrictlist to\n>> > check if there exists an equi-join condition for each pair of partition\n>> > keys.\n\n>> Could you add the patch to the\n>> upcoming CF so that it doesn’t get lost?\n\n> Added this patch: https://commitfest.postgresql.org/24/2266/\n\nThanks!\n\nBest regards,\nEtsuro Fujita\n\n\n", "msg_date": "Fri, 30 Aug 2019 15:13:37 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "So in this patch, the input restrictlist is modified to include the\nclauses generated by generate_join_implied_equalities_for_all. That\ndoesn't seem okay -- doesn't it affect downstream usage of the\nrestrictlist in the caller of set_joinrel_size_estimates?\n\nI wonder if it's possible to do this by using the ECs directly in\nhave_partkey_equi_join instead of using them to create fake join\nclauses.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 10 Sep 2019 17:48:22 -0300", "msg_from": "Alvaro Herrera from 2ndQuadrant <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "Hi Alvaro,\n\nThank you for reviewing this patch.\n\nOn Wed, Sep 11, 2019 at 4:48 AM Alvaro Herrera from 2ndQuadrant <\nalvherre@alvh.no-ip.org> wrote:\n\n> So in this patch, the input restrictlist is modified to include the\n> clauses generated by generate_join_implied_equalities_for_all. That\n> doesn't seem okay -- doesn't it affect downstream usage of the\n> restrictlist in the caller of set_joinrel_size_estimates?\n>\n\nActually the joinclauses generated by\ngenerate_join_implied_equalities_for_all only affects the restrictlist\nused in have_partkey_equi_join to check equi-join conditions for\npartition keys. The input restrictlist would not be altered.\n\n\n>\n> I wonder if it's possible to do this by using the ECs directly in\n> have_partkey_equi_join instead of using them to create fake join\n> clauses.\n>\n\nHmm.. I thought about this option and at last figured that what we need\nto do in have_partkey_equi_join with the ECs is actually the same as in\ngenerate_join_implied_equalities_for_all. Maybe I didn't think it\ncorrectly.\n\nThanks\nRichard\n\nHi Alvaro,Thank you for reviewing this patch.On Wed, Sep 11, 2019 at 4:48 AM Alvaro Herrera from 2ndQuadrant <alvherre@alvh.no-ip.org> wrote:So in this patch, the input restrictlist is modified to include the\nclauses generated by generate_join_implied_equalities_for_all.  That\ndoesn't seem okay -- doesn't it affect downstream usage of the\nrestrictlist in the caller of set_joinrel_size_estimates?Actually the joinclauses generated bygenerate_join_implied_equalities_for_all only affects the restrictlistused in have_partkey_equi_join to check equi-join conditions forpartition keys.  The input restrictlist would not be altered. \n\nI wonder if it's possible to do this by using the ECs directly in\nhave_partkey_equi_join instead of using them to create fake join\nclauses.Hmm.. I thought about this option and at last figured that what we needto do in have_partkey_equi_join with the ECs is actually the same as ingenerate_join_implied_equalities_for_all. Maybe I didn't think itcorrectly.ThanksRichard", "msg_date": "Wed, 11 Sep 2019 11:56:33 +0800", "msg_from": "Richard Guo <riguo@pivotal.io>", "msg_from_op": true, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Thu, Aug 29, 2019 at 3:15 PM Richard Guo <riguo@pivotal.io> wrote:\n>\n>\n> Attached is a patch as an attempt to address this issue. The idea is\n> quite straightforward. When building partition info for joinrel, we\n> generate any possible EC-derived joinclauses of form 'outer_em =\n> inner_em', which will be used together with the original restrictlist to\n> check if there exists an equi-join condition for each pair of partition\n> keys.\n>\n> Any comments are welcome!\n /*\n+ * generate_join_implied_equalities_for_all\n+ * Create any EC-derived joinclauses of form 'outer_em = inner_em'.\n+ *\n+ * This is used when building partition info for joinrel.\n+ */\n+List *\n+generate_join_implied_equalities_for_all(PlannerInfo *root,\n+ Relids join_relids,\n+ Relids outer_relids,\n+ Relids inner_relids)\n\nI think we need to have more detailed comments about why we need this\nseparate function, we can also explain that\ngenerate_join_implied_equalities function will avoid\nthe join clause if EC has the constant but for partition-wise join, we\nneed that clause too.\n\n\n+ while ((i = bms_next_member(matching_ecs, i)) >= 0)\n+ {\n+ EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes, i);\n+ List *outer_members = NIL;\n+ List *inner_members = NIL;\n+ ListCell *lc1;\n+\n+ /* Do not consider this EC if it's ec_broken */\n+ if (ec->ec_broken)\n+ continue;\n+\n+ /* Single-member ECs won't generate any deductions */\n+ if (list_length(ec->ec_members) <= 1)\n+ continue;\n+\n\nI am wondering isn't it possible to just process the missing join\nclause? I mean 'generate_join_implied_equalities' has only skipped\nthe ECs which has const so\ncan't we create join clause only for those ECs and append it the\n\"Restrictlist\" we already have? I might be missing something?\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 20 Sep 2019 10:18:44 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "Hi Dilip,\n\nThank you for reviewing this patch.\n\nOn Fri, Sep 20, 2019 at 12:48 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n\n> On Thu, Aug 29, 2019 at 3:15 PM Richard Guo <riguo@pivotal.io> wrote:\n> >\n> >\n> > Attached is a patch as an attempt to address this issue. The idea is\n> > quite straightforward. When building partition info for joinrel, we\n> > generate any possible EC-derived joinclauses of form 'outer_em =\n> > inner_em', which will be used together with the original restrictlist to\n> > check if there exists an equi-join condition for each pair of partition\n> > keys.\n> >\n> > Any comments are welcome!\n> /*\n> + * generate_join_implied_equalities_for_all\n> + * Create any EC-derived joinclauses of form 'outer_em = inner_em'.\n> + *\n> + * This is used when building partition info for joinrel.\n> + */\n> +List *\n> +generate_join_implied_equalities_for_all(PlannerInfo *root,\n> + Relids join_relids,\n> + Relids outer_relids,\n> + Relids inner_relids)\n>\n> I think we need to have more detailed comments about why we need this\n> separate function, we can also explain that\n> generate_join_implied_equalities function will avoid\n> the join clause if EC has the constant but for partition-wise join, we\n> need that clause too.\n>\n\nThank you for the suggestion.\n\n\n>\n> + while ((i = bms_next_member(matching_ecs, i)) >= 0)\n> + {\n> + EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes,\n> i);\n> + List *outer_members = NIL;\n> + List *inner_members = NIL;\n> + ListCell *lc1;\n> +\n> + /* Do not consider this EC if it's ec_broken */\n> + if (ec->ec_broken)\n> + continue;\n> +\n> + /* Single-member ECs won't generate any deductions */\n> + if (list_length(ec->ec_members) <= 1)\n> + continue;\n> +\n>\n> I am wondering isn't it possible to just process the missing join\n> clause? I mean 'generate_join_implied_equalities' has only skipped\n> the ECs which has const so\n> can't we create join clause only for those ECs and append it the\n> \"Restrictlist\" we already have? I might be missing something?\n>\n\nFor ECs without const, 'generate_join_implied_equalities' also has\nskipped some join clauses since it only selects the joinclause with\n'best_score' between outer members and inner members. And the missing\njoin clauses are needed to generate partitionwise join. That's why the\nquery below cannot be planned as partitionwise join, as we have missed\njoinclause 'foo.k = bar.k'.\n\nselect * from p as foo join p as bar on foo.k = bar.val and foo.k = bar.k;\n\nAnd yes 'generate_join_implied_equalities_for_all' will create join\nclauses that have existed in restrictlist. I think it's OK since the\nsame RestrictInfo deduced from EC will share the same pointer and\nlist_concat_unique_ptr will make sure there are no duplicates in the\nrestrictlist used by have_partkey_equi_join.\n\nThanks\nRichard\n\nHi Dilip,Thank you for reviewing this patch.On Fri, Sep 20, 2019 at 12:48 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:On Thu, Aug 29, 2019 at 3:15 PM Richard Guo <riguo@pivotal.io> wrote:\n>\n>\n> Attached is a patch as an attempt to address this issue. The idea is\n> quite straightforward. When building partition info for joinrel, we\n> generate any possible EC-derived joinclauses of form 'outer_em =\n> inner_em', which will be used together with the original restrictlist to\n> check if there exists an equi-join condition for each pair of partition\n> keys.\n>\n> Any comments are welcome!\n /*\n+ * generate_join_implied_equalities_for_all\n+ *   Create any EC-derived joinclauses of form 'outer_em = inner_em'.\n+ *\n+ * This is used when building partition info for joinrel.\n+ */\n+List *\n+generate_join_implied_equalities_for_all(PlannerInfo *root,\n+ Relids join_relids,\n+ Relids outer_relids,\n+ Relids inner_relids)\n\nI think we need to have more detailed comments about why we need this\nseparate function, we can also explain that\ngenerate_join_implied_equalities function will avoid\nthe join clause if EC has the constant but for partition-wise join, we\nneed that clause too.Thank you for the suggestion. \n\n\n+ while ((i = bms_next_member(matching_ecs, i)) >= 0)\n+ {\n+ EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes, i);\n+ List    *outer_members = NIL;\n+ List    *inner_members = NIL;\n+ ListCell   *lc1;\n+\n+ /* Do not consider this EC if it's ec_broken */\n+ if (ec->ec_broken)\n+ continue;\n+\n+ /* Single-member ECs won't generate any deductions */\n+ if (list_length(ec->ec_members) <= 1)\n+ continue;\n+\n\nI am wondering isn't it possible to just process the missing join\nclause?  I mean 'generate_join_implied_equalities' has only skipped\nthe ECs which has const so\ncan't we create join clause only for those ECs and append it the\n\"Restrictlist\" we already have?  I might be missing something?For ECs without const, 'generate_join_implied_equalities' also hasskipped some join clauses since it only selects the joinclause with'best_score' between outer members and inner members. And the missingjoin clauses are needed to generate partitionwise join. That's why thequery below cannot be planned as partitionwise join, as we have missedjoinclause 'foo.k = bar.k'.select * from p as foo join p as bar on foo.k = bar.val and foo.k = bar.k;And yes 'generate_join_implied_equalities_for_all' will create joinclauses that have existed in restrictlist. I think it's OK since thesame RestrictInfo deduced from EC will share the same pointer andlist_concat_unique_ptr will make sure there are no duplicates in therestrictlist used by have_partkey_equi_join.ThanksRichard", "msg_date": "Fri, 20 Sep 2019 17:02:52 +0800", "msg_from": "Richard Guo <riguo@pivotal.io>", "msg_from_op": true, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Fri, Sep 20, 2019 at 2:33 PM Richard Guo <riguo@pivotal.io> wrote:\n>\n> Hi Dilip,\n>\n> Thank you for reviewing this patch.\n>\n> On Fri, Sep 20, 2019 at 12:48 PM Dilip Kumar <dilipbalaut@gmail.com> wrote:\n>>\n>> On Thu, Aug 29, 2019 at 3:15 PM Richard Guo <riguo@pivotal.io> wrote:\n>> >\n>> >\n>> > Attached is a patch as an attempt to address this issue. The idea is\n>> > quite straightforward. When building partition info for joinrel, we\n>> > generate any possible EC-derived joinclauses of form 'outer_em =\n>> > inner_em', which will be used together with the original restrictlist to\n>> > check if there exists an equi-join condition for each pair of partition\n>> > keys.\n>> >\n>> > Any comments are welcome!\n>> /*\n>> + * generate_join_implied_equalities_for_all\n>> + * Create any EC-derived joinclauses of form 'outer_em = inner_em'.\n>> + *\n>> + * This is used when building partition info for joinrel.\n>> + */\n>> +List *\n>> +generate_join_implied_equalities_for_all(PlannerInfo *root,\n>> + Relids join_relids,\n>> + Relids outer_relids,\n>> + Relids inner_relids)\n>>\n>> I think we need to have more detailed comments about why we need this\n>> separate function, we can also explain that\n>> generate_join_implied_equalities function will avoid\n>> the join clause if EC has the constant but for partition-wise join, we\n>> need that clause too.\n>\n>\n> Thank you for the suggestion.\n>\n>>\n>>\n>> + while ((i = bms_next_member(matching_ecs, i)) >= 0)\n>> + {\n>> + EquivalenceClass *ec = (EquivalenceClass *) list_nth(root->eq_classes, i);\n>> + List *outer_members = NIL;\n>> + List *inner_members = NIL;\n>> + ListCell *lc1;\n>> +\n>> + /* Do not consider this EC if it's ec_broken */\n>> + if (ec->ec_broken)\n>> + continue;\n>> +\n>> + /* Single-member ECs won't generate any deductions */\n>> + if (list_length(ec->ec_members) <= 1)\n>> + continue;\n>> +\n>>\n>> I am wondering isn't it possible to just process the missing join\n>> clause? I mean 'generate_join_implied_equalities' has only skipped\n>> the ECs which has const so\n>> can't we create join clause only for those ECs and append it the\n>> \"Restrictlist\" we already have? I might be missing something?\n>\n>\n> For ECs without const, 'generate_join_implied_equalities' also has\n> skipped some join clauses since it only selects the joinclause with\n> 'best_score' between outer members and inner members. And the missing\n> join clauses are needed to generate partitionwise join. That's why the\n> query below cannot be planned as partitionwise join, as we have missed\n> joinclause 'foo.k = bar.k'.\n\noh right. I missed that part.\n\n> select * from p as foo join p as bar on foo.k = bar.val and foo.k = bar.k;\n>\n> And yes 'generate_join_implied_equalities_for_all' will create join\n> clauses that have existed in restrictlist. I think it's OK since the\n> same RestrictInfo deduced from EC will share the same pointer and\n> list_concat_unique_ptr will make sure there are no duplicates in the\n> restrictlist used by have_partkey_equi_join.\n>\nok\n\n-- \nRegards,\nDilip Kumar\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Sat, 21 Sep 2019 11:58:17 +0530", "msg_from": "Dilip Kumar <dilipbalaut@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "Hi Richard,\n\nOn Fri, Aug 30, 2019 at 3:08 AM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:\n> On Thu, Aug 29, 2019 at 6:45 PM Richard Guo <riguo@pivotal.io> wrote:\n> > Attached is a patch as an attempt to address this issue. The idea is\n> > quite straightforward. When building partition info for joinrel, we\n> > generate any possible EC-derived joinclauses of form 'outer_em =\n> > inner_em', which will be used together with the original restrictlist to\n> > check if there exists an equi-join condition for each pair of partition\n> > keys.\n>\n> Will review.\n\nI've just started reviewing this patch. One comment I have for now\nis: this is categorized into Bug Fixes, but we have a workaround at\nleast to the regression test case in the patch (ie, just reorder join\nclauses), so this seems to me more like an improvement than a bug fix.\n\nSorry for the delay.\n\nBest regards,\nEtsuro Fujita\n\n\n", "msg_date": "Tue, 26 Nov 2019 20:35:33 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Tue, Nov 26, 2019 at 08:35:33PM +0900, Etsuro Fujita wrote:\n> I've just started reviewing this patch. One comment I have for now\n> is: this is categorized into Bug Fixes, but we have a workaround at\n> least to the regression test case in the patch (ie, just reorder join\n> clauses), so this seems to me more like an improvement than a bug fix.\n\nHmm. Agreed. Changed the category and moved to next CF.\n--\nMichael", "msg_date": "Fri, 29 Nov 2019 12:03:05 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Fri, Nov 29, 2019 at 11:03 AM Michael Paquier <michael@paquier.xyz>\nwrote:\n\n> On Tue, Nov 26, 2019 at 08:35:33PM +0900, Etsuro Fujita wrote:\n> > I've just started reviewing this patch. One comment I have for now\n> > is: this is categorized into Bug Fixes, but we have a workaround at\n> > least to the regression test case in the patch (ie, just reorder join\n> > clauses), so this seems to me more like an improvement than a bug fix.\n>\n> Hmm. Agreed. Changed the category and moved to next CF.\n>\n\nThanks Etsuro for the comment and thanks Michael for the change.\n\nThanks\nRichard\n\nOn Fri, Nov 29, 2019 at 11:03 AM Michael Paquier <michael@paquier.xyz> wrote:On Tue, Nov 26, 2019 at 08:35:33PM +0900, Etsuro Fujita wrote:\n> I've just started reviewing this patch.  One comment I have for now\n> is: this is categorized into Bug Fixes, but we have a workaround at\n> least to the regression test case in the patch (ie, just reorder join\n> clauses), so this seems to me more like an improvement than a bug fix.\n\nHmm.  Agreed.  Changed the category and moved to next CF.Thanks Etsuro for the comment and thanks Michael for the change.ThanksRichard", "msg_date": "Fri, 29 Nov 2019 11:07:53 +0800", "msg_from": "Richard Guo <riguo@pivotal.io>", "msg_from_op": true, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Fri, Nov 29, 2019 at 12:08 PM Richard Guo <riguo@pivotal.io> wrote:\n> On Fri, Nov 29, 2019 at 11:03 AM Michael Paquier <michael@paquier.xyz> wrote:\n>> On Tue, Nov 26, 2019 at 08:35:33PM +0900, Etsuro Fujita wrote:\n>> > I've just started reviewing this patch. One comment I have for now\n>> > is: this is categorized into Bug Fixes, but we have a workaround at\n>> > least to the regression test case in the patch (ie, just reorder join\n>> > clauses), so this seems to me more like an improvement than a bug fix.\n>>\n>> Hmm. Agreed. Changed the category and moved to next CF.\n\n> thanks Michael for the change.\n\n+1\n\nBest regards,\nEtsuro Fujita\n\n\n", "msg_date": "Fri, 29 Nov 2019 12:35:33 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "Rebased the patch with latest master and also addressed the test case\nfailure reported by PostgreSQL Patch Tester.\n\nThanks\nRichard\n\n\nOn Fri, Nov 29, 2019 at 11:35 AM Etsuro Fujita <etsuro.fujita@gmail.com>\nwrote:\n\n> On Fri, Nov 29, 2019 at 12:08 PM Richard Guo <riguo@pivotal.io> wrote:\n> > On Fri, Nov 29, 2019 at 11:03 AM Michael Paquier <michael@paquier.xyz>\n> wrote:\n> >> On Tue, Nov 26, 2019 at 08:35:33PM +0900, Etsuro Fujita wrote:\n> >> > I've just started reviewing this patch. One comment I have for now\n> >> > is: this is categorized into Bug Fixes, but we have a workaround at\n> >> > least to the regression test case in the patch (ie, just reorder join\n> >> > clauses), so this seems to me more like an improvement than a bug fix.\n> >>\n> >> Hmm. Agreed. Changed the category and moved to next CF.\n>\n> > thanks Michael for the change.\n>\n> +1\n>\n> Best regards,\n> Etsuro Fujita\n>", "msg_date": "Sun, 19 Jan 2020 12:01:16 +0800", "msg_from": "Richard Guo <riguo@pivotal.io>", "msg_from_op": true, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "Richard Guo <riguo@pivotal.io> writes:\n> Rebased the patch with latest master and also addressed the test case\n> failure reported by PostgreSQL Patch Tester.\n\nI looked this patch over, but I don't like it too much: it seems very\nbrute-force (and badly under-commented). Creating all those extra\nRestrictInfos isn't too cheap in itself, plus they'll jam up the\nequivalence-class machinery for future tests.\n\nThere is already something in equivclass.c that would almost do what\nwe want here: exprs_known_equal() would tell us whether the partkeys\ncan be found in the same eclass, without having to generate data\nstructures along the way. The current implementation is not watertight\nbecause it doesn't check opclass semantics, but that consideration\ncan be bolted on readily enough. So that leads me to something like\nthe attached.\n\nOne argument that could be made against this approach is that if there\nare a lot of partkey expressions, this requires O(N^2) calls to\nexprs_known_equal, something that's already not too cheap. I think\nthat that's not a big problem because the number of partkey expressions\nwould only be equal to the join degree (ie it doesn't scale with the\nnumber of partitions of the baserels) ... but maybe I'm wrong about\nthat? I also wonder if it's really necessary to check every pair\nof partkey expressions. It seems at least plausible that in the\ncases we care about, all the partkeys on each side would be in the same\neclasses anyway, so that comparing the first members of each list would\nbe sufficient. But I haven't beat on that point.\n\n\t\t\tregards, tom lane", "msg_date": "Sat, 04 Apr 2020 16:37:58 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Sun, Apr 5, 2020 at 4:38 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Richard Guo <riguo@pivotal.io> writes:\n> > Rebased the patch with latest master and also addressed the test case\n> > failure reported by PostgreSQL Patch Tester.\n>\n> I looked this patch over, but I don't like it too much: it seems very\n> brute-force (and badly under-commented). Creating all those extra\n> RestrictInfos isn't too cheap in itself, plus they'll jam up the\n> equivalence-class machinery for future tests.\n>\n\nThanks for the review.\n\n\n>\n> There is already something in equivclass.c that would almost do what\n> we want here: exprs_known_equal() would tell us whether the partkeys\n> can be found in the same eclass, without having to generate data\n> structures along the way. The current implementation is not watertight\n> because it doesn't check opclass semantics, but that consideration\n> can be bolted on readily enough. So that leads me to something like\n> the attached.\n>\n\nI looked through this patch and it's much more elegant than the previous\none. Thank you for working on it.\n\nFor partkeys which fail to be identified as equal by looking through\nrestrictlist, it's a good idea to check them in ECs with the help of\nexprs_known_equal().\n\nI have some concern about we only check non-nullable partexprs. Is it\npossible that two nullable partexprs come from the same EC? I tried to\ngive an example but failed.\n\n\n>\n> One argument that could be made against this approach is that if there\n> are a lot of partkey expressions, this requires O(N^2) calls to\n> exprs_known_equal, something that's already not too cheap. I think\n> that that's not a big problem because the number of partkey expressions\n> would only be equal to the join degree (ie it doesn't scale with the\n> number of partitions of the baserels) ... but maybe I'm wrong about\n> that?\n\n\nYou are right. According to how partexpr is formed for joinrel in\nset_joinrel_partition_key_exprs(), each base relation within the join\ncontributes one partexpr, so the number of partexprs would be equal to\nthe join degree.\n\n\n> I also wonder if it's really necessary to check every pair\n> of partkey expressions. It seems at least plausible that in the\n> cases we care about, all the partkeys on each side would be in the same\n> eclasses anyway, so that comparing the first members of each list would\n> be sufficient. But I haven't beat on that point.\n>\n\nNot sure about it. But cannot come out with a counterexample.\n\nThanks\nRichard\n\nOn Sun, Apr 5, 2020 at 4:38 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:Richard Guo <riguo@pivotal.io> writes:\n> Rebased the patch with latest master and also addressed the test case\n> failure reported by PostgreSQL Patch Tester.\n\nI looked this patch over, but I don't like it too much: it seems very\nbrute-force (and badly under-commented).  Creating all those extra\nRestrictInfos isn't too cheap in itself, plus they'll jam up the\nequivalence-class machinery for future tests.Thanks for the review. \n\nThere is already something in equivclass.c that would almost do what\nwe want here: exprs_known_equal() would tell us whether the partkeys\ncan be found in the same eclass, without having to generate data\nstructures along the way.  The current implementation is not watertight\nbecause it doesn't check opclass semantics, but that consideration\ncan be bolted on readily enough.  So that leads me to something like\nthe attached.I looked through this patch and it's much more elegant than the previousone. Thank you for working on it.For partkeys which fail to be identified as equal by looking throughrestrictlist, it's a good idea to check them in ECs with the help ofexprs_known_equal().I have some concern about we only check non-nullable partexprs. Is itpossible that two nullable partexprs come from the same EC? I tried togive an example but failed. \n\nOne argument that could be made against this approach is that if there\nare a lot of partkey expressions, this requires O(N^2) calls to\nexprs_known_equal, something that's already not too cheap.  I think\nthat that's not a big problem because the number of partkey expressions\nwould only be equal to the join degree (ie it doesn't scale with the\nnumber of partitions of the baserels) ... but maybe I'm wrong about\nthat?You are right. According to how partexpr is formed for joinrel inset_joinrel_partition_key_exprs(), each base relation within the joincontributes one partexpr, so the number of partexprs would be equal tothe join degree.   I also wonder if it's really necessary to check every pair\nof partkey expressions.  It seems at least plausible that in the\ncases we care about, all the partkeys on each side would be in the same\neclasses anyway, so that comparing the first members of each list would\nbe sufficient.  But I haven't beat on that point.Not sure about it. But cannot come out with a counterexample.ThanksRichard", "msg_date": "Wed, 8 Apr 2020 12:58:49 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "Richard Guo <guofenglinux@gmail.com> writes:\n> On Sun, Apr 5, 2020 at 4:38 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> There is already something in equivclass.c that would almost do what\n>> we want here: exprs_known_equal() would tell us whether the partkeys\n>> can be found in the same eclass, without having to generate data\n>> structures along the way. The current implementation is not watertight\n>> because it doesn't check opclass semantics, but that consideration\n>> can be bolted on readily enough. So that leads me to something like\n>> the attached.\n\n> I have some concern about we only check non-nullable partexprs. Is it\n> possible that two nullable partexprs come from the same EC? I tried to\n> give an example but failed.\n\nCurrently the EC infrastructure doesn't really cope with outer join\nequijoins. They are not treated as producing true equivalences,\nso I think that the case you're worried about can't occur (which is why\nI didn't code for it). I have hopes of being able to incorporate outer\njoins into the EC logic in a less squishy way in the future, by making\nthe representation of Vars distinguish explicitly between\nvalue-before-outer-join and value-after-outer-join, after which we could\nmake bulletproof assertions about what is equal to what, even with outer\njoins in the mix. If that works out it might produce a cleaner answer\nin this area too.\n\nTBH, now that I have had some exposure to the partitionwise join\nmatching logic I don't much like any of it. I feel like it's doing\nabout the same job as ECs, but in an unprincipled and not very\nefficient manner. Right now is no time to redesign it, of course,\nbut maybe at some point we could do that. (I did experiment with\nremoving all the rest of have_partkey_equi_join() and having it\n*only* ask exprs_known_equal() about equivalences, which is more or\nless what I'm envisioning here. That caused some of the existing\nregression tests to fail, so there's something that the idea isn't\ncovering. I didn't dig any further at the time, and in particular\nfailed to check whether the problems were specifically about outer\njoins, which'd be unsurprising given the above.)\n\nAnyway, this work has missed the window for v13, so we've got plenty\nof time to think about it.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 08 Apr 2020 13:07:54 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Thu, Apr 9, 2020 at 1:07 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Richard Guo <guofenglinux@gmail.com> writes:\n> > On Sun, Apr 5, 2020 at 4:38 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> There is already something in equivclass.c that would almost do what\n> >> we want here: exprs_known_equal() would tell us whether the partkeys\n> >> can be found in the same eclass, without having to generate data\n> >> structures along the way. The current implementation is not watertight\n> >> because it doesn't check opclass semantics, but that consideration\n> >> can be bolted on readily enough. So that leads me to something like\n> >> the attached.\n>\n> > I have some concern about we only check non-nullable partexprs. Is it\n> > possible that two nullable partexprs come from the same EC? I tried to\n> > give an example but failed.\n>\n> Currently the EC infrastructure doesn't really cope with outer join\n> equijoins. They are not treated as producing true equivalences,\n> so I think that the case you're worried about can't occur (which is why\n> I didn't code for it). I have hopes of being able to incorporate outer\n> joins into the EC logic in a less squishy way in the future, by making\n> the representation of Vars distinguish explicitly between\n> value-before-outer-join and value-after-outer-join, after which we could\n> make bulletproof assertions about what is equal to what, even with outer\n> joins in the mix. If that works out it might produce a cleaner answer\n> in this area too.\n>\n\nThis is very appealing. Do we have ongoing discussions/threads about\nthis idea?\n\n\n> (I did experiment with\n> removing all the rest of have_partkey_equi_join() and having it\n> *only* ask exprs_known_equal() about equivalences, which is more or\n> less what I'm envisioning here. That caused some of the existing\n> regression tests to fail, so there's something that the idea isn't\n> covering. I didn't dig any further at the time, and in particular\n> failed to check whether the problems were specifically about outer\n> joins, which'd be unsurprising given the above.)\n>\n\nI think it would not work for outer joins if we only check\nexprs_known_equal() for equivalences. If the equi-join conditions\ninvolving pairs of matching partition keys are outer join quals\nmentioning nonnullable side rels, they would not exist in any EC\naccording to the current EC infrastructure. So we still have to look\nthrough restrictlist.\n\nThanks\nRichard\n\nOn Thu, Apr 9, 2020 at 1:07 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:Richard Guo <guofenglinux@gmail.com> writes:\n> On Sun, Apr 5, 2020 at 4:38 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> There is already something in equivclass.c that would almost do what\n>> we want here: exprs_known_equal() would tell us whether the partkeys\n>> can be found in the same eclass, without having to generate data\n>> structures along the way.  The current implementation is not watertight\n>> because it doesn't check opclass semantics, but that consideration\n>> can be bolted on readily enough.  So that leads me to something like\n>> the attached.\n\n> I have some concern about we only check non-nullable partexprs. Is it\n> possible that two nullable partexprs come from the same EC? I tried to\n> give an example but failed.\n\nCurrently the EC infrastructure doesn't really cope with outer join\nequijoins.  They are not treated as producing true equivalences,\nso I think that the case you're worried about can't occur (which is why\nI didn't code for it).  I have hopes of being able to incorporate outer\njoins into the EC logic in a less squishy way in the future, by making\nthe representation of Vars distinguish explicitly between\nvalue-before-outer-join and value-after-outer-join, after which we could\nmake bulletproof assertions about what is equal to what, even with outer\njoins in the mix.  If that works out it might produce a cleaner answer\nin this area too.This is very appealing. Do we have ongoing discussions/threads aboutthis idea?  (I did experiment with\nremoving all the rest of have_partkey_equi_join() and having it\n*only* ask exprs_known_equal() about equivalences, which is more or\nless what I'm envisioning here.  That caused some of the existing\nregression tests to fail, so there's something that the idea isn't\ncovering.  I didn't dig any further at the time, and in particular\nfailed to check whether the problems were specifically about outer\njoins, which'd be unsurprising given the above.)I think it would not work for outer joins if we only checkexprs_known_equal() for equivalences. If the equi-join conditionsinvolving pairs of matching partition keys are outer join qualsmentioning nonnullable side rels, they would not exist in any ECaccording to the current EC infrastructure. So we still have to lookthrough restrictlist.ThanksRichard", "msg_date": "Thu, 9 Apr 2020 12:14:24 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "Richard Guo <guofenglinux@gmail.com> writes:\n> On Thu, Apr 9, 2020 at 1:07 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I have hopes of being able to incorporate outer\n>> joins into the EC logic in a less squishy way in the future, by making\n>> the representation of Vars distinguish explicitly between\n>> value-before-outer-join and value-after-outer-join, after which we could\n>> make bulletproof assertions about what is equal to what, even with outer\n>> joins in the mix. If that works out it might produce a cleaner answer\n>> in this area too.\n\n> This is very appealing. Do we have ongoing discussions/threads about\n> this idea?\n\nThere's some preliminary noodling in this thread:\n\nhttps://www.postgresql.org/message-id/flat/15848.1576515643%40sss.pgh.pa.us\n\nI've pushed the earlier work discussed there, but stalled out due to\nthe call of other responsibilities after posting the currently-last\nmessage in the thread. Hoping to get back into that over the summer.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 09 Apr 2020 01:24:23 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": ">\n> I think it would not work for outer joins if we only check\n> exprs_known_equal() for equivalences. If the equi-join conditions\n> involving pairs of matching partition keys are outer join quals\n> mentioning nonnullable side rels, they would not exist in any EC\n> according to the current EC infrastructure. So we still have to look\n> through restrictlist.\n>\n\nWhen I wrote that function and even today, EC didn't accommodate outer\njoin equality conditions. If we can somehow do that,\nhave_partkey_equi_join() can be completely eliminated.\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n", "msg_date": "Thu, 9 Apr 2020 19:36:28 +0530", "msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "Status update for a commitfest entry.\r\n\r\nAccording to CFbot this patch fails to apply. Richard, can you send an update, please?\r\n\r\nAlso, I see that the thread was inactive for a while.\r\nAre you going to continue this work? I think it would be helpful, if you could write a short recap about current state of the patch and list open questions for reviewers.\n\nThe new status of this patch is: Waiting on Author\n", "msg_date": "Fri, 06 Nov 2020 15:25:24 +0000", "msg_from": "Anastasia Lubennikova <a.lubennikova@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Fri, Nov 6, 2020 at 11:26 PM Anastasia Lubennikova <\na.lubennikova@postgrespro.ru> wrote:\n\n> Status update for a commitfest entry.\n>\n> According to CFbot this patch fails to apply. Richard, can you send an\n> update, please?\n>\n> Also, I see that the thread was inactive for a while.\n> Are you going to continue this work? I think it would be helpful, if you\n> could write a short recap about current state of the patch and list open\n> questions for reviewers.\n>\n> The new status of this patch is: Waiting on Author\n>\n\nThanks Anastasia. I've rebased the patch with latest master.\n\nTo recap, the problem we are fixing here is when generating join clauses\nfrom equivalence classes, we only select the joinclause with the 'best\nscore', or the first joinclause with a score of 3. This may cause us to\nmiss some joinclause on partition keys and thus fail to generate\npartitionwise join.\n\nThe initial idea for the fix is to create all the RestrictInfos from ECs\nin order to check whether there exist equi-join conditions involving\npairs of matching partition keys of the relations being joined for all\npartition keys. And then Tom proposed a much better idea which leverages\nfunction exprs_known_equal() to tell whether the partkeys can be found\nin the same eclass, which is the current implementation in the latest\npatch.\n\nThanks\nRichard", "msg_date": "Tue, 10 Nov 2020 17:12:58 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Tue, Nov 10, 2020 at 2:43 PM Richard Guo <guofenglinux@gmail.com> wrote:\n>\n>\n> On Fri, Nov 6, 2020 at 11:26 PM Anastasia Lubennikova <a.lubennikova@postgrespro.ru> wrote:\n>>\n>> Status update for a commitfest entry.\n>>\n>> According to CFbot this patch fails to apply. Richard, can you send an update, please?\n>>\n>> Also, I see that the thread was inactive for a while.\n>> Are you going to continue this work? I think it would be helpful, if you could write a short recap about current state of the patch and list open questions for reviewers.\n>>\n>> The new status of this patch is: Waiting on Author\n>\n>\n> Thanks Anastasia. I've rebased the patch with latest master.\n>\n> To recap, the problem we are fixing here is when generating join clauses\n> from equivalence classes, we only select the joinclause with the 'best\n> score', or the first joinclause with a score of 3. This may cause us to\n> miss some joinclause on partition keys and thus fail to generate\n> partitionwise join.\n>\n> The initial idea for the fix is to create all the RestrictInfos from ECs\n> in order to check whether there exist equi-join conditions involving\n> pairs of matching partition keys of the relations being joined for all\n> partition keys. And then Tom proposed a much better idea which leverages\n> function exprs_known_equal() to tell whether the partkeys can be found\n> in the same eclass, which is the current implementation in the latest\n> patch.\n>\n\nIn the example you gave earlier, the equi join on partition key was\nthere but it was replaced by individual constant assignment clauses.\nSo if we keep the original restrictclause in there with a new flag\nindicating that it's redundant, have_partkey_equi_join will still be\nable to use it without much change. Depending upon where all we need\nto use avoid restrictclauses with the redundant flag, this might be an\neasier approach. However, with Tom's idea partition-wise join may be\nused even when there is no equi-join between partition keys but there\nare clauses like pk = const for all tables involved and const is the\nsame for all such tables.\n\nIn the spirit of small improvement made to the performance of\nhave_partkey_equi_join(), pk_has_clause should be renamed as\npk_known_equal and pks_known_equal as num_equal_pks.\n\nThe loop traversing the partition keys at a given position, may be\noptimized further if we pass lists to exprs_known_equal() which in\nturns checks whether one expression from each list is member of a\ngiven EC. This will avoid traversing all equivalence classes for each\npartition key expression, which can be a huge improvement when there\nare many ECs. But I think if one of the partition key expression at a\ngiven position is member of an equivalence class all the other\npartition key expressions at that position should be part of that\nequivalence class since there should be an equi-join between those. So\nthe loop in loop may not be required to start with.\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n", "msg_date": "Fri, 27 Nov 2020 17:35:00 +0530", "msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On 11/27/20 7:05 AM, Ashutosh Bapat wrote:\n> On Tue, Nov 10, 2020 at 2:43 PM Richard Guo <guofenglinux@gmail.com> wrote:\n>>\n>> To recap, the problem we are fixing here is when generating join clauses\n>> from equivalence classes, we only select the joinclause with the 'best\n>> score', or the first joinclause with a score of 3. This may cause us to\n>> miss some joinclause on partition keys and thus fail to generate\n>> partitionwise join.\n>>\n>> The initial idea for the fix is to create all the RestrictInfos from ECs\n>> in order to check whether there exist equi-join conditions involving\n>> pairs of matching partition keys of the relations being joined for all\n>> partition keys. And then Tom proposed a much better idea which leverages\n>> function exprs_known_equal() to tell whether the partkeys can be found\n>> in the same eclass, which is the current implementation in the latest\n>> patch.\n> \n> In the example you gave earlier, the equi join on partition key was\n> there but it was replaced by individual constant assignment clauses.\n> So if we keep the original restrictclause in there with a new flag\n> indicating that it's redundant, have_partkey_equi_join will still be\n> able to use it without much change. Depending upon where all we need\n> to use avoid restrictclauses with the redundant flag, this might be an\n> easier approach. However, with Tom's idea partition-wise join may be\n> used even when there is no equi-join between partition keys but there\n> are clauses like pk = const for all tables involved and const is the\n> same for all such tables.\n> \n> In the spirit of small improvement made to the performance of\n> have_partkey_equi_join(), pk_has_clause should be renamed as\n> pk_known_equal and pks_known_equal as num_equal_pks.\n> \n> The loop traversing the partition keys at a given position, may be\n> optimized further if we pass lists to exprs_known_equal() which in\n> turns checks whether one expression from each list is member of a\n> given EC. This will avoid traversing all equivalence classes for each\n> partition key expression, which can be a huge improvement when there\n> are many ECs. But I think if one of the partition key expression at a\n> given position is member of an equivalence class all the other\n> partition key expressions at that position should be part of that\n> equivalence class since there should be an equi-join between those. So\n> the loop in loop may not be required to start with.\n\nRichard, any thoughts on Ashutosh's comments?\n\nRegards,\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Tue, 9 Mar 2021 11:22:32 -0500", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Fri, Nov 27, 2020 at 8:05 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>\nwrote:\n\n> On Tue, Nov 10, 2020 at 2:43 PM Richard Guo <guofenglinux@gmail.com>\n> wrote:\n> > Thanks Anastasia. I've rebased the patch with latest master.\n> >\n> > To recap, the problem we are fixing here is when generating join clauses\n> > from equivalence classes, we only select the joinclause with the 'best\n> > score', or the first joinclause with a score of 3. This may cause us to\n> > miss some joinclause on partition keys and thus fail to generate\n> > partitionwise join.\n> >\n> > The initial idea for the fix is to create all the RestrictInfos from ECs\n> > in order to check whether there exist equi-join conditions involving\n> > pairs of matching partition keys of the relations being joined for all\n> > partition keys. And then Tom proposed a much better idea which leverages\n> > function exprs_known_equal() to tell whether the partkeys can be found\n> > in the same eclass, which is the current implementation in the latest\n> > patch.\n> >\n>\n> In the example you gave earlier, the equi join on partition key was\n> there but it was replaced by individual constant assignment clauses.\n> So if we keep the original restrictclause in there with a new flag\n> indicating that it's redundant, have_partkey_equi_join will still be\n> able to use it without much change. Depending upon where all we need\n> to use avoid restrictclauses with the redundant flag, this might be an\n> easier approach. However, with Tom's idea partition-wise join may be\n> used even when there is no equi-join between partition keys but there\n> are clauses like pk = const for all tables involved and const is the\n> same for all such tables.\n>\n\nCorrect. So with Tom's idea partition-wise join can cope with clauses\nsuch as 'foo.k1 = bar.k1 and foo.k2 = 16 and bar.k2 = 16'.\n\n\n>\n> In the spirit of small improvement made to the performance of\n> have_partkey_equi_join(), pk_has_clause should be renamed as\n> pk_known_equal and pks_known_equal as num_equal_pks.\n>\n\nThanks for the suggestion. Will do that in the new version of patch.\n\n\n>\n> The loop traversing the partition keys at a given position, may be\n> optimized further if we pass lists to exprs_known_equal() which in\n> turns checks whether one expression from each list is member of a\n> given EC. This will avoid traversing all equivalence classes for each\n> partition key expression, which can be a huge improvement when there\n> are many ECs. But I think if one of the partition key expression at a\n> given position is member of an equivalence class all the other\n> partition key expressions at that position should be part of that\n> equivalence class since there should be an equi-join between those. So\n> the loop in loop may not be required to start with.\n>\n\nGood point. Quote from one of Tom's earlier emails,\n \"It seems at least plausible that in the cases we care about, all the\n partkeys on each side would be in the same eclasses anyway, so that\n comparing the first members of each list would be sufficient.\"\n\nBut I'm not sure if this holds true in all cases. However, since each\nbase relation within the join contributes only one partexpr, the number\nof partexprs would only be equal to the join degree. Thus the loop in\nloop may not be a big problem?\n\nPS. Sorry for delaying so long time!\n\nThanks\nRichard", "msg_date": "Wed, 21 Jul 2021 16:44:53 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Wed, Jul 21, 2021 at 04:44:53PM +0800, Richard Guo wrote:\n> On Fri, Nov 27, 2020 at 8:05 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>\n> wrote:\n> \n> >\n> > In the example you gave earlier, the equi join on partition key was\n> > there but it was replaced by individual constant assignment clauses.\n> > So if we keep the original restrictclause in there with a new flag\n> > indicating that it's redundant, have_partkey_equi_join will still be\n> > able to use it without much change. Depending upon where all we need\n> > to use avoid restrictclauses with the redundant flag, this might be an\n> > easier approach. However, with Tom's idea partition-wise join may be\n> > used even when there is no equi-join between partition keys but there\n> > are clauses like pk = const for all tables involved and const is the\n> > same for all such tables.\n> >\n> \n> Correct. So with Tom's idea partition-wise join can cope with clauses\n> such as 'foo.k1 = bar.k1 and foo.k2 = 16 and bar.k2 = 16'.\n> \n> \n> >\n> > In the spirit of small improvement made to the performance of\n> > have_partkey_equi_join(), pk_has_clause should be renamed as\n> > pk_known_equal and pks_known_equal as num_equal_pks.\n> >\n> \n> Thanks for the suggestion. Will do that in the new version of patch.\n> \n\nHi Richard,\n\nWe are marking this CF entry as \"Returned with Feedback\", which means\nyou are encouraged to send a new patch (and create a new entry for a\nfuture CF for it) with the suggested changes.\n\n-- \nJaime Casanova\nDirector de Servicios Profesionales\nSystemGuards - Consultores de PostgreSQL\n\n\n", "msg_date": "Tue, 5 Oct 2021 12:19:22 -0500", "msg_from": "Jaime Casanova <jcasanov@systemguards.com.ec>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Wed, Oct 6, 2021 at 1:19 AM Jaime Casanova <jcasanov@systemguards.com.ec>\nwrote:\n\n> On Wed, Jul 21, 2021 at 04:44:53PM +0800, Richard Guo wrote:\n> > On Fri, Nov 27, 2020 at 8:05 PM Ashutosh Bapat <\n> ashutosh.bapat.oss@gmail.com>\n> > wrote:\n> >\n> > >\n> > > In the example you gave earlier, the equi join on partition key was\n> > > there but it was replaced by individual constant assignment clauses.\n> > > So if we keep the original restrictclause in there with a new flag\n> > > indicating that it's redundant, have_partkey_equi_join will still be\n> > > able to use it without much change. Depending upon where all we need\n> > > to use avoid restrictclauses with the redundant flag, this might be an\n> > > easier approach. However, with Tom's idea partition-wise join may be\n> > > used even when there is no equi-join between partition keys but there\n> > > are clauses like pk = const for all tables involved and const is the\n> > > same for all such tables.\n> > >\n> >\n> > Correct. So with Tom's idea partition-wise join can cope with clauses\n> > such as 'foo.k1 = bar.k1 and foo.k2 = 16 and bar.k2 = 16'.\n> >\n> >\n> > >\n> > > In the spirit of small improvement made to the performance of\n> > > have_partkey_equi_join(), pk_has_clause should be renamed as\n> > > pk_known_equal and pks_known_equal as num_equal_pks.\n> > >\n> >\n> > Thanks for the suggestion. Will do that in the new version of patch.\n> >\n>\n> Hi Richard,\n>\n> We are marking this CF entry as \"Returned with Feedback\", which means\n> you are encouraged to send a new patch (and create a new entry for a\n> future CF for it) with the suggested changes.\n>\n\nHi,\n\nThe suggested changes have already been included in v5 patch. Sorry for\nthe confusion.\n\nVerified that the patch still applies and works on latest master. So I'm\nmoving it to the next CF (which is Commitfest 2022-01). Please correct\nme if this is not the right thing to do.\n\nThanks\nRichard\n\nOn Wed, Oct 6, 2021 at 1:19 AM Jaime Casanova <jcasanov@systemguards.com.ec> wrote:On Wed, Jul 21, 2021 at 04:44:53PM +0800, Richard Guo wrote:\n> On Fri, Nov 27, 2020 at 8:05 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>\n> wrote:\n> \n> >\n> > In the example you gave earlier, the equi join on partition key was\n> > there but it was replaced by individual constant assignment clauses.\n> > So if we keep the original restrictclause in there with a new flag\n> > indicating that it's redundant, have_partkey_equi_join will still be\n> > able to use it without much change. Depending upon where all we need\n> > to use avoid restrictclauses with the redundant flag, this might be an\n> > easier approach. However, with Tom's idea partition-wise join may be\n> > used even when there is no equi-join between partition keys but there\n> > are clauses like pk = const for all tables involved and const is the\n> > same for all such tables.\n> >\n> \n> Correct. So with Tom's idea partition-wise join can cope with clauses\n> such as 'foo.k1 = bar.k1 and foo.k2 = 16 and bar.k2 = 16'.\n> \n> \n> >\n> > In the spirit of small improvement made to the performance of\n> > have_partkey_equi_join(), pk_has_clause should be renamed as\n> > pk_known_equal and pks_known_equal as num_equal_pks.\n> >\n> \n> Thanks for the suggestion. Will do that in the new version of patch.\n> \n\nHi Richard,\n\nWe are marking this CF entry as \"Returned with Feedback\", which means\nyou are encouraged to send a new patch (and create a new entry for a\nfuture CF for it) with the suggested changes.Hi,The suggested changes have already been included in v5 patch. Sorry forthe confusion.Verified that the patch still applies and works on latest master. So I'mmoving it to the next CF (which is Commitfest 2022-01). Please correctme if this is not the right thing to do.ThanksRichard", "msg_date": "Mon, 22 Nov 2021 15:04:58 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Mon, Nov 22, 2021 at 3:04 PM Richard Guo <guofenglinux@gmail.com> wrote:\n\n>\n> The suggested changes have already been included in v5 patch. Sorry for\n> the confusion.\n>\n> Verified that the patch still applies and works on latest master. So I'm\n> moving it to the next CF (which is Commitfest 2022-01). Please correct\n> me if this is not the right thing to do.\n>\n\nRebased the patch with latest master. Appreciate any comments.\n\nThanks\nRichard", "msg_date": "Mon, 25 Apr 2022 15:21:06 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "As discussed in [1], we're taking this opportunity to return some\npatchsets that don't appear to be getting enough reviewer interest.\n\nThis is not a rejection, since we don't necessarily think there's\nanything unacceptable about the entry, but it differs from a standard\n\"Returned with Feedback\" in that there's probably not much actionable\nfeedback at all. Rather than code changes, what this patch needs is more\ncommunity interest. You might\n\n- ask people for help with your approach,\n- see if there are similar patches that your code could supplement,\n- get interested parties to agree to review your patch in a CF, or\n- possibly present the functionality in a way that's easier to review\n overall.\n\n(Doing these things is no guarantee that there will be interest, but\nit's hopefully better than endlessly rebasing a patchset that is not\nreceiving any feedback from the community.)\n\nOnce you think you've built up some community support and the patchset\nis ready for review, you (or any interested party) can resurrect the\npatch entry by visiting\n\n https://commitfest.postgresql.org/38/2266/\n\nand changing the status to \"Needs Review\", and then changing the\nstatus again to \"Move to next CF\". (Don't forget the second step;\nhopefully we will have streamlined this in the near future!)\n\nThanks,\n--Jacob\n\n[1]\nhttps://postgr.es/m/flat/0ab66589-2f71-69b3-2002-49e821740b0d%40timescale.com\n\n\n", "msg_date": "Mon, 1 Aug 2022 13:24:08 -0700", "msg_from": "Jacob Champion <jchampion@timescale.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Tue, Aug 2, 2022 at 4:24 AM Jacob Champion <jchampion@timescale.com>\nwrote:\n\n> Once you think you've built up some community support and the patchset\n> is ready for review, you (or any interested party) can resurrect the\n> patch entry by visiting\n>\n> https://commitfest.postgresql.org/38/2266/\n>\n> and changing the status to \"Needs Review\", and then changing the\n> status again to \"Move to next CF\". (Don't forget the second step;\n> hopefully we will have streamlined this in the near future!)\n\n\nThis patch was returned due to 'lack of interest'. However, upon\nverification, it appears that the reported issue still exists, and the\nproposed fix in the thread remains valid. Hence, resurrect this patch\nafter rebasing it on master. I've also written a detailed commit\nmessage which hopefully can help people review the changes more\neffectively.\n\nThanks\nRichard", "msg_date": "Wed, 21 Feb 2024 19:24:54 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Wed, Feb 21, 2024 at 4:55 PM Richard Guo <guofenglinux@gmail.com> wrote:\n>\n>\n> On Tue, Aug 2, 2022 at 4:24 AM Jacob Champion <jchampion@timescale.com> wrote:\n>>\n>> Once you think you've built up some community support and the patchset\n>> is ready for review, you (or any interested party) can resurrect the\n>> patch entry by visiting\n>>\n>> https://commitfest.postgresql.org/38/2266/\n>>\n>> and changing the status to \"Needs Review\", and then changing the\n>> status again to \"Move to next CF\". (Don't forget the second step;\n>> hopefully we will have streamlined this in the near future!)\n>\n>\n> This patch was returned due to 'lack of interest'. However, upon\n> verification, it appears that the reported issue still exists, and the\n> proposed fix in the thread remains valid. Hence, resurrect this patch\n> after rebasing it on master. I've also written a detailed commit\n> message which hopefully can help people review the changes more\n> effectively.\n\nThe concept looks useful. The SQL statement added in the test looks\ncooked though (it outputs data that has same value for two columns\nwhich is equal to primary key of other table - when would somebody do\nthat?). Is there some real life example of this?\n\nThe patch uses restrictclauses as well as EC's. Tom has proposed to\nmake EC work with outer joins sensibly. Has that happened? Can this\npatch leverage it rather than having two loops?\n\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n", "msg_date": "Thu, 22 Feb 2024 14:56:49 +0530", "msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Thu, Feb 22, 2024 at 2:56 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>\nwrote:\n\n> On Wed, Feb 21, 2024 at 4:55 PM Richard Guo <guofenglinux@gmail.com>\n> wrote:\n> >\n> >\n> > On Tue, Aug 2, 2022 at 4:24 AM Jacob Champion <jchampion@timescale.com>\n> wrote:\n> >>\n> >> Once you think you've built up some community support and the patchset\n> >> is ready for review, you (or any interested party) can resurrect the\n> >> patch entry by visiting\n> >>\n> >> https://commitfest.postgresql.org/38/2266/\n> >>\n> >> and changing the status to \"Needs Review\", and then changing the\n> >> status again to \"Move to next CF\". (Don't forget the second step;\n> >> hopefully we will have streamlined this in the near future!)\n> >\n> >\n> > This patch was returned due to 'lack of interest'. However, upon\n> > verification, it appears that the reported issue still exists, and the\n> > proposed fix in the thread remains valid. Hence, resurrect this patch\n> > after rebasing it on master. I've also written a detailed commit\n> > message which hopefully can help people review the changes more\n> > effectively.\n>\n>\nI did a deeper review of the patch. Here are some comments\n\nApproach\n--------\nThe equijoin condition between partition keys doesn't appear in the join's\nrestrictilist because of 'best_score' strategy as you explained well in\n[2]. What if we add an extra score for clauses between partition keys and\ngive preference to equijoin between partition keys? Have you given it a\nthought? I feel that having an equijoin clause involving partition keys has\nmore usages compared to a clause with any random column. E.g. nextloop may\nbe able to prune partitions from inner relation if the clause contains a\npartition key.\n\nPartition pruning requires equality clauses on partition keys as well.\ncreate_append_plan() fetches those from best_path->param_info. If we\ncreated and saved the clauses involving partition keys somewhere\nseparately, similar to the clauses involving index keys, it might help this\ncase as well as the partition pruning code. Have you considered this idea?\n\nThere was a proposal to use ECs for outer joins as well and then use only\nECs to decide whether equijoins between partition keys exist. I don't think\nthe proposal has materialized. So we have to continue looking at\nrestrictlist as well. I don't see a point waiting for it, but others might\nfeel differently.\n\nI am just trying to find ways to avoid two loops in\nhave_partkey_equi_join(). If the alternatives are worse, I think the\ncurrent approach is fine.\n\nDocumentation\n-------------\nThe patch does not modify any documentation. The only documentation I could\nfind about partitionwise join is the one for GUC\n'enable_partitionwise_join'. It says\n--- quote\n\"Partitionwise join currently applies only when the join conditions include\nall the partition keys, which must be of the same data type and have\none-to-one matching sets of child partitions.\".\n--- unquote\nThis sentence is general and IMO covers the case this patch considers. But\nin general I feel that partitionwise join and aggregation deserve separate\nsections next to \"partition pruning\" in [1]; It should mention advanced\npartition matching algorithm as well. Would you be willing to write one and\nthen expand it for the case in the patch?\n\nTests\n-----\nThe patch adds a testcase for single column partitioning. I think we need\nto do better like\n1. Test for partitioning on expression, multilevel partitioning, advanced\npartition matching. Those all might just work. Having tests helps us to\nnotice any future breakage.\n2. Some negative test case e.g. equijoin clauses with disjunction, with\ninequality operator, equality operators with operators from different\nfamilies etc.\n3. The testcase added looks artificial. it outputs data that has same value\nfor two columns which is equal to the primary key of the other table - when\nwould somebody do that?. Is there some real life example where this change\nwill be useful?\n\nCode\n----\nMinor comment for now. It will be better to increment num_equal_pks\nimmediately after setting pk_known_equal[ipk] = true. Otherwise the code\ngets confusing around line 2269. I will spend more time reviewing the code\nnext week.\n\n[1] https://www.postgresql.org/docs/current/ddl-partitioning.html\n[2]\nhttps://www.postgresql.org/message-id/CAN_9JTxucGdVY9tV6Uxq0CdhrW98bZtxPKFbF_75qdPi5wBaow@mail.gmail.com\n\n-- \nBest Wishes,\nAshutosh Bapat\n\nOn Thu, Feb 22, 2024 at 2:56 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com> wrote:On Wed, Feb 21, 2024 at 4:55 PM Richard Guo <guofenglinux@gmail.com> wrote:\n>\n>\n> On Tue, Aug 2, 2022 at 4:24 AM Jacob Champion <jchampion@timescale.com> wrote:\n>>\n>> Once you think you've built up some community support and the patchset\n>> is ready for review, you (or any interested party) can resurrect the\n>> patch entry by visiting\n>>\n>>     https://commitfest.postgresql.org/38/2266/\n>>\n>> and changing the status to \"Needs Review\", and then changing the\n>> status again to \"Move to next CF\". (Don't forget the second step;\n>> hopefully we will have streamlined this in the near future!)\n>\n>\n> This patch was returned due to 'lack of interest'.  However, upon\n> verification, it appears that the reported issue still exists, and the\n> proposed fix in the thread remains valid.  Hence, resurrect this patch\n> after rebasing it on master.  I've also written a detailed commit\n> message which hopefully can help people review the changes more\n> effectively.\nI did a deeper review of the patch. Here are some commentsApproach--------The equijoin condition between partition keys doesn't appear in the join's restrictilist because of 'best_score' strategy as you explained well in [2]. What if we add an extra score for clauses between partition keys and give preference to equijoin between partition keys? Have you given it a thought? I feel that having an equijoin clause involving partition keys has more usages compared to a clause with any random column. E.g. nextloop may be able to prune partitions from inner relation if the clause contains a partition key.Partition pruning requires equality clauses on partition keys as well. create_append_plan() fetches those from best_path->param_info. If we created and saved the clauses involving partition keys somewhere separately, similar to the clauses involving index keys, it might help this case as well as the partition pruning code. Have you considered this idea?There was a proposal to use ECs for outer joins as well and then use only ECs to decide whether equijoins between partition keys exist. I don't think the proposal has materialized. So we have to continue looking at restrictlist as well. I don't see a point waiting for it, but others might feel differently.I am just trying to find ways to avoid two loops in \nhave_partkey_equi_join(). If the alternatives are worse, I think the \ncurrent approach is fine.Documentation-------------The patch does not modify any documentation. The only documentation I could find about partitionwise join is the one for GUC 'enable_partitionwise_join'. It says --- quote\"Partitionwise join currently applies only when the join conditions include all the partition keys, which must be of the same data type and have one-to-one matching sets of child partitions.\".--- unquoteThis sentence is general and IMO covers the case this patch considers. But in general I feel that partitionwise join and aggregation deserve separate sections next to \"partition pruning\" in [1]; It should mention advanced partition matching algorithm as well. Would you be willing to write one and then expand it for the case in the patch?Tests-----The patch adds a testcase for single column partitioning. I think we need to do better like1. Test for partitioning on expression, multilevel partitioning, advanced partition matching. Those all might just work. Having tests helps us to notice any future breakage.2. Some negative test case e.g. equijoin clauses with disjunction, with inequality operator, equality operators with operators from different families etc.3. The testcase added looks artificial. it outputs data that has same value for two columns which is equal to the primary key of the other table - when would somebody do that?. Is there some real life example where this change will be useful?Code----Minor comment for now. It will be better to increment num_equal_pks immediately after setting pk_known_equal[ipk] = true. Otherwise the code gets confusing around line 2269. I will spend more time reviewing the code next week.[1] https://www.postgresql.org/docs/current/ddl-partitioning.html[2] https://www.postgresql.org/message-id/CAN_9JTxucGdVY9tV6Uxq0CdhrW98bZtxPKFbF_75qdPi5wBaow@mail.gmail.com-- Best Wishes,Ashutosh Bapat", "msg_date": "Thu, 7 Mar 2024 16:43:05 +0530", "msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "(Sorry it takes me some time to get back to this thread.)\n\nOn Thu, Mar 7, 2024 at 7:13 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>\nwrote:\n\n> I did a deeper review of the patch. Here are some comments\n>\n\nThank you for the review!\n\n\n> Approach\n> --------\n> The equijoin condition between partition keys doesn't appear in the join's\n> restrictilist because of 'best_score' strategy as you explained well in\n> [2]. What if we add an extra score for clauses between partition keys and\n> give preference to equijoin between partition keys? Have you given it a\n> thought? I feel that having an equijoin clause involving partition keys has\n> more usages compared to a clause with any random column. E.g. nextloop may\n> be able to prune partitions from inner relation if the clause contains a\n> partition key.\n>\n\nHmm, I think this approach won't work in cases where one certain pair of\npartition keys has formed an EC that contains pseudoconstants. In such\ncases, the EC machinery will generate restriction clauses like 'pk =\nconst' rather than any join clauses.\n\nBesides, it seems to me that it's not a cheap operation to check whether\na join clause is between partition keys when we generate join clauses\nfrom ECs in generate_join_implied_equalities().\n\n\n> Documentation\n> -------------\n> The patch does not modify any documentation. The only documentation I\n> could find about partitionwise join is the one for GUC\n> 'enable_partitionwise_join'. It says\n> --- quote\n> \"Partitionwise join currently applies only when the join conditions\n> include all the partition keys, which must be of the same data type and\n> have one-to-one matching sets of child partitions.\".\n> --- unquote\n> This sentence is general and IMO covers the case this patch considers. But\n> in general I feel that partitionwise join and aggregation deserve separate\n> sections next to \"partition pruning\" in [1]; It should mention advanced\n> partition matching algorithm as well. Would you be willing to write one and\n> then expand it for the case in the patch?\n>\n\nI don't think it should be part of this patch to add a new section in\nthe docs to explain partitionwise join and aggregation. Maybe that\ndeserves a separate patch?\n\n\n> Tests\n> -----\n> The patch adds a testcase for single column partitioning. I think we need\n> to do better like\n> 1. Test for partitioning on expression, multilevel partitioning, advanced\n> partition matching. Those all might just work. Having tests helps us to\n> notice any future breakage.\n> 2. Some negative test case e.g. equijoin clauses with disjunction, with\n> inequality operator, equality operators with operators from different\n> families etc.\n>\n\nThanks for the suggestions. We can do that.\n\n\n> 3. The testcase added looks artificial. it outputs data that has same\n> value for two columns which is equal to the primary key of the other table\n> - when would somebody do that?. Is there some real life example where this\n> change will be useful?\n>\n\nHmm, I think the test case is good as long as it reveals the issue that\nthis patch fixes. It follows the same format as the existing test case\njust above it. I'm not sure if there are real life examples, but I\nthink it may not always be necessary to derive test cases from them.\n\n\n> Code\n> ----\n> Minor comment for now. It will be better to increment num_equal_pks\n> immediately after setting pk_known_equal[ipk] = true. Otherwise the code\n> gets confusing around line 2269. I will spend more time reviewing the code\n> next week.\n>\n\nHmm, the increment of num_equal_pks on line 2272 is parallel to the one\nin the first loop (around line 2200). Maybe it's better to keep them\nconsistent as the current patch does?\n\nThanks\nRichard\n\n(Sorry it takes me some time to get back to this thread.)On Thu, Mar 7, 2024 at 7:13 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com> wrote:I did a deeper review of the patch. Here are some commentsThank you for the review! Approach--------The equijoin condition between partition keys doesn't appear in the join's restrictilist because of 'best_score' strategy as you explained well in [2]. What if we add an extra score for clauses between partition keys and give preference to equijoin between partition keys? Have you given it a thought? I feel that having an equijoin clause involving partition keys has more usages compared to a clause with any random column. E.g. nextloop may be able to prune partitions from inner relation if the clause contains a partition key.Hmm, I think this approach won't work in cases where one certain pair ofpartition keys has formed an EC that contains pseudoconstants.  In suchcases, the EC machinery will generate restriction clauses like 'pk =const' rather than any join clauses.Besides, it seems to me that it's not a cheap operation to check whethera join clause is between partition keys when we generate join clausesfrom ECs in generate_join_implied_equalities(). Documentation-------------The patch does not modify any documentation. The only documentation I could find about partitionwise join is the one for GUC 'enable_partitionwise_join'. It says --- quote\"Partitionwise join currently applies only when the join conditions include all the partition keys, which must be of the same data type and have one-to-one matching sets of child partitions.\".--- unquoteThis sentence is general and IMO covers the case this patch considers. But in general I feel that partitionwise join and aggregation deserve separate sections next to \"partition pruning\" in [1]; It should mention advanced partition matching algorithm as well. Would you be willing to write one and then expand it for the case in the patch?I don't think it should be part of this patch to add a new section inthe docs to explain partitionwise join and aggregation.  Maybe thatdeserves a separate patch? Tests-----The patch adds a testcase for single column partitioning. I think we need to do better like1. Test for partitioning on expression, multilevel partitioning, advanced partition matching. Those all might just work. Having tests helps us to notice any future breakage.2. Some negative test case e.g. equijoin clauses with disjunction, with inequality operator, equality operators with operators from different families etc.Thanks for the suggestions.  We can do that. 3. The testcase added looks artificial. it outputs data that has same value for two columns which is equal to the primary key of the other table - when would somebody do that?. Is there some real life example where this change will be useful?Hmm, I think the test case is good as long as it reveals the issue thatthis patch fixes.  It follows the same format as the existing test casejust above it.  I'm not sure if there are real life examples, but Ithink it may not always be necessary to derive test cases from them. Code----Minor comment for now. It will be better to increment num_equal_pks immediately after setting pk_known_equal[ipk] = true. Otherwise the code gets confusing around line 2269. I will spend more time reviewing the code next week. Hmm, the increment of num_equal_pks on line 2272 is parallel to the onein the first loop (around line 2200).  Maybe it's better to keep themconsistent as the current patch does?ThanksRichard", "msg_date": "Tue, 19 Mar 2024 10:47:49 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Tue, Mar 19, 2024 at 8:18 AM Richard Guo <guofenglinux@gmail.com> wrote:\n\n> (Sorry it takes me some time to get back to this thread.)\n>\n> On Thu, Mar 7, 2024 at 7:13 PM Ashutosh Bapat <\n> ashutosh.bapat.oss@gmail.com> wrote:\n>\n>> I did a deeper review of the patch. Here are some comments\n>>\n>\n> Thank you for the review!\n>\n>\n>> Approach\n>> --------\n>> The equijoin condition between partition keys doesn't appear in the\n>> join's restrictilist because of 'best_score' strategy as you explained well\n>> in [2]. What if we add an extra score for clauses between partition keys\n>> and give preference to equijoin between partition keys? Have you given it a\n>> thought? I feel that having an equijoin clause involving partition keys has\n>> more usages compared to a clause with any random column. E.g. nextloop may\n>> be able to prune partitions from inner relation if the clause contains a\n>> partition key.\n>>\n>\n> Hmm, I think this approach won't work in cases where one certain pair of\n> partition keys has formed an EC that contains pseudoconstants. In such\n> cases, the EC machinery will generate restriction clauses like 'pk =\n> const' rather than any join clauses.\n>\n\nThat should be ok and more desirable. Clauses like pk = const will leave\nonly one partition around in each of the joining relations thus PWJ won't\nbe required OR it will be automatic - whichever way you see it.\n\n\n>\n> Besides, it seems to me that it's not a cheap operation to check whether\n> a join clause is between partition keys when we generate join clauses\n> from ECs in generate_join_implied_equalities().\n>\n\nWhy? The code would be the same as what we have\nin have_partkey_equi_join().\n\n>\n>\n\n\n> Documentation\n>> -------------\n>> The patch does not modify any documentation. The only documentation I\n>> could find about partitionwise join is the one for GUC\n>> 'enable_partitionwise_join'. It says\n>> --- quote\n>> \"Partitionwise join currently applies only when the join conditions\n>> include all the partition keys, which must be of the same data type and\n>> have one-to-one matching sets of child partitions.\".\n>> --- unquote\n>> This sentence is general and IMO covers the case this patch considers.\n>> But in general I feel that partitionwise join and aggregation deserve\n>> separate sections next to \"partition pruning\" in [1]; It should mention\n>> advanced partition matching algorithm as well. Would you be willing to\n>> write one and then expand it for the case in the patch?\n>>\n>\n> I don't think it should be part of this patch to add a new section in\n> the docs to explain partitionwise join and aggregation. Maybe that\n> deserves a separate patch?\n>\n\nYes.\n\n3. The testcase added looks artificial. it outputs data that has same value\n>> for two columns which is equal to the primary key of the other table - when\n>> would somebody do that?. Is there some real life example where this change\n>> will be useful?\n>>\n>\n> Hmm, I think the test case is good as long as it reveals the issue that\n> this patch fixes. It follows the same format as the existing test case\n> just above it. I'm not sure if there are real life examples, but I\n> think it may not always be necessary to derive test cases from them.\n>\n\nLet's defer this to the committer.\n\n\n>\n>\n>> Code\n>> ----\n>> Minor comment for now. It will be better to increment num_equal_pks\n>> immediately after setting pk_known_equal[ipk] = true. Otherwise the code\n>> gets confusing around line 2269. I will spend more time reviewing the code\n>> next week.\n>>\n>\n> Hmm, the increment of num_equal_pks on line 2272 is parallel to the one\n> in the first loop (around line 2200). Maybe it's better to keep them\n> consistent as the current patch does?\n>\n>\nIn the first loop, setting pk_known_equal[ipk1] = true and ++num_equal_pks\nhappens on consecutive lines. That's not true in the second loop, where\nthere are at least some code line where num_equal_pks is inconsistent with\nthe number of \"true\" entries in pk_known_equal. We should avoid that.\n\n-- \nBest Wishes,\nAshutosh Bapat\n\nOn Tue, Mar 19, 2024 at 8:18 AM Richard Guo <guofenglinux@gmail.com> wrote:(Sorry it takes me some time to get back to this thread.)On Thu, Mar 7, 2024 at 7:13 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com> wrote:I did a deeper review of the patch. Here are some commentsThank you for the review! Approach--------The equijoin condition between partition keys doesn't appear in the join's restrictilist because of 'best_score' strategy as you explained well in [2]. What if we add an extra score for clauses between partition keys and give preference to equijoin between partition keys? Have you given it a thought? I feel that having an equijoin clause involving partition keys has more usages compared to a clause with any random column. E.g. nextloop may be able to prune partitions from inner relation if the clause contains a partition key.Hmm, I think this approach won't work in cases where one certain pair ofpartition keys has formed an EC that contains pseudoconstants.  In suchcases, the EC machinery will generate restriction clauses like 'pk =const' rather than any join clauses.That should be ok and more desirable. Clauses like pk = const will leave only one partition around in each of the joining relations thus PWJ won't be required OR it will be automatic - whichever way you see it. Besides, it seems to me that it's not a cheap operation to check whethera join clause is between partition keys when we generate join clausesfrom ECs in generate_join_implied_equalities().Why? The code would be the same as what we have in have_partkey_equi_join().   Documentation-------------The patch does not modify any documentation. The only documentation I could find about partitionwise join is the one for GUC 'enable_partitionwise_join'. It says --- quote\"Partitionwise join currently applies only when the join conditions include all the partition keys, which must be of the same data type and have one-to-one matching sets of child partitions.\".--- unquoteThis sentence is general and IMO covers the case this patch considers. But in general I feel that partitionwise join and aggregation deserve separate sections next to \"partition pruning\" in [1]; It should mention advanced partition matching algorithm as well. Would you be willing to write one and then expand it for the case in the patch?I don't think it should be part of this patch to add a new section inthe docs to explain partitionwise join and aggregation.  Maybe thatdeserves a separate patch?Yes.3. The testcase added looks artificial. it outputs data that has same value for two columns which is equal to the primary key of the other table - when would somebody do that?. Is there some real life example where this change will be useful?Hmm, I think the test case is good as long as it reveals the issue thatthis patch fixes.  It follows the same format as the existing test casejust above it.  I'm not sure if there are real life examples, but Ithink it may not always be necessary to derive test cases from them.Let's defer this to the committer.   Code----Minor comment for now. It will be better to increment num_equal_pks immediately after setting pk_known_equal[ipk] = true. Otherwise the code gets confusing around line 2269. I will spend more time reviewing the code next week. Hmm, the increment of num_equal_pks on line 2272 is parallel to the onein the first loop (around line 2200).  Maybe it's better to keep themconsistent as the current patch does?In the first loop, setting pk_known_equal[ipk1] = true and ++num_equal_pks happens on consecutive lines. That's not true in the second loop, where there are at least some code line where num_equal_pks is inconsistent with the number of \"true\" entries in pk_known_equal. We should avoid that.-- Best Wishes,Ashutosh Bapat", "msg_date": "Tue, 19 Mar 2024 13:09:53 +0530", "msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Tue, Mar 19, 2024 at 3:40 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>\nwrote:\n\n> On Tue, Mar 19, 2024 at 8:18 AM Richard Guo <guofenglinux@gmail.com>\n> wrote:\n>\n>> On Thu, Mar 7, 2024 at 7:13 PM Ashutosh Bapat <\n>> ashutosh.bapat.oss@gmail.com> wrote:\n>>\n>>> Approach\n>>> --------\n>>> The equijoin condition between partition keys doesn't appear in the\n>>> join's restrictilist because of 'best_score' strategy as you explained well\n>>> in [2]. What if we add an extra score for clauses between partition keys\n>>> and give preference to equijoin between partition keys? Have you given it a\n>>> thought? I feel that having an equijoin clause involving partition keys has\n>>> more usages compared to a clause with any random column. E.g. nextloop may\n>>> be able to prune partitions from inner relation if the clause contains a\n>>> partition key.\n>>>\n>>\n>> Hmm, I think this approach won't work in cases where one certain pair of\n>> partition keys has formed an EC that contains pseudoconstants. In such\n>> cases, the EC machinery will generate restriction clauses like 'pk =\n>> const' rather than any join clauses.\n>>\n>\n> That should be ok and more desirable. Clauses like pk = const will leave\n> only one partition around in each of the joining relations thus PWJ won't\n> be required OR it will be automatic - whichever way you see it.\n>\n\nNo, that's not true. There could be multiple partition keys, and the\nparticular key involved in the pushed-down restriction 'pk = const' may\nnot be able to prune away any partitions. To be concrete, consider the\nquery:\n\ncreate table p (k1 int, k2 int, val int) partition by range(k1, k2);\ncreate table p_1 partition of p for values from (1,1) to (10,100);\ncreate table p_2 partition of p for values from (10,100) to (20,200);\n\nset enable_partitionwise_join to on;\n\nexplain (costs off)\nselect * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 = bar.k2\nand foo.k2 = 5;\n QUERY PLAN\n-----------------------------------------\n Hash Join\n Hash Cond: (foo.k1 = bar.k1)\n -> Append\n -> Seq Scan on p_1 foo_1\n Filter: (k2 = 5)\n -> Seq Scan on p_2 foo_2\n Filter: (k2 = 5)\n -> Hash\n -> Append\n -> Seq Scan on p_1 bar_1\n Filter: (k2 = 5)\n -> Seq Scan on p_2 bar_2\n Filter: (k2 = 5)\n(13 rows)\n\nThanks\nRichard\n\nOn Tue, Mar 19, 2024 at 3:40 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com> wrote:On Tue, Mar 19, 2024 at 8:18 AM Richard Guo <guofenglinux@gmail.com> wrote:On Thu, Mar 7, 2024 at 7:13 PM Ashutosh Bapat <ashutosh.bapat.oss@gmail.com> wrote:Approach--------The equijoin condition between partition keys doesn't appear in the join's restrictilist because of 'best_score' strategy as you explained well in [2]. What if we add an extra score for clauses between partition keys and give preference to equijoin between partition keys? Have you given it a thought? I feel that having an equijoin clause involving partition keys has more usages compared to a clause with any random column. E.g. nextloop may be able to prune partitions from inner relation if the clause contains a partition key.Hmm, I think this approach won't work in cases where one certain pair ofpartition keys has formed an EC that contains pseudoconstants.  In suchcases, the EC machinery will generate restriction clauses like 'pk =const' rather than any join clauses.That should be ok and more desirable. Clauses like pk = const will leave only one partition around in each of the joining relations thus PWJ won't be required OR it will be automatic - whichever way you see it.No, that's not true.  There could be multiple partition keys, and theparticular key involved in the pushed-down restriction 'pk = const' maynot be able to prune away any partitions.  To be concrete, consider thequery:create table p (k1 int, k2 int, val int) partition by range(k1, k2);create table p_1 partition of p for values from (1,1) to (10,100);create table p_2 partition of p for values from (10,100) to (20,200);set enable_partitionwise_join to on;explain (costs off)select * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 = bar.k2 and foo.k2 = 5;               QUERY PLAN----------------------------------------- Hash Join   Hash Cond: (foo.k1 = bar.k1)   ->  Append         ->  Seq Scan on p_1 foo_1               Filter: (k2 = 5)         ->  Seq Scan on p_2 foo_2               Filter: (k2 = 5)   ->  Hash         ->  Append               ->  Seq Scan on p_1 bar_1                     Filter: (k2 = 5)               ->  Seq Scan on p_2 bar_2                     Filter: (k2 = 5)(13 rows)ThanksRichard", "msg_date": "Mon, 25 Mar 2024 11:30:55 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Mon, Mar 25, 2024 at 9:01 AM Richard Guo <guofenglinux@gmail.com> wrote:\n\n>\n> create table p (k1 int, k2 int, val int) partition by range(k1, k2);\n> create table p_1 partition of p for values from (1,1) to (10,100);\n> create table p_2 partition of p for values from (10,100) to (20,200);\n>\n> set enable_partitionwise_join to on;\n>\n> explain (costs off)\n> select * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 =\n> bar.k2 and foo.k2 = 5;\n> QUERY PLAN\n> -----------------------------------------\n> Hash Join\n> Hash Cond: (foo.k1 = bar.k1)\n> -> Append\n> -> Seq Scan on p_1 foo_1\n> Filter: (k2 = 5)\n> -> Seq Scan on p_2 foo_2\n> Filter: (k2 = 5)\n> -> Hash\n> -> Append\n> -> Seq Scan on p_1 bar_1\n> Filter: (k2 = 5)\n> -> Seq Scan on p_2 bar_2\n> Filter: (k2 = 5)\n> (13 rows)\n>\n\nThanks for the example. You are right.\n\nI think we need some way to avoid two different ways of looking up\npartition keys - if we can't teach the EC machinery to produce clauses with\npartition keys (always), we need to teach EC to contain partition keys in\ncase of outer joins. Tom alluded to this but I haven't seen any proposal.\nThe potential danger with the current patch is that it will continue to\nhave two loops even if we fix one of the above cases in future.\n\n-- \nBest Wishes,\nAshutosh Bapat\n\nOn Mon, Mar 25, 2024 at 9:01 AM Richard Guo <guofenglinux@gmail.com> wrote:create table p (k1 int, k2 int, val int) partition by range(k1, k2);create table p_1 partition of p for values from (1,1) to (10,100);create table p_2 partition of p for values from (10,100) to (20,200);set enable_partitionwise_join to on;explain (costs off)select * from p as foo join p as bar on foo.k1 = bar.k1 and foo.k2 = bar.k2 and foo.k2 = 5;               QUERY PLAN----------------------------------------- Hash Join   Hash Cond: (foo.k1 = bar.k1)   ->  Append         ->  Seq Scan on p_1 foo_1               Filter: (k2 = 5)         ->  Seq Scan on p_2 foo_2               Filter: (k2 = 5)   ->  Hash         ->  Append               ->  Seq Scan on p_1 bar_1                     Filter: (k2 = 5)               ->  Seq Scan on p_2 bar_2                     Filter: (k2 = 5)(13 rows)Thanks for the example. You are right.I think we need some way to avoid two different ways of looking up partition keys - if we can't teach the EC machinery to produce clauses with partition keys (always), we need to teach EC to contain partition keys in case of outer joins. Tom alluded to this but I haven't seen any proposal. The potential danger with the current patch is that it will continue to have two loops even if we fix one of the above cases in future. -- Best Wishes,Ashutosh Bapat", "msg_date": "Mon, 25 Mar 2024 16:39:27 +0530", "msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Wed, Feb 21, 2024 at 6:25 AM Richard Guo <guofenglinux@gmail.com> wrote:\n> This patch was returned due to 'lack of interest'. However, upon\n> verification, it appears that the reported issue still exists, and the\n> proposed fix in the thread remains valid. Hence, resurrect this patch\n> after rebasing it on master. I've also written a detailed commit\n> message which hopefully can help people review the changes more\n> effectively.\n\nI think it's slightly questionable whether this patch is worthwhile.\nThe case memorialized in the regression tests, t1.a = t2.a AND t1.a =\nt2.b, is a very weird thing to do. The case mentioned in the original\nemail, foo.k1 = bar.k1 and foo.k2 = bar.k2 and foo.k2 = 16, seems like\nsomething that could realistically happen, especially when there are\nviews in use (e.g. the view joins foo and bar, and then someone\nqueries the view for one of the join columns). In such a case, it's\npossible that foo.k2 = 16 is selective enough that we really don't\ncare about partition-wise join any more, but it's also possible that\nit's not too selective and we do care about partition-wise join. So I\ndon't think that the case that the patch fixes is something that can\never happen, but I do think it's probably fairly rare that brings any\nbenefit, which is why I thought that EC-based matching was an OK\napproach to this problem initially. Perhaps that was the wrong idea,\nthough.\n\nDoes the additional logic added by this patch have a noticeable\nperformance cost?\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 30 Apr 2024 13:31:09 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Wed, May 1, 2024 at 1:31 AM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> I think it's slightly questionable whether this patch is worthwhile.\n> The case memorialized in the regression tests, t1.a = t2.a AND t1.a =\n> t2.b, is a very weird thing to do. The case mentioned in the original\n> email, foo.k1 = bar.k1 and foo.k2 = bar.k2 and foo.k2 = 16, seems like\n> something that could realistically happen, especially when there are\n> views in use (e.g. the view joins foo and bar, and then someone\n> queries the view for one of the join columns). In such a case, it's\n> possible that foo.k2 = 16 is selective enough that we really don't\n> care about partition-wise join any more, but it's also possible that\n> it's not too selective and we do care about partition-wise join. So I\n> don't think that the case that the patch fixes is something that can\n> ever happen, but I do think it's probably fairly rare that brings any\n> benefit, which is why I thought that EC-based matching was an OK\n> approach to this problem initially. Perhaps that was the wrong idea,\n> though.\n\n\nThank you for taking the time to review this patch! I think Ashutosh\nalso mentioned that the new added test case looks artificial. I must\nadmit that I'm not too sure how common we encounter queries with\npartially-redundant join clauses in real-life scenarios. It is possible\nthat such cases are quite rare, and this patch will then not be of much\nuse.\n\nI initially brought up this issue because I noticed an inconsistency\nregarding the generation of a partition-wise join: with 't1.k = t2.k and\nt1.k = t2.val' we are able to generate a partition-wise join, while its\nequivalent form 't1.k = t2.val and t1.k = t2.k' does not result in a\npartition-wise join. I think this inconsistency could be confusing.\n\nThe reason behind this is that with 't1.k = t2.val and t1.k = t2.k' it\nhappens to constrain other members (t1.k and t2.val) of the EC than the\nones we are looking for (t1.k and t2.k). Our current code looks through\nthe join's restriction clauses for matched keys. In addition to that,\nthis patch checks to see if any unmatched keys are known equal by ECs,\nleveraging function exprs_known_equal().\n\n\n> Does the additional logic added by this patch have a noticeable\n> performance cost?\n\n\nI think one concern regarding performance cost is that the function\nexprs_known_equal() would be called O(N^2) times, where N is the number\nof partition key expressions. But I think this might not be a problem.\nThe number of a joinrel's partition key expressions would only be equal\nto the join degree, since each base relation within the join contributes\nonly one partition key expression, according to\nset_joinrel_partition_key_exprs(). This number would not scale with the\nnumber of partitions. But I have not measured the performance in\npractice by running benchmarks. Maybe I'm just wrong.\n\nThanks\nRichard\n\nOn Wed, May 1, 2024 at 1:31 AM Robert Haas <robertmhaas@gmail.com> wrote:\nI think it's slightly questionable whether this patch is worthwhile.\nThe case memorialized in the regression tests, t1.a = t2.a AND t1.a =\nt2.b, is a very weird thing to do. The case mentioned in the original\nemail, foo.k1 = bar.k1 and foo.k2 = bar.k2 and foo.k2 = 16, seems like\nsomething that could realistically happen, especially when there are\nviews in use (e.g. the view joins foo and bar, and then someone\nqueries the view for one of the join columns). In such a case, it's\npossible that foo.k2 = 16 is selective enough that we really don't\ncare about partition-wise join any more, but it's also possible that\nit's not too selective and we do care about partition-wise join. So I\ndon't think that the case that the patch fixes is something that can\never happen, but I do think it's probably fairly rare that brings any\nbenefit, which is why I thought that EC-based matching was an OK\napproach to this problem initially. Perhaps that was the wrong idea,\nthough.Thank you for taking the time to review this patch!  I think Ashutoshalso mentioned that the new added test case looks artificial.  I mustadmit that I'm not too sure how common we encounter queries withpartially-redundant join clauses in real-life scenarios.  It is possiblethat such cases are quite rare, and this patch will then not be of muchuse.I initially brought up this issue because I noticed an inconsistencyregarding the generation of a partition-wise join: with 't1.k = t2.k andt1.k = t2.val' we are able to generate a partition-wise join, while itsequivalent form 't1.k = t2.val and t1.k = t2.k' does not result in apartition-wise join.  I think this inconsistency could be confusing.The reason behind this is that with 't1.k = t2.val and t1.k = t2.k' ithappens to constrain other members (t1.k and t2.val) of the EC than theones we are looking for (t1.k and t2.k).  Our current code looks throughthe join's restriction clauses for matched keys.  In addition to that,this patch checks to see if any unmatched keys are known equal by ECs,leveraging function exprs_known_equal(). \nDoes the additional logic added by this patch have a noticeable\nperformance cost?I think one concern regarding performance cost is that the functionexprs_known_equal() would be called O(N^2) times, where N is the numberof partition key expressions.  But I think this might not be a problem.The number of a joinrel's partition key expressions would only be equalto the join degree, since each base relation within the join contributesonly one partition key expression, according toset_joinrel_partition_key_exprs().  This number would not scale with thenumber of partitions.  But I have not measured the performance inpractice by running benchmarks.  Maybe I'm just wrong.ThanksRichard", "msg_date": "Fri, 3 May 2024 19:47:45 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Fri, May 3, 2024 at 7:47 AM Richard Guo <guofenglinux@gmail.com> wrote:\n>> Does the additional logic added by this patch have a noticeable\n>> performance cost?\n>\n> I think one concern regarding performance cost is that the function\n> exprs_known_equal() would be called O(N^2) times, where N is the number\n> of partition key expressions. But I think this might not be a problem.\n> The number of a joinrel's partition key expressions would only be equal\n> to the join degree, since each base relation within the join contributes\n> only one partition key expression, according to\n> set_joinrel_partition_key_exprs(). This number would not scale with the\n> number of partitions. But I have not measured the performance in\n> practice by running benchmarks. Maybe I'm just wrong.\n\nI don't know, but I do think you should do some benchmarking and see\nif you can find cases where this regresses performance. In my opinion,\nthis feature is worth having only if it's basically free. There's lots\nof things we could do in the planner that would give better (perhaps\nmuch better) plans in certain cases, but which we don't do because in\nall other cases we'd pay a certain number of CPU cycles to have them\nand it just doesn't make sense given how often we'd actually get a\nbenefit. This might be another such case.\n\nI agree with you that the number of partition key expressions is\nlikely to be small, but that doesn't mean there's no problem. A big\npart of the value of equivalence classes is that they let us make\ndeductions cheaply. Replacing that with some more complex matching\nmechanism probably has a cost, and maybe that cost is material. If\nit's not quite material with one partition key expression, going up to\n2 or 3 of them might make it matter.\n\n-- \nRobert Haas\nEDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Fri, 3 May 2024 09:31:24 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Fri, May 3, 2024 at 9:31 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Fri, May 3, 2024 at 7:47 AM Richard Guo <guofenglinux@gmail.com> wrote:\n> > I think one concern regarding performance cost is that the function\n> > exprs_known_equal() would be called O(N^2) times, where N is the number\n> > of partition key expressions. But I think this might not be a problem.\n> > The number of a joinrel's partition key expressions would only be equal\n> > to the join degree, since each base relation within the join contributes\n> > only one partition key expression, according to\n> > set_joinrel_partition_key_exprs(). This number would not scale with the\n> > number of partitions. But I have not measured the performance in\n> > practice by running benchmarks. Maybe I'm just wrong.\n>\n> I don't know, but I do think you should do some benchmarking and see\n> if you can find cases where this regresses performance. In my opinion,\n> this feature is worth having only if it's basically free. There's lots\n> of things we could do in the planner that would give better (perhaps\n> much better) plans in certain cases, but which we don't do because in\n> all other cases we'd pay a certain number of CPU cycles to have them\n> and it just doesn't make sense given how often we'd actually get a\n> benefit. This might be another such case.\n\n\nThank you for the suggestion. In order to obtain a rough estimation of\nhow this patch affects planning time, I did the following benchmarking:\n\n* create a partitioned table with 3 keys and 1000 partitions, which\nlooks like\n\n Partitioned table \"public.t1_parted\"\n Column | Type | Collation | Nullable | Default\n--------+---------+-----------+----------+---------\n a | integer | | |\n b | integer | | |\n c | integer | | |\n d | integer | | |\nPartition key: RANGE (a, b, c)\nNumber of partitions: 1000 (Use \\d+ to list them.)\n\n* compose a query involving 5-way joins of this partitioned table, which\nlooks like:\n\nselect * from t1_parted t1\n natural join t1_parted t2\n natural join t1_parted t3\n natural join t1_parted t4\n natural join t1_parted t5\nwhere t1.b = 1 and t1.c = 2;\n\nThis query is composed in such a way that it could actually generate\npartitionwise join, because there exist equi-join condition for each\npair of matching partition keys; but currently on master it is not able\nto generate partitionwise join, because of the filters 't1.b = 1 and\nt1.c = 2', which is the issue fixed by this patch.\n\n* run this query 5 times with enable_partitionwise_join set to on, and\ncollect the average planning time on master and on patched.\n\nTo ensure fairness, on master, a little hack is required to enable the\ngeneration of partitionwise join for this query. This allows us to\neliminate any potential impact on planning partitionwise joins and\nevaluate the effects of this patch accurately.\n\nBelow is what I got on my local machine.\n\n-- on master\n\n measurement | average | maximum | minimum | std_dev |\nstd_dev_as_perc_of_avg\n---------------+----------+----------+----------+---------+------------------------\n planning time | 30355.07 | 33148.47 | 29020.82 | 1681.23 | 5.54%\n\n\n-- on patched\n\n measurement | average | maximum | minimum | std_dev |\nstd_dev_as_perc_of_avg\n---------------+----------+----------+----------+---------+------------------------\n planning time | 30600.00 | 33523.23 | 28680.75 | 1861.90 | 6.08%\n\n\n-- without partitionwise join\n\n measurement | average | maximum | minimum | std_dev |\nstd_dev_as_perc_of_avg\n---------------+---------+---------+---------+---------+------------------------\n planning time | 4840.18 | 5184.05 | 4528.87 | 299.98 | 6.20%\n\n\nSo it seems that the planning time is not significantly affected by this\npatch, particularly when compared to the impact caused by partitionwise\njoin.\n\nBTW, I was using Ashutosh's script [1] for setting up the benchmarking.\nI find the script very handy.\n\n[1]\nhttps://www.postgresql.org/message-id/flat/CAExHW5s%3DbCLMMq8n_bN6iU%2BPjau0DS3z_6Dn6iLE69ESmsPMJQ%40mail.gmail.com\n\nThanks\nRichard\n\nOn Fri, May 3, 2024 at 9:31 PM Robert Haas <robertmhaas@gmail.com> wrote:On Fri, May 3, 2024 at 7:47 AM Richard Guo <guofenglinux@gmail.com> wrote:\n> I think one concern regarding performance cost is that the function\n> exprs_known_equal() would be called O(N^2) times, where N is the number\n> of partition key expressions.  But I think this might not be a problem.\n> The number of a joinrel's partition key expressions would only be equal\n> to the join degree, since each base relation within the join contributes\n> only one partition key expression, according to\n> set_joinrel_partition_key_exprs().  This number would not scale with the\n> number of partitions.  But I have not measured the performance in\n> practice by running benchmarks.  Maybe I'm just wrong.\n\nI don't know, but I do think you should do some benchmarking and see\nif you can find cases where this regresses performance. In my opinion,\nthis feature is worth having only if it's basically free. There's lots\nof things we could do in the planner that would give better (perhaps\nmuch better) plans in certain cases, but which we don't do because in\nall other cases we'd pay a certain number of CPU cycles to have them\nand it just doesn't make sense given how often we'd actually get a\nbenefit. This might be another such case.Thank you for the suggestion.  In order to obtain a rough estimation ofhow this patch affects planning time, I did the following benchmarking:* create a partitioned table with 3 keys and 1000 partitions, whichlooks like       Partitioned table \"public.t1_parted\" Column |  Type   | Collation | Nullable | Default--------+---------+-----------+----------+--------- a      | integer |           |          | b      | integer |           |          | c      | integer |           |          | d      | integer |           |          |Partition key: RANGE (a, b, c)Number of partitions: 1000 (Use \\d+ to list them.)* compose a query involving 5-way joins of this partitioned table, whichlooks like:select * from t1_parted t1 natural join t1_parted t2 natural join t1_parted t3 natural join t1_parted t4 natural join t1_parted t5where t1.b = 1 and t1.c = 2;This query is composed in such a way that it could actually generatepartitionwise join, because there exist equi-join condition for eachpair of matching partition keys; but currently on master it is not ableto generate partitionwise join, because of the filters 't1.b = 1 andt1.c = 2', which is the issue fixed by this patch.* run this query 5 times with enable_partitionwise_join set to on, andcollect the average planning time on master and on patched.To ensure fairness, on master, a little hack is required to enable thegeneration of partitionwise join for this query.  This allows us toeliminate any potential impact on planning partitionwise joins andevaluate the effects of this patch accurately.Below is what I got on my local machine.-- on master  measurement  | average  | maximum  | minimum  | std_dev | std_dev_as_perc_of_avg---------------+----------+----------+----------+---------+------------------------ planning time | 30355.07 | 33148.47 | 29020.82 | 1681.23 | 5.54%-- on patched  measurement  | average  | maximum  | minimum  | std_dev | std_dev_as_perc_of_avg---------------+----------+----------+----------+---------+------------------------ planning time | 30600.00 | 33523.23 | 28680.75 | 1861.90 | 6.08%-- without partitionwise join  measurement  | average | maximum | minimum | std_dev | std_dev_as_perc_of_avg---------------+---------+---------+---------+---------+------------------------ planning time | 4840.18 | 5184.05 | 4528.87 | 299.98  | 6.20%So it seems that the planning time is not significantly affected by thispatch, particularly when compared to the impact caused by partitionwisejoin.BTW, I was using Ashutosh's script [1] for setting up the benchmarking.I find the script very handy.[1] https://www.postgresql.org/message-id/flat/CAExHW5s%3DbCLMMq8n_bN6iU%2BPjau0DS3z_6Dn6iLE69ESmsPMJQ%40mail.gmail.comThanksRichard", "msg_date": "Wed, 8 May 2024 17:01:51 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Wed, May 8, 2024 at 5:01 PM Richard Guo <guofenglinux@gmail.com> wrote:\n> Below is what I got on my local machine.\n>\n> -- on master\n>\n> measurement | average | maximum | minimum | std_dev | std_dev_as_perc_of_avg\n> ---------------+----------+----------+----------+---------+------------------------\n> planning time | 30355.07 | 33148.47 | 29020.82 | 1681.23 | 5.54%\n>\n>\n> -- on patched\n>\n> measurement | average | maximum | minimum | std_dev | std_dev_as_perc_of_avg\n> ---------------+----------+----------+----------+---------+------------------------\n> planning time | 30600.00 | 33523.23 | 28680.75 | 1861.90 | 6.08%\n>\n>\n> -- without partitionwise join\n>\n> measurement | average | maximum | minimum | std_dev | std_dev_as_perc_of_avg\n> ---------------+---------+---------+---------+---------+------------------------\n> planning time | 4840.18 | 5184.05 | 4528.87 | 299.98 | 6.20%\n>\n>\n> So it seems that the planning time is not significantly affected by this\n> patch, particularly when compared to the impact caused by partitionwise\n> join.\n\nThis benchmark shows that the impact of this patch on planning time is\nwithin the margin of error, particularly compared to the impact of\npartitionwise joins. So I've pushed this patch after working a bit\nmore on the commit message.\n\nThanks\nRichard\n\n\n", "msg_date": "Tue, 30 Jul 2024 15:36:00 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Sat, Aug 10, 2024 at 6:22 AM Alexey Dvoichenkov\n<alexey@hyperplane.net> wrote:\n> I haven't read the entire thread so I might be missing something, but\n> one interesting consequence of this patch is that it kind of breaks\n> the initial pruning of generic plans. Given a query such as SELECT\n> ... WHERE A.PK = B.PK AND A.PK = $1 the planner will do the right\n> thing for custom plans, but not for GPs since the existing logic is\n> not capable of pruning anything more complex than a scan. See the\n> attached example.\n\nThanks for the report! I see what the problem is. Previously, for a\njoin with filter 'WHERE A.PK = B.PK AND A.PK = $1', the planner was\nunable to generate partitionwise join, because it failed to realize\nthat there exists an equi-join condition between A.PK and B.PK. As a\nresult, the prepared statement 'ps' was planned as a join of two\nAppends in generic mode:\n\n Nested Loop\n -> Append\n -> Seq Scan on a0 a_1\n Filter: (x = $1)\n -> Seq Scan on a1 a_2\n Filter: (x = $1)\n -> Materialize\n -> Append\n -> Seq Scan on b0 b_1\n Filter: (x = $1)\n -> Seq Scan on b1 b_2\n Filter: (x = $1)\n\n... and then one of the subpaths for each Append node would be pruned\nduring initial pruning phase, so you'd get:\n\n Nested Loop\n -> Append\n Subplans Removed: 1\n -> Seq Scan on a0 a_1\n Filter: (x = $1)\n -> Materialize\n -> Append\n Subplans Removed: 1\n -> Seq Scan on b0 b_1\n Filter: (x = $1)\n\nWith this patch, the planner is able to generate partitionwise join,\nas it can recognize the equi-join condition between A.PK and B.PK from\nECs. So the prepared statement 'ps' is planned as an Append of two\njoins in generic mode:\n\n Append\n -> Nested Loop\n -> Seq Scan on a0 a_1\n Filter: (x = $1)\n -> Seq Scan on b0 b_1\n Filter: (x = $1)\n -> Nested Loop\n -> Seq Scan on a1 a_2\n Filter: (x = $1)\n -> Seq Scan on b1 b_2\n Filter: (x = $1)\n\n... and neither subpath of this Append can be pruned during the\ninitial pruning phase.\n\nIt seems to me that this is not the fault of this patch: it fixes the\npartitionwise join as expected. The ideal fix to this issue is, IMO,\nto take initial pruning into account when calculating costs, so we can\npick the non-partitionwise-join path and then apply the initial\npruning if that is cheaper. Of course we also need to fix\napply_scanjoin_target_to_paths to not drop old paths of partitioned\njoinrels so that we can retain non-partitionwise-join paths if\nthe cheapest path happens to be among them. This work is being\ndiscussed in [1].\n\nFor now, I think you can work around this issue by setting\nenable_partitionwise_join to off for this query, if that works for\nyou.\n\n[1] https://postgr.es/m/CAExHW5toze58+jL-454J3ty11sqJyU13Sz5rJPQZDmASwZgWiA@mail.gmail.com\n\nThanks\nRichard\n\n\n", "msg_date": "Mon, 12 Aug 2024 11:19:55 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Mon, Mar 25, 2024 at 7:09 PM Ashutosh Bapat\n<ashutosh.bapat.oss@gmail.com> wrote:\n> I think we need some way to avoid two different ways of looking up partition keys - if we can't teach the EC machinery to produce clauses with partition keys (always), we need to teach EC to contain partition keys in case of outer joins. Tom alluded to this but I haven't seen any proposal. The potential danger with the current patch is that it will continue to have two loops even if we fix one of the above cases in future.\n\nSorry for not replying to this comment before pushing the patch. I\nunderstand your concern and agree that it would be ideal if the\npartitionwise join matching logic relied solely on ECs. However,\nimplementing that would require a lot of changes to the EC mechanism,\nand I'm not sure if that will happen in the near future. And if we do\nachieve this in the future, I believe many parts of the code, not just\nthe loops here, will need to be modified to leverage the new EC\nmechanism.\n\nThanks\nRichard\n\n\n", "msg_date": "Mon, 12 Aug 2024 11:54:32 +0800", "msg_from": "Richard Guo <guofenglinux@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" }, { "msg_contents": "On Mon, Aug 12, 2024 at 8:50 AM Richard Guo <guofenglinux@gmail.com> wrote:\n>\n> On Sat, Aug 10, 2024 at 6:22 AM Alexey Dvoichenkov\n> <alexey@hyperplane.net> wrote:\n> > I haven't read the entire thread so I might be missing something, but\n> > one interesting consequence of this patch is that it kind of breaks\n> > the initial pruning of generic plans. Given a query such as SELECT\n> > ... WHERE A.PK = B.PK AND A.PK = $1 the planner will do the right\n> > thing for custom plans, but not for GPs since the existing logic is\n> > not capable of pruning anything more complex than a scan. See the\n> > attached example.\n>\n> Thanks for the report! I see what the problem is. Previously, for a\n> join with filter 'WHERE A.PK = B.PK AND A.PK = $1', the planner was\n> unable to generate partitionwise join, because it failed to realize\n> that there exists an equi-join condition between A.PK and B.PK. As a\n> result, the prepared statement 'ps' was planned as a join of two\n> Appends in generic mode:\n>\n> Nested Loop\n> -> Append\n> -> Seq Scan on a0 a_1\n> Filter: (x = $1)\n> -> Seq Scan on a1 a_2\n> Filter: (x = $1)\n> -> Materialize\n> -> Append\n> -> Seq Scan on b0 b_1\n> Filter: (x = $1)\n> -> Seq Scan on b1 b_2\n> Filter: (x = $1)\n>\n> ... and then one of the subpaths for each Append node would be pruned\n> during initial pruning phase, so you'd get:\n>\n> Nested Loop\n> -> Append\n> Subplans Removed: 1\n> -> Seq Scan on a0 a_1\n> Filter: (x = $1)\n> -> Materialize\n> -> Append\n> Subplans Removed: 1\n> -> Seq Scan on b0 b_1\n> Filter: (x = $1)\n>\n> With this patch, the planner is able to generate partitionwise join,\n> as it can recognize the equi-join condition between A.PK and B.PK from\n> ECs. So the prepared statement 'ps' is planned as an Append of two\n> joins in generic mode:\n>\n> Append\n> -> Nested Loop\n> -> Seq Scan on a0 a_1\n> Filter: (x = $1)\n> -> Seq Scan on b0 b_1\n> Filter: (x = $1)\n> -> Nested Loop\n> -> Seq Scan on a1 a_2\n> Filter: (x = $1)\n> -> Seq Scan on b1 b_2\n> Filter: (x = $1)\n>\n> ... and neither subpath of this Append can be pruned during the\n> initial pruning phase.\n>\n> It seems to me that this is not the fault of this patch: it fixes the\n> partitionwise join as expected. The ideal fix to this issue is, IMO,\n> to take initial pruning into account when calculating costs, so we can\n> pick the non-partitionwise-join path and then apply the initial\n> pruning if that is cheaper.\n\nThis will be fine if the number of surviving partitions is only 1 (or\nat most a couple), but in case the number of surviving partitions\nafter pruning are more than a handful, partitionwise join + runtime\npartition pruning will be required.\n\n> Of course we also need to fix\n> apply_scanjoin_target_to_paths to not drop old paths of partitioned\n> joinrels so that we can retain non-partitionwise-join paths if\n> the cheapest path happens to be among them. This work is being\n> discussed in [1].\n\nRight.\n\n-- \nBest Wishes,\nAshutosh Bapat\n\n\n", "msg_date": "Mon, 12 Aug 2024 14:40:58 +0530", "msg_from": "Ashutosh Bapat <ashutosh.bapat.oss@gmail.com>", "msg_from_op": false, "msg_subject": "Re: A problem about partitionwise join" } ]
[ { "msg_contents": "Hello,\n\none of the most frustating things when I started with PostgreSQL was \nthat IDENTITY columns are based on sequences that are completly \ndisconnected from the table contents and manually imported data will \nlead to errors like 'duplicate key value violates unique constraint \n\"xyz_pkey\"'.\n\nI had to fight this initially with an insert trigger that always updates \nthe sequences on each insert, or with client side code that updates the \nsequence when such an error occurs and then retries the insert.\n\nEven Microsoft Access did a better job at autogenerated primaries keys, \nand while I love the elegant design of PostgreSQL in many ways I believe \nwe can do better here. I would like to implement a fallback solution \nthat detects such errors and automatically updates the nextvalue of the \nsequence when the nextvalue is already used on insert.\n\nI believe this can be implemented without affecting performance \nnegatively when one just does extra stuff in the error case, so I \nwouldn't do table scans when creating the insert initially.\n\nAny reasons why this isn't a good idea to try?\n\nRegards,\nDaniel Migowski\n\n\n\n", "msg_date": "Mon, 26 Aug 2019 13:28:47 +0200", "msg_from": "Daniel Migowski <dmigowski@ikoffice.de>", "msg_from_op": true, "msg_subject": "Proposal: Better generation of values in GENERATED columns." }, { "msg_contents": "On 2019-08-26 13:28, Daniel Migowski wrote:\n> I would like to implement a fallback solution \n> that detects such errors and automatically updates the nextvalue of the \n> sequence when the nextvalue is already used on insert.\n\nISTM that such a system would likely have many of the same problems as\nthe often-proposed ignore-errors mode for COPY, namely that you can't\ncatch errors and do something else other than rethrowing the error.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 26 Aug 2019 19:18:55 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Proposal: Better generation of values in GENERATED columns." }, { "msg_contents": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> On 2019-08-26 13:28, Daniel Migowski wrote:\n>> I would like to implement a fallback solution \n>> that detects such errors and automatically updates the nextvalue of the \n>> sequence when the nextvalue is already used on insert.\n\n> ISTM that such a system would likely have many of the same problems as\n> the often-proposed ignore-errors mode for COPY, namely that you can't\n> catch errors and do something else other than rethrowing the error.\n\nIn principle you could probably use the same infrastructure used by\nON CONFLICT to detect the unique-key violation. But ON CONFLICT is\nmighty complicated, and not very cheap either. I don't for one second\nbelieve Daniel's assertion that this could be done without a\nsignificant COPY performance hit.\n\nI'm also dubious that the right response to a duplicate key would be\nas simple as \"try the next nextval() result\". I for one wouldn't be\nsatisfied with waiting for COPY to grind through a few thousand/million\nsequential nextval values before finding one that doesn't conflict with\nthe existing table entries.\n\nThe actually-sound advice for loading data that might have conflicting\nserial values is to do the equivalent of\n\n\tsetval('sequence', max(existing keys) + 1)\n\nbefore you start loading. I wonder whether there's a way to make that\nsimpler.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 26 Aug 2019 13:46:41 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Proposal: Better generation of values in GENERATED columns." } ]
[ { "msg_contents": "Hi\n\nI would like to check that postgresql is compatible with TLS 1.2.\nwhat test could I do to check this compatibility?\n\nThanks in advance\n\nBest Regards\nDidier ROS\nEDF\nCe message et toutes les pièces jointes (ci-après le 'Message') sont établis à l'intention exclusive des destinataires et les informations qui y figurent sont strictement confidentielles. Toute utilisation de ce Message non conforme à sa destination, toute diffusion ou toute publication totale ou partielle, est interdite sauf autorisation expresse.\n\nSi vous n'êtes pas le destinataire de ce Message, il vous est interdit de le copier, de le faire suivre, de le divulguer ou d'en utiliser tout ou partie. Si vous avez reçu ce Message par erreur, merci de le supprimer de votre système, ainsi que toutes ses copies, et de n'en garder aucune trace sur quelque support que ce soit. Nous vous remercions également d'en avertir immédiatement l'expéditeur par retour du message.\n\nIl est impossible de garantir que les communications par messagerie électronique arrivent en temps utile, sont sécurisées ou dénuées de toute erreur ou virus.\n____________________________________________________\n\nThis message and any attachments (the 'Message') are intended solely for the addressees. The information contained in this Message is confidential. Any use of information contained in this Message not in accord with its purpose, any dissemination or disclosure, either whole or partial, is prohibited except formal approval.\n\nIf you are not the addressee, you may not copy, forward, disclose or use any part of it. If you have received this message in error, please delete it and all copies from your system and notify the sender immediately by return message.\n\nE-mail communication cannot be guaranteed to be timely secure, error or virus-free.", "msg_date": "Mon, 26 Aug 2019 14:10:37 +0000", "msg_from": "ROS Didier <didier.ros@edf.fr>", "msg_from_op": true, "msg_subject": "PostgreSQL and TLS 1.2" }, { "msg_contents": "On 8/26/19 10:10 AM, ROS Didier wrote:\n> Hi\n> \n> I would like to check that postgresql is compatible with TLS 1.2.\n> what test could I do to check this compatibility?\n\nHi,\n\nI just now pointed this command at our PG 9.5 server at $work:\n\nopenssl s_client -connect dbhost:5432 -starttls postgres\n\nand got the following response (excerpted for the relevant parts):\n\nSSL handshake has read 5465 bytes and written 737 bytes\nVerification: OK\n---\nNew, TLSv1.3, Cipher is TLS_AES_256_GCM_SHA384\n\n\nThen I tried this version:\n\nopenssl s_client -connect dbhost:5432 -starttls postgres -tls1_2\n\nand got this result:\n\nSSL handshake has read 5258 bytes and written 343 bytes\nVerification: OK\n---\nNew, TLSv1.2, Cipher is ECDHE-RSA-AES256-GCM-SHA384\n\n\nRegards,\n-Chap\n\n\n", "msg_date": "Mon, 26 Aug 2019 10:31:07 -0400", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": false, "msg_subject": "Re: PostgreSQL and TLS 1.2" } ]
[ { "msg_contents": "OK, let's try this again :)\n\nThis is work mainly based in the first version of the online checksums\npatch, but based on top of Andres WIP patchset for global barriers (\nhttps://www.postgresql.org/message-id/20181030051643.elbxjww5jjgnjaxg%40alap3.anarazel.de\n)\n\nAndres patch has been enhanced with wait events per\nhttps://www.postgresql.org/message-id/CABUevEwy4LUFqePC5YzanwtzyDDpYvgrj6R5WNznwrO5ouVg1w%40mail.gmail.com\n.\n\nI'm including both those as attachments here to hopefully trick the cfbot\ninto being able to build things :)\n\nOther than that, we believe that the list of objections from the first one\nshould be covered by now, but it's been quite some time and many emails, so\nit's possible we missed some. So if you find them, point them out!\n\nDocumentation needs another go-over in particular base don changes since,\nbut the basic principles of how it works should not have changed.\n\n//Magnus & Daniel", "msg_date": "Mon, 26 Aug 2019 20:56:35 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "Online checksums patch - once again" }, { "msg_contents": "On 2019-Aug-26, Magnus Hagander wrote:\n\n> OK, let's try this again :)\n> \n> This is work mainly based in the first version of the online checksums\n> patch, but based on top of Andres WIP patchset for global barriers (\n> https://www.postgresql.org/message-id/20181030051643.elbxjww5jjgnjaxg%40alap3.anarazel.de\n> )\n> \n> Andres patch has been enhanced with wait events per\n> https://www.postgresql.org/message-id/CABUevEwy4LUFqePC5YzanwtzyDDpYvgrj6R5WNznwrO5ouVg1w%40mail.gmail.com\n> .\n\nTravis says your SGML doesn't compile (maybe you just forgot to \"git\nadd\" and edit allfiles.sgml?):\n\n/usr/bin/xmllint --path . --noout --valid postgres.sgml\nreference.sgml:287: parser error : Entity 'pgVerifyChecksums' not defined\n &pgVerifyChecksums;\n ^\nreference.sgml:295: parser error : chunk is not well balanced\npostgres.sgml:231: parser error : Failure to process entity reference\n &reference;\n ^\npostgres.sgml:231: parser error : Entity 'reference' not defined\n &reference;\n ^\n\nOther than bots, this patch doesn't seem to have attracted any reviewers\nthis time around. Perhaps you need to bribe someone? (Maybe \"how sad\nyour committer SSH key stopped working\" would do?)\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 26 Sep 2019 16:48:28 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Thu, Sep 26, 2019 at 9:48 PM Alvaro Herrera <alvherre@2ndquadrant.com>\nwrote:\n\n> On 2019-Aug-26, Magnus Hagander wrote:\n>\n> > OK, let's try this again :)\n> >\n> > This is work mainly based in the first version of the online checksums\n> > patch, but based on top of Andres WIP patchset for global barriers (\n> >\n> https://www.postgresql.org/message-id/20181030051643.elbxjww5jjgnjaxg%40alap3.anarazel.de\n> > )\n> >\n> > Andres patch has been enhanced with wait events per\n> >\n> https://www.postgresql.org/message-id/CABUevEwy4LUFqePC5YzanwtzyDDpYvgrj6R5WNznwrO5ouVg1w%40mail.gmail.com\n> > .\n>\n> Travis says your SGML doesn't compile (maybe you just forgot to \"git\n> add\" and edit allfiles.sgml?):\n>\n\nNope, even easier -- the reference pgVerifyChecksums was renamed to\npgChecksums and for some reason we missed that in the merge.\n\nI've rebased again on top of todays master, but that was the only change I\nhad to make.\n\n\nOther than bots, this patch doesn't seem to have attracted any reviewers\n> this time around. Perhaps you need to bribe someone? (Maybe \"how sad\n> your committer SSH key stopped working\" would do?)\n>\n\nHmm. I don't think that's a bribe, that's a threat. However, maybe it will\nwork.\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/ <http://www.hagander.net/>\n Work: https://www.redpill-linpro.com/ <http://www.redpill-linpro.com/>", "msg_date": "Mon, 30 Sep 2019 13:03:20 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Mon, Sep 30, 2019 at 01:03:20PM +0200, Magnus Hagander wrote:\n>On Thu, Sep 26, 2019 at 9:48 PM Alvaro Herrera <alvherre@2ndquadrant.com>\n>wrote:\n>\n>> On 2019-Aug-26, Magnus Hagander wrote:\n>>\n>> > OK, let's try this again :)\n>> >\n>> > This is work mainly based in the first version of the online checksums\n>> > patch, but based on top of Andres WIP patchset for global barriers (\n>> >\n>> https://www.postgresql.org/message-id/20181030051643.elbxjww5jjgnjaxg%40alap3.anarazel.de\n>> > )\n>> >\n>> > Andres patch has been enhanced with wait events per\n>> >\n>> https://www.postgresql.org/message-id/CABUevEwy4LUFqePC5YzanwtzyDDpYvgrj6R5WNznwrO5ouVg1w%40mail.gmail.com\n>> > .\n>>\n>> Travis says your SGML doesn't compile (maybe you just forgot to \"git\n>> add\" and edit allfiles.sgml?):\n>>\n>\n>Nope, even easier -- the reference pgVerifyChecksums was renamed to\n>pgChecksums and for some reason we missed that in the merge.\n>\n>I've rebased again on top of todays master, but that was the only change I\n>had to make.\n>\n>\n>Other than bots, this patch doesn't seem to have attracted any reviewers\n>> this time around. Perhaps you need to bribe someone? (Maybe \"how sad\n>> your committer SSH key stopped working\" would do?)\n>>\n>\n>Hmm. I don't think that's a bribe, that's a threat. However, maybe it will\n>work.\n>\n\nIMHO the patch is ready to go - I think the global barrier solves the\nissue in the previous version, and that's the only problem I'm aware of.\nSo +1 from me to go ahead and push it.\n\nAnd now please uncomment my commit SSH key again, please ;-)\n\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 30 Sep 2019 14:49:44 +0200", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Mon, Sep 30, 2019 at 02:49:44PM +0200, Tomas Vondra wrote:\n> On Mon, Sep 30, 2019 at 01:03:20PM +0200, Magnus Hagander wrote:\n> > Other than bots, this patch doesn't seem to have attracted any reviewers\n> > > this time around. Perhaps you need to bribe someone? (Maybe \"how sad\n> > > your committer SSH key stopped working\" would do?)\n> > > \n> > \n> > Hmm. I don't think that's a bribe, that's a threat. However, maybe it will\n> > work.\n> > \n> \n> IMHO the patch is ready to go - I think the global barrier solves the\n> issue in the previous version, and that's the only problem I'm aware of.\n> So +1 from me to go ahead and push it.\n> \n> And now please uncomment my commit SSH key again, please ;-)\n\nFor adding cluster-level encryption to Postgres, the plan is to create a\nstandby that has encryption enabled, then switchover to it. Is that a\nmethod we support now for adding checksums to Postgres? Do we need the\nability to do it in-place too?\n\n-- \n Bruce Momjian <bruce@momjian.us> http://momjian.us\n EnterpriseDB http://enterprisedb.com\n\n+ As you are, so once was I. As I am, so you will be. +\n+ Ancient Roman grave inscription +\n\n\n", "msg_date": "Mon, 30 Sep 2019 10:53:13 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Mon, Sep 30, 2019 at 4:53 PM Bruce Momjian <bruce@momjian.us> wrote:\n\n> On Mon, Sep 30, 2019 at 02:49:44PM +0200, Tomas Vondra wrote:\n> > On Mon, Sep 30, 2019 at 01:03:20PM +0200, Magnus Hagander wrote:\n> > > Other than bots, this patch doesn't seem to have attracted any\n> reviewers\n> > > > this time around. Perhaps you need to bribe someone? (Maybe \"how\n> sad\n> > > > your committer SSH key stopped working\" would do?)\n> > > >\n> > >\n> > > Hmm. I don't think that's a bribe, that's a threat. However, maybe it\n> will\n> > > work.\n> > >\n> >\n> > IMHO the patch is ready to go - I think the global barrier solves the\n> > issue in the previous version, and that's the only problem I'm aware of.\n> > So +1 from me to go ahead and push it.\n> >\n> > And now please uncomment my commit SSH key again, please ;-)\n>\n> For adding cluster-level encryption to Postgres, the plan is to create a\n> standby that has encryption enabled, then switchover to it. Is that a\n> method we support now for adding checksums to Postgres? Do we need the\n> ability to do it in-place too?\n>\n\nI definitely think we need the ability to do it in-place as well, yes.\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/ <http://www.hagander.net/>\n Work: https://www.redpill-linpro.com/ <http://www.redpill-linpro.com/>\n\nOn Mon, Sep 30, 2019 at 4:53 PM Bruce Momjian <bruce@momjian.us> wrote:On Mon, Sep 30, 2019 at 02:49:44PM +0200, Tomas Vondra wrote:\n> On Mon, Sep 30, 2019 at 01:03:20PM +0200, Magnus Hagander wrote:\n> > Other than bots, this patch doesn't seem to have attracted any reviewers\n> > > this time around.  Perhaps you need to bribe someone?  (Maybe \"how sad\n> > > your committer SSH key stopped working\" would do?)\n> > > \n> > \n> > Hmm. I don't think that's a bribe, that's a threat. However, maybe it will\n> > work.\n> > \n> \n> IMHO the patch is ready to go - I think the global barrier solves the\n> issue in the previous version, and that's the only problem I'm aware of.\n> So +1 from me to go ahead and push it.\n> \n> And now please uncomment my commit SSH key again, please ;-)\n\nFor adding cluster-level encryption to Postgres, the plan is to create a\nstandby that has encryption enabled, then switchover to it.  Is that a\nmethod we support now for adding checksums to Postgres?  Do we need the\nability to do it in-place too?I definitely think we need the ability to do it in-place as well, yes. --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Mon, 30 Sep 2019 16:57:41 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Mon, Sep 30, 2019 at 04:57:41PM +0200, Magnus Hagander wrote:\n> \n> \n> On Mon, Sep 30, 2019 at 4:53 PM Bruce Momjian <bruce@momjian.us> wrote:\n> \n> On Mon, Sep 30, 2019 at 02:49:44PM +0200, Tomas Vondra wrote:\n> > On Mon, Sep 30, 2019 at 01:03:20PM +0200, Magnus Hagander wrote:\n> > > Other than bots, this patch doesn't seem to have attracted any\n> reviewers\n> > > > this time around.� Perhaps you need to bribe someone?� (Maybe \"how\n> sad\n> > > > your committer SSH key stopped working\" would do?)\n> > > >\n> > >\n> > > Hmm. I don't think that's a bribe, that's a threat. However, maybe it\n> will\n> > > work.\n> > >\n> >\n> > IMHO the patch is ready to go - I think the global barrier solves the\n> > issue in the previous version, and that's the only problem I'm aware of.\n> > So +1 from me to go ahead and push it.\n> >\n> > And now please uncomment my commit SSH key again, please ;-)\n> \n> For adding cluster-level encryption to Postgres, the plan is to create a\n> standby that has encryption enabled, then switchover to it.� Is that a\n> method we support now for adding checksums to Postgres?� Do we need the\n> ability to do it in-place too?\n> \n> \n> I definitely think we need the ability to do it in-place as well, yes.�\n\nOK, just has to ask. I think for encryption, for the first version, we\nwill do just replica-only changes.\n\n-- \n Bruce Momjian <bruce@momjian.us> http://momjian.us\n EnterpriseDB http://enterprisedb.com\n\n+ As you are, so once was I. As I am, so you will be. +\n+ Ancient Roman grave inscription +\n\n\n", "msg_date": "Mon, 30 Sep 2019 10:58:52 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Mon, Sep 30, 2019 at 2:49 PM Tomas Vondra <tomas.vondra@2ndquadrant.com>\nwrote:\n\n> On Mon, Sep 30, 2019 at 01:03:20PM +0200, Magnus Hagander wrote:\n> >On Thu, Sep 26, 2019 at 9:48 PM Alvaro Herrera <alvherre@2ndquadrant.com>\n> >wrote:\n> >\n> >> On 2019-Aug-26, Magnus Hagander wrote:\n> >>\n> >> > OK, let's try this again :)\n> >> >\n> >> > This is work mainly based in the first version of the online checksums\n> >> > patch, but based on top of Andres WIP patchset for global barriers (\n> >> >\n> >>\n> https://www.postgresql.org/message-id/20181030051643.elbxjww5jjgnjaxg%40alap3.anarazel.de\n> >> > )\n> >> >\n> >> > Andres patch has been enhanced with wait events per\n> >> >\n> >>\n> https://www.postgresql.org/message-id/CABUevEwy4LUFqePC5YzanwtzyDDpYvgrj6R5WNznwrO5ouVg1w%40mail.gmail.com\n> >> > .\n> >>\n> >> Travis says your SGML doesn't compile (maybe you just forgot to \"git\n> >> add\" and edit allfiles.sgml?):\n> >>\n> >\n> >Nope, even easier -- the reference pgVerifyChecksums was renamed to\n> >pgChecksums and for some reason we missed that in the merge.\n> >\n> >I've rebased again on top of todays master, but that was the only change I\n> >had to make.\n> >\n> >\n> >Other than bots, this patch doesn't seem to have attracted any reviewers\n> >> this time around. Perhaps you need to bribe someone? (Maybe \"how sad\n> >> your committer SSH key stopped working\" would do?)\n> >>\n> >\n> >Hmm. I don't think that's a bribe, that's a threat. However, maybe it will\n> >work.\n> >\n>\n> IMHO the patch is ready to go - I think the global barrier solves the\n> issue in the previous version, and that's the only problem I'm aware of.\n> So +1 from me to go ahead and push it.\n>\n\nNot to downvalue your review, but I'd really appreciate a review from\nsomeone who was one of the ones who spotted the issue initially.\n\nEspecially -- Andres, any chance I can bribe you to take another look?\n\n\nAnd now please uncomment my commit SSH key again, please ;-)\n>\n\nI'll consider it...\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/ <http://www.hagander.net/>\n Work: https://www.redpill-linpro.com/ <http://www.redpill-linpro.com/>\n\nOn Mon, Sep 30, 2019 at 2:49 PM Tomas Vondra <tomas.vondra@2ndquadrant.com> wrote:On Mon, Sep 30, 2019 at 01:03:20PM +0200, Magnus Hagander wrote:\n>On Thu, Sep 26, 2019 at 9:48 PM Alvaro Herrera <alvherre@2ndquadrant.com>\n>wrote:\n>\n>> On 2019-Aug-26, Magnus Hagander wrote:\n>>\n>> > OK, let's try this again :)\n>> >\n>> > This is work mainly based in the first version of the online checksums\n>> > patch, but based on top of Andres WIP patchset for global barriers (\n>> >\n>> https://www.postgresql.org/message-id/20181030051643.elbxjww5jjgnjaxg%40alap3.anarazel.de\n>> > )\n>> >\n>> > Andres patch has been enhanced with wait events per\n>> >\n>> https://www.postgresql.org/message-id/CABUevEwy4LUFqePC5YzanwtzyDDpYvgrj6R5WNznwrO5ouVg1w%40mail.gmail.com\n>> > .\n>>\n>> Travis says your SGML doesn't compile (maybe you just forgot to \"git\n>> add\" and edit allfiles.sgml?):\n>>\n>\n>Nope, even easier -- the reference pgVerifyChecksums was renamed to\n>pgChecksums and for some reason we missed that in the merge.\n>\n>I've rebased again on top of todays master, but that was the only change I\n>had to make.\n>\n>\n>Other than bots, this patch doesn't seem to have attracted any reviewers\n>> this time around.  Perhaps you need to bribe someone?  (Maybe \"how sad\n>> your committer SSH key stopped working\" would do?)\n>>\n>\n>Hmm. I don't think that's a bribe, that's a threat. However, maybe it will\n>work.\n>\n\nIMHO the patch is ready to go - I think the global barrier solves the\nissue in the previous version, and that's the only problem I'm aware of.\nSo +1 from me to go ahead and push it.Not to downvalue your review, but I'd really appreciate a review from someone who was one of the ones who spotted the issue initially.Especially -- Andres, any chance I can bribe you to take another look?\nAnd now please uncomment my commit SSH key again, please ;-)I'll consider it... --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Mon, 30 Sep 2019 16:59:00 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "Hi,\n\nOn 2019-09-30 16:59:00 +0200, Magnus Hagander wrote:\n> On Mon, Sep 30, 2019 at 2:49 PM Tomas Vondra <tomas.vondra@2ndquadrant.com>\n> wrote:\n> > IMHO the patch is ready to go - I think the global barrier solves the\n> > issue in the previous version, and that's the only problem I'm aware of.\n> > So +1 from me to go ahead and push it.\n\nI don't think the global barrier part is necessarily ready. I wrote it\non a flight back from a conference, to allow Magnus to make some\nprogress. And I don't think it has received meaningful review so far.\n\n\n> Especially -- Andres, any chance I can bribe you to take another look?\n\nI'll try to take a look.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Mon, 30 Sep 2019 09:11:25 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Mon, Sep 30, 2019 at 6:11 PM Andres Freund <andres@anarazel.de> wrote:\n\n> Hi,\n>\n> On 2019-09-30 16:59:00 +0200, Magnus Hagander wrote:\n> > On Mon, Sep 30, 2019 at 2:49 PM Tomas Vondra <\n> tomas.vondra@2ndquadrant.com>\n> > wrote:\n> > > IMHO the patch is ready to go - I think the global barrier solves the\n> > > issue in the previous version, and that's the only problem I'm aware\n> of.\n> > > So +1 from me to go ahead and push it.\n>\n> I don't think the global barrier part is necessarily ready. I wrote it\n> on a flight back from a conference, to allow Magnus to make some\n> progress. And I don't think it has received meaningful review so far.\n>\n\nI don't believe it has, no. I wouldn't trust my own level of review a\ntleast :)\n\n\n> Especially -- Andres, any chance I can bribe you to take another look?\n>\n> I'll try to take a look.\n>\n\nMuch appreciated!\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/ <http://www.hagander.net/>\n Work: https://www.redpill-linpro.com/ <http://www.redpill-linpro.com/>\n\nOn Mon, Sep 30, 2019 at 6:11 PM Andres Freund <andres@anarazel.de> wrote:Hi,\n\nOn 2019-09-30 16:59:00 +0200, Magnus Hagander wrote:\n> On Mon, Sep 30, 2019 at 2:49 PM Tomas Vondra <tomas.vondra@2ndquadrant.com>\n> wrote:\n> > IMHO the patch is ready to go - I think the global barrier solves the\n> > issue in the previous version, and that's the only problem I'm aware of.\n> > So +1 from me to go ahead and push it.\n\nI don't think the global barrier part is necessarily ready. I wrote it\non a flight back from a conference, to allow Magnus to make some\nprogress. And I don't think it has received meaningful review so far.I don't believe it has, no. I wouldn't trust my own level of review a tleast :)\n> Especially -- Andres, any chance I can bribe you to take another look?\n\nI'll try to take a look.Much appreciated! --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Wed, 2 Oct 2019 20:59:27 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Wed, Oct 02, 2019 at 08:59:27PM +0200, Magnus Hagander wrote:\n> Much appreciated!\n\nThe latest patch does not apply, could you send a rebase? Moved it to\nnext CF, waiting on author.\n--\nMichael", "msg_date": "Sun, 1 Dec 2019 11:32:16 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 1 Dec 2019, at 03:32, Michael Paquier <michael@paquier.xyz> wrote:\n\n> The latest patch does not apply, could you send a rebase? Moved it to\n> next CF, waiting on author.\n\nAttached is a rebased v14 patchset on top of maser. The Global Barriers patch\nis left as a prerequisite, but it will obviously be dropped, or be\nsignificantly changed, once the work Robert is doing with ProcSignalBarrier\nlands.\n\ncheers ./daniel", "msg_date": "Wed, 4 Dec 2019 00:40:42 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Tue, Dec 3, 2019 at 6:41 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n> Attached is a rebased v14 patchset on top of maser. The Global Barriers patch\n> is left as a prerequisite, but it will obviously be dropped, or be\n> significantly changed, once the work Robert is doing with ProcSignalBarrier\n> lands.\n\nAny chance you and/or Magnus could offer opinions on some of those\npatches? I am reluctant to start committing things with nobody having\nreplied.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 5 Dec 2019 10:13:05 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 5 Dec 2019, at 16:13, Robert Haas <robertmhaas@gmail.com> wrote:\n> \n>> On Tue, Dec 3, 2019 at 6:41 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n>> Attached is a rebased v14 patchset on top of maser. The Global Barriers patch\n>> is left as a prerequisite, but it will obviously be dropped, or be\n>> significantly changed, once the work Robert is doing with ProcSignalBarrier\n>> lands.\n> \n> Any chance you and/or Magnus could offer opinions on some of those\n> patches? I am reluctant to start committing things with nobody having\n> replied.\n\nI am currently reviewing your latest patchset, but need a bit more time.\n\ncheers ./daniel\n\n", "msg_date": "Thu, 5 Dec 2019 16:28:23 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Thu, Dec 5, 2019 at 10:28 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n> I am currently reviewing your latest patchset, but need a bit more time.\n\nOh, great, thanks.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 5 Dec 2019 10:29:24 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 5 Dec 2019, at 16:13, Robert Haas <robertmhaas@gmail.com> wrote:\n> \n> On Tue, Dec 3, 2019 at 6:41 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n>> Attached is a rebased v14 patchset on top of maser. The Global Barriers patch\n>> is left as a prerequisite, but it will obviously be dropped, or be\n>> significantly changed, once the work Robert is doing with ProcSignalBarrier\n>> lands.\n> \n> Any chance you and/or Magnus could offer opinions on some of those\n> patches? I am reluctant to start committing things with nobody having\n> replied.\n\nAttached is a v15 of the online checksums patchset (minus 0005), rebased on top\nof your v3 ProcSignalBarrier patch rather than Andres' PoC GlobalBarrier patch.\nIt does take the, perhaps, controversial approach of replacing the SAMPLE\nbarrier with the CHECKSUM barrier. The cfbot will be angry since this email\ndoesn't contain the procsignalbarrier patch, but it sounded like that would go\nin shortly so opted for that.\n\nThis version also contains touchups to the documentation part, as well as a\npgindent run.\n\nIf reviewers think this version is nearing completion, then a v16 should\naddress the comment below, but as this version switches its underlying\ninfrastructure it seemed usefel for testing still.\n\n+ /*\n+ * Force a checkpoint to get everything out to disk. XXX: this should\n+ * probably not be an IMMEDIATE checkpoint, but leave it there for now for\n+ * testing.\n+ */\n+ RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT | CHECKPOINT_IMMEDIATE);\n\ncheers ./daniel", "msg_date": "Mon, 16 Dec 2019 16:16:22 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "Hello\n\n> Attached is a v15 of the online checksums patchset (minus 0005), rebased on top\n> of your v3 ProcSignalBarrier patch rather than Andres' PoC GlobalBarrier patch.\n> It does take the, perhaps, controversial approach of replacing the SAMPLE\n> barrier with the CHECKSUM barrier. The cfbot will be angry since this email\n> doesn't contain the procsignalbarrier patch, but it sounded like that would go\n> in shortly so opted for that.\n\nProcSignalBarrier was committed, so online checksums patchset has no other pending dependencies and should be applied cleanly on master. Right? The patchset needs another rebase in this case, does not apply...\n\nregards, Sergei\n\n\n", "msg_date": "Wed, 25 Dec 2019 14:30:54 +0300", "msg_from": "Sergei Kornilov <sk@zsrv.org>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Mon, Dec 16, 2019 at 10:16 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n> If reviewers think this version is nearing completion, then a v16 should\n> address the comment below, but as this version switches its underlying\n> infrastructure it seemed usefel for testing still.\n\nI think this patch still needs a lot of work.\n\n- doPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites);\n+ doPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites ||\nDataChecksumsInProgress());\n\nThis will have a small performance cost in a pretty hot code path. Not\nsure that it's enough to worry about, though.\n\n-DataChecksumsEnabled(void)\n+DataChecksumsNeedWrite(void)\n {\n Assert(ControlFile != NULL);\n return (ControlFile->data_checksum_version > 0);\n }\n\nThis seems troubling, because data_checksum_version can now change,\nbut you're still accessing it without a lock. This complain applies\nlikewise to a bunch of related functions in xlog.c as well.\n\n+ elog(ERROR, \"Checksums not in inprogress mode\");\n\nQuestionable capitalization and punctuation.\n\n+void\n+SetDataChecksumsOff(void)\n+{\n+ LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);\n+\n+ ControlFile->data_checksum_version = 0;\n+ UpdateControlFile();\n+ LWLockRelease(ControlFileLock);\n+ WaitForProcSignalBarrier(EmitProcSignalBarrier(PROCSIGNAL_BARRIER_CHECKSUM));\n+\n+ XlogChecksums(0);\n+}\n\nThis looks racey. Suppose that checksums are on. Other backends will\nsee that checksums are disabled as soon as\nControlFile->data_checksum_version = 0 happens, and they will feel\nfree to write blocks without checksums. Now we crash, and those blocks\nexist on disk even though the on-disk state still otherwise shows\nchecksums fully enabled. It's a little better if we stop reading\ndata_checksum_version without a lock, because now nobody else can see\nthe updated state until we've actually updated the control file. But\neven then, isn't it strange that writes of non-checksummed stuff could\nappear or be written to disk before XlogChecksums(0) happens? If\nthat's safe, it seems like it deserves some kind of comment.\n\n+ /*\n+ * If we reach this point with checksums in inprogress state, we notify\n+ * the user that they need to manually restart the process to enable\n+ * checksums. This is because we cannot launch a dynamic background worker\n+ * directly from here, it has to be launched from a regular backend.\n+ */\n+ if (ControlFile->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_VERSION)\n+ ereport(WARNING,\n+ (errmsg(\"checksum state is \\\"inprogress\\\" with no worker\"),\n+ errhint(\"Either disable or enable checksums by calling the\npg_disable_data_checksums() or pg_enable_data_checksums()\nfunctions.\")));\n\nThis seems pretty half-baked.\n\n+ (errmsg(\"could not start checksumhelper: has been canceled\")));\n+ (errmsg(\"could not start checksumhelper: already running\")));\n+ (errmsg(\"failed to start checksum helper launcher\")));\n\nThese seem rough around the edges. Using an internal term like\n'checksumhelper' in a user-facing error message doesn't seem great.\nGenerally primary error messages are phrased as a single utterance\nwhere we can, rather than colon-separated fragments like this. The\nthird message calls it 'checksum helper launcher' whereas the other\ntwo call it 'checksumhelper'. It also isn't very helpful; I don't\nthink most people like a message saying that something failed with no\nexplanation given.\n\n+ elog(DEBUG1, \"Checksumhelper skipping relation %d as it no longer\nexists\", relationId);\n\nHere's another way to spell 'checksumhelper', and this time it refers\nto the worker rather than the launcher. Also, relation IDs are OIDs,\nso need to be printed with %u, and usually we try to print names if\npossible. Also, this message, like a lot of messages in this patch,\nbegins with a capital letter and does not end with a period. That is\nneither the style for primary messages nor the style for detail\nmessages. As these are primary messages, the primary message style\nshould be used. That style is no capital and no period.\n\n+ if (!RegisterDynamicBackgroundWorker(&bgw, &bgw_handle))\n+ {\n+ ereport(LOG,\n+ (errmsg(\"failed to start worker for checksumhelper in \\\"%s\\\"\",\n+ db->dbname)));\n+ return FAILED;\n+ }\n\nI don't think having constants with names like\nSUCCESSFUL/ABORTED/FAILED is a very good idea. Too much chance of name\ncollisions. I suggest adding a prefix.\n\nAlso, the retry logic here doesn't look particularly robust.\nRegisterDynamicBackgroundWorker will fail if all slots are available;\nif that happens twice for the same database, once on first attempting\nit and again when retrying it, the whole process fails, all state is\nlost, and all work has to be redone. That seems neither particularly\nunlikely nor pleasant.\n\n+ if (DatabaseList == NIL || list_length(DatabaseList) == 0)\n\nI don't think that the second half of this test serves any purpose.\n\n+ snprintf(activity, sizeof(activity), \"Waiting for current\ntransactions to finish (waiting for %d)\", waitforxid);\n\n%u here too.\n\n+ if (pgc->relpersistence == 't')\n\nUse the relevant constant.\n\n+ /*\n+ * Wait for all temp tables that existed when we started to go away. This\n+ * is necessary since we cannot \"reach\" them to enable checksums. Any temp\n+ * tables created after we started will already have checksums in them\n+ * (due to the inprogress state), so those are safe.\n+ */\n\nThis does not seem very nice. It just leaves a worker running more or\nless forever. It's essentially waiting for temp-table using sessions\nto go away, but that could take a really long time.\n\n+ WAIT_EVENT_PG_SLEEP);\n\nYou need to invent a new wait event and add docs for it.\n\n+ if (BARRIER_SHOULD_CHECK(flags, PROCSIGNAL_BARRIER_CHECKSUM))\n+ {\n+ /*\n+ * By virtue of getting here (i.e. interrupts being processed), we\n+ * know that this backend won't have any in-progress writes (which\n+ * might have missed the checksum change).\n+ */\n+ }\n\nI don't believe this. I already wrote some about this over here:\n\nhttp://postgr.es/m/CA+TgmobORrsgSUydZ3MsSw9L5MBUGz7jRK+973uPZgiyCQ81ag@mail.gmail.com\n\nAs a general point, I think that the idea of the ProcSignalBarrier\nmechanism is that every backend has some private state that needs to\nbe updated, and when it absorbs the barrier you know that it's updated\nthat state, and so when everybody's absorbed the barrier you know that\nall the state has been updated. Here, however, there actually is no\nbackend-private state. The only state that everyone's consulting is\nthe shared state stored in ControlFile->data_checksum_version. So what\ndoes absorbing the barrier prove? Only that we've reached a\nCHECK_FOR_INTERRUPTS(). But that is a useful guarantee only if we\nnever check for interrupts between the time we examine\nControlFile->data_checksum_version and the time we use it, and I see\nno particular reason to believe that should always be true, and I\nsuspect it isn't, and even if it happens to be true today I think it\ncould get broken in the future pretty easily. There are no particular\nrestrictions documented in terms of where DataChecksumsNeedWrite(),\nXLogHintBitIsNeeded(), etc. can be checked or what can be done between\nchecking the value and using it. The issue doesn't arise for today's\nDataChecksumsEnabled() because the value can't ever change, but with\nthis patch things can change, and to me what the patch does about that\ndoesn't really look adequate.\n\nI'm sort of out of time for right now, but I think this patch needs a\nlot more work on the concurrency end of things. It seems to me that it\nprobably mostly works in practice, but that the whole concurrency\nmechanism is not very solid and probably has a lot of rare cases where\nit can just misbehave if you get unlucky. I'll try to spend some more\ntime thinking about this next week. I also think that the fact that\nthe mechanism for getting from 'inprogress' to 'on' seems fragile and\nunder-engineered. It still bothers me that there's no mechanism for\npersisting the progress that we've made in enabling checksums; but\neven apart from that, I think that there just hasn't been enough\nthought given here to error/problem cases.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 3 Jan 2020 17:07:49 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 3 Jan 2020, at 23:07, Robert Haas <robertmhaas@gmail.com> wrote:\n> \n> On Mon, Dec 16, 2019 at 10:16 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n>> If reviewers think this version is nearing completion, then a v16 should\n>> address the comment below, but as this version switches its underlying\n>> infrastructure it seemed usefel for testing still.\n> \n> I think this patch still needs a lot of work.\n\nThanks a lot for your thorough review, much appreciated! Also, sorry for being\nslow to respond. Below are fixes and responses to most of the feedback, but I\nneed a bit more time to think about the concurrency aspects that you brought\nup. However, in the spirit of showing work early/often I opted for still\nsending the partial response, to perhaps be able to at least close some of the\nraised issues in the meantime.\n\n> - doPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites);\n> + doPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites ||\n> DataChecksumsInProgress());\n> \n> This will have a small performance cost in a pretty hot code path. Not\n> sure that it's enough to worry about, though.\n\nNot sure either, and/or how clever compilers are about inlining this. As a\ntest, I've switched over this to be a static inline function, as it's only\nconsumer is in xlog.c. Now, as mentioned later in this review, reading the\nversion unlocked has issues so do consider this a WIP test, not a final\nsuggestion.\n\n> -DataChecksumsEnabled(void)\n> +DataChecksumsNeedWrite(void)\n> {\n> Assert(ControlFile != NULL);\n> return (ControlFile->data_checksum_version > 0);\n> }\n> \n> This seems troubling, because data_checksum_version can now change,\n> but you're still accessing it without a lock. This complain applies\n> likewise to a bunch of related functions in xlog.c as well.\n\nRight, let me do some more thinking on this before addressing in a next version\nof the patch. Simply wrapping it in a SHARED lock still has TOCTOU problems so\na bit more work/thinking is needed.\n\n> + elog(ERROR, \"Checksums not in inprogress mode\");\n> \n> Questionable capitalization and punctuation.\n\nFixed capitalization, but elogs shouldn't end with a period so left that.\n\n> +void\n> +SetDataChecksumsOff(void)\n> +{\n> + LWLockAcquire(ControlFileLock, LW_EXCLUSIVE);\n> +\n> + ControlFile->data_checksum_version = 0;\n> + UpdateControlFile();\n> + LWLockRelease(ControlFileLock);\n> + WaitForProcSignalBarrier(EmitProcSignalBarrier(PROCSIGNAL_BARRIER_CHECKSUM));\n> +\n> + XlogChecksums(0);\n> +}\n> \n> This looks racey. Suppose that checksums are on. Other backends will\n> see that checksums are disabled as soon as\n> ControlFile->data_checksum_version = 0 happens, and they will feel\n> free to write blocks without checksums. Now we crash, and those blocks\n> exist on disk even though the on-disk state still otherwise shows\n> checksums fully enabled. It's a little better if we stop reading\n> data_checksum_version without a lock, because now nobody else can see\n> the updated state until we've actually updated the control file. But\n> even then, isn't it strange that writes of non-checksummed stuff could\n> appear or be written to disk before XlogChecksums(0) happens? If\n> that's safe, it seems like it deserves some kind of comment.\n\nAs mentioned above, I would like to address this in the next version. I'm\nworking on it, just need a little more time and wanted to share progress on the\nother bits.\n\n> + /*\n> + * If we reach this point with checksums in inprogress state, we notify\n> + * the user that they need to manually restart the process to enable\n> + * checksums. This is because we cannot launch a dynamic background worker\n> + * directly from here, it has to be launched from a regular backend.\n> + */\n> + if (ControlFile->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_VERSION)\n> + ereport(WARNING,\n> + (errmsg(\"checksum state is \\\"inprogress\\\" with no worker\"),\n> + errhint(\"Either disable or enable checksums by calling the\n> pg_disable_data_checksums() or pg_enable_data_checksums()\n> functions.\")));\n> \n> This seems pretty half-baked.\n\nI don't disagree with that. However, given that enabling checksums is a pretty\nintensive operation it seems somewhat unfriendly to automatically restart. As\na DBA I wouldn't want that to kick off without manual intervention, but there\nis also the risk of this being missed due to assumptions that it would restart.\nAny ideas on how to treat this?\n\nIf/when we can restart the processing where it left off, without the need to go\nover all data again, things might be different wrt the default action.\n\n> + (errmsg(\"could not start checksumhelper: has been canceled\")));\n> + (errmsg(\"could not start checksumhelper: already running\")));\n> + (errmsg(\"failed to start checksum helper launcher\")));\n> \n> These seem rough around the edges. Using an internal term like\n> 'checksumhelper' in a user-facing error message doesn't seem great.\n> Generally primary error messages are phrased as a single utterance\n> where we can, rather than colon-separated fragments like this. The\n> third message calls it 'checksum helper launcher' whereas the other\n> two call it 'checksumhelper'. It also isn't very helpful; I don't\n> think most people like a message saying that something failed with no\n> explanation given.\n> \n> + elog(DEBUG1, \"Checksumhelper skipping relation %d as it no longer\n> exists\", relationId);\n> \n> Here's another way to spell 'checksumhelper', and this time it refers\n> to the worker rather than the launcher. Also, relation IDs are OIDs,\n> so need to be printed with %u, and usually we try to print names if\n> possible. Also, this message, like a lot of messages in this patch,\n> begins with a capital letter and does not end with a period. That is\n> neither the style for primary messages nor the style for detail\n> messages. As these are primary messages, the primary message style\n> should be used. That style is no capital and no period.\n\nI've removed checksumhelper from all user facing strings, and only kept them in\nthe DEBUG strings (which to some extent probably will be removed before a final\nversion of the patch, so didn't spend too much time on those just now). The\nbgworker name is still checksumhelper launcher and checksumhelper worker, but\nthat could perhaps do with a better name too.\n\n> + if (!RegisterDynamicBackgroundWorker(&bgw, &bgw_handle))\n> + {\n> + ereport(LOG,\n> + (errmsg(\"failed to start worker for checksumhelper in \\\"%s\\\"\",\n> + db->dbname)));\n> + return FAILED;\n> + }\n> \n> I don't think having constants with names like\n> SUCCESSFUL/ABORTED/FAILED is a very good idea. Too much chance of name\n> collisions. I suggest adding a prefix.\n\nFixed.\n\n> Also, the retry logic here doesn't look particularly robust.\n> RegisterDynamicBackgroundWorker will fail if all slots are available;\n> if that happens twice for the same database, once on first attempting\n> it and again when retrying it, the whole process fails, all state is\n> lost, and all work has to be redone. That seems neither particularly\n> unlikely nor pleasant.\n\nAgreed, this was a brick or two shy of a load. I've rewritten this logic to\ncope better with the conditions around startup/shutdown of bgworkers. I think\nthere should be some form of backoff mechanism as well in case there\ntemporarily aren't any slots, to avoid running through all the databases in\nshort order only to run up the retry counter. Something like if X databases in\nsuccession fail on no slot being available, back off a little before trying X+1\nto allow for operations that consume the slot(s) to finish. Or something. It\nwont help for systems which are permanently starved with a too low\nmax_worker_processes, but nothing sort of will. For the latter, I've added a\nnote to the documentation.\n\n> + if (DatabaseList == NIL || list_length(DatabaseList) == 0)\n> \n> I don't think that the second half of this test serves any purpose.\n\nTrue, but I think the code is clearer if the second half is the one we keep, so\nwent with that.\n\n> + snprintf(activity, sizeof(activity), \"Waiting for current\n> transactions to finish (waiting for %d)\", waitforxid);\n> \n> %u here too.\n\nFixed.\n\n> + if (pgc->relpersistence == 't')\n> \n> Use the relevant constant.\n\nFixed.\n\n> + /*\n> + * Wait for all temp tables that existed when we started to go away. This\n> + * is necessary since we cannot \"reach\" them to enable checksums. Any temp\n> + * tables created after we started will already have checksums in them\n> + * (due to the inprogress state), so those are safe.\n> + */\n> \n> This does not seem very nice. It just leaves a worker running more or\n> less forever. It's essentially waiting for temp-table using sessions\n> to go away, but that could take a really long time.\n\nIt can, but is there a realistic alternative? I can't think of one but if you\nhave ideas I'd love for this requirement to go away, or be made less blocking.\n\nAt the same time, enabling checksums is hardly the kind of operation one does\ncasually in a busy database, but probably a more planned operation. This\nrequirement is mentioned in the documentation such that a DBA can plan for when\nto start the processing.\n\n> + WAIT_EVENT_PG_SLEEP);\n> \n> You need to invent a new wait event and add docs for it.\n\nDone. I failed to figure out a (IMO) good name though, and welcome suggestions\nthat are more descriptive. CHECKSUM_ENABLE_STARTCONDITION was what I settled on\nbut I'm not too excited about it.\n\n> + if (BARRIER_SHOULD_CHECK(flags, PROCSIGNAL_BARRIER_CHECKSUM))\n> + {\n> + /*\n> + * By virtue of getting here (i.e. interrupts being processed), we\n> + * know that this backend won't have any in-progress writes (which\n> + * might have missed the checksum change).\n> + */\n> + }\n> \n> I don't believe this. I already wrote some about this over here:\n> \n> http://postgr.es/m/CA+TgmobORrsgSUydZ3MsSw9L5MBUGz7jRK+973uPZgiyCQ81ag@mail.gmail.com\n> \n> As a general point, I think that the idea of the ProcSignalBarrier\n> mechanism is that every backend has some private state that needs to\n> be updated, and when it absorbs the barrier you know that it's updated\n> that state, and so when everybody's absorbed the barrier you know that\n> all the state has been updated. Here, however, there actually is no\n> backend-private state. The only state that everyone's consulting is\n> the shared state stored in ControlFile->data_checksum_version. So what\n> does absorbing the barrier prove? Only that we've reached a\n> CHECK_FOR_INTERRUPTS(). But that is a useful guarantee only if we\n> never check for interrupts between the time we examine\n> ControlFile->data_checksum_version and the time we use it, and I see\n> no particular reason to believe that should always be true, and I\n> suspect it isn't, and even if it happens to be true today I think it\n> could get broken in the future pretty easily. There are no particular\n> restrictions documented in terms of where DataChecksumsNeedWrite(),\n> XLogHintBitIsNeeded(), etc. can be checked or what can be done between\n> checking the value and using it. The issue doesn't arise for today's\n> DataChecksumsEnabled() because the value can't ever change, but with\n> this patch things can change, and to me what the patch does about that\n> doesn't really look adequate.\n\nI don't disagree with this, but I need to do a bit more thinking before\npresenting a suggested fix for this concurrency issue.\n\n> I'm sort of out of time for right now, but I think this patch needs a\n> lot more work on the concurrency end of things. It seems to me that it\n> probably mostly works in practice, but that the whole concurrency\n> mechanism is not very solid and probably has a lot of rare cases where\n> it can just misbehave if you get unlucky. I'll try to spend some more\n> time thinking about this next week. I also think that the fact that\n> the mechanism for getting from 'inprogress' to 'on' seems fragile and\n> under-engineered. It still bothers me that there's no mechanism for\n> persisting the progress that we've made in enabling checksums; but\n> even apart from that, I think that there just hasn't been enough\n> thought given here to error/problem cases.\n\nThanks again for reviewing (and working on the infrastructure required for this\npatch to begin with)! Regarding the persisting the progress; that would be a\nreally neat feature but I don't have any suggestion on how to do that safely\nfor real use-cases.\n\nAttached is a v16 rebased on top of current master which addresses the above\ncommented points, and which I am basing the concurrency work on.\n\ncheers ./daniel", "msg_date": "Sun, 19 Jan 2020 00:18:18 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Sat, Jan 18, 2020 at 6:18 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n> Thanks again for reviewing (and working on the infrastructure required for this\n> patch to begin with)! Regarding the persisting the progress; that would be a\n> really neat feature but I don't have any suggestion on how to do that safely\n> for real use-cases.\n\nLeaving to one side the question of how much work is involved, could\nwe do something conceptually similar to relfrozenxid/datfrozenxid,\ni.e. use catalog state to keep track of which objects have been\nhandled and which not?\n\nVery rough sketch:\n\n* set a flag indicating that checksums must be computed for all page writes\n* use barriers and other magic to make sure everyone has gotten the\nmemo from the previous step\n* use new catalog fields pg_class.relhaschecksums and\npg_database.dathaschecksums to track whether checksums are enabled\n* keep launching workers for databases where !pg_class.dathaschecksums\nuntil none remain\n* mark checksums as fully enabled\n* party\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Mon, 20 Jan 2020 15:14:47 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": " On Mon, Jan 20, 2020 at 12:14 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Sat, Jan 18, 2020 at 6:18 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n> > Thanks again for reviewing (and working on the infrastructure required for this\n> > patch to begin with)! Regarding the persisting the progress; that would be a\n> > really neat feature but I don't have any suggestion on how to do that safely\n> > for real use-cases.\n>\n> Leaving to one side the question of how much work is involved, could\n> we do something conceptually similar to relfrozenxid/datfrozenxid,\n> i.e. use catalog state to keep track of which objects have been\n> handled and which not?\n>\n> Very rough sketch:\n>\n> * set a flag indicating that checksums must be computed for all page writes\n> * use barriers and other magic to make sure everyone has gotten the\n> memo from the previous step\n> * use new catalog fields pg_class.relhaschecksums and\n> pg_database.dathaschecksums to track whether checksums are enabled\n> * keep launching workers for databases where !pg_class.dathaschecksums\n> until none remain\n> * mark checksums as fully enabled\n> * party\n\nWe did discuss this back when we started work on this (I can't\nremember if it was just me and Daniel and someone else or on a list --\nbut that's not important atm).\n\nThe reasoning that led us to *not* doing that is that it's a one-off\noperation. That along with the fact that we hope to at some point be\nable to change the default to chekcsums on (and t wouldn't be\nnecessary for the transition on->off as that is very fast), it would\nbecome an increasingly rate on-off operation. And by adding these\nflags to the catalogs, everybody is paying the overhead for this\none-off rare operation. Another option would be to add the flag on the\npg_database level which would decrease the overhead, but our guess was\nthat this would also decrease the usefulness in most cases to make it\nnot worth it (most people with big databases don't have many big\ndatabases in the same cluster -- it's usually just one or two, so in\nthe end the results would be more or less the same was we have now as\nit would have to keep re-doing the big ones)\n\nUnless we actually want to support running systems more or less\npermanently with some tables with checksums and other tables without\nchecksums. But that's going to have an effect on the validation of\nchecksums that would generate a huge overhead (since each buffer check\nwould have to look up the pg_class entry).\n\nFYI, Daniel is working on an update that will include this -- so we\ncan see what the actual outcome is of it in th case of complexity as\nwell. Should hopefully be ready soon.\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/\n Work: https://www.redpill-linpro.com/\n\n\n", "msg_date": "Wed, 22 Jan 2020 11:50:47 -0800", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Wed, Jan 22, 2020 at 2:50 PM Magnus Hagander <magnus@hagander.net> wrote:\n> The reasoning that led us to *not* doing that is that it's a one-off\n> operation. That along with the fact that we hope to at some point be\n> able to change the default to chekcsums on (and t wouldn't be\n> necessary for the transition on->off as that is very fast), it would\n> become an increasingly rate on-off operation. And by adding these\n> flags to the catalogs, everybody is paying the overhead for this\n> one-off rare operation. Another option would be to add the flag on the\n> pg_database level which would decrease the overhead, but our guess was\n> that this would also decrease the usefulness in most cases to make it\n> not worth it (most people with big databases don't have many big\n> databases in the same cluster -- it's usually just one or two, so in\n> the end the results would be more or less the same was we have now as\n> it would have to keep re-doing the big ones)\n\nI understand, but the point for me is that the patch does not seem\nrobust as written. Nobody's going to be happy if there are reasonably\nhigh-probability scenarios where it turns checksums part way on and\nthen just stops. Now, that can probably be improved to some degree\nwithout adding catalog flags, but I bet it can be improved more and\nfor less effort if we do add catalog flags. Maybe being able to\nsurvive a cluster restart without losing track of progress is not a\nhard requirement for this feature, but it certainly seems nice. And I\nwould venture to say that continuing to run without giving up if there\nhappen to be no background workers available for a while IS a hard\nrequirement, because that can easily happen due to normal use of\nparallel query. We do not normally commit features if, without any\nerror occurring, they might just give up part way through the\noperation.\n\nI think the argument about adding catalog flags adding overhead is\npretty much bogus. Fixed-width fields in catalogs are pretty cheap.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Wed, 22 Jan 2020 15:20:21 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Wed, Jan 22, 2020 at 12:20 PM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Wed, Jan 22, 2020 at 2:50 PM Magnus Hagander <magnus@hagander.net> wrote:\n> > The reasoning that led us to *not* doing that is that it's a one-off\n> > operation. That along with the fact that we hope to at some point be\n> > able to change the default to chekcsums on (and t wouldn't be\n> > necessary for the transition on->off as that is very fast), it would\n> > become an increasingly rate on-off operation. And by adding these\n> > flags to the catalogs, everybody is paying the overhead for this\n> > one-off rare operation. Another option would be to add the flag on the\n> > pg_database level which would decrease the overhead, but our guess was\n> > that this would also decrease the usefulness in most cases to make it\n> > not worth it (most people with big databases don't have many big\n> > databases in the same cluster -- it's usually just one or two, so in\n> > the end the results would be more or less the same was we have now as\n> > it would have to keep re-doing the big ones)\n>\n> I understand, but the point for me is that the patch does not seem\n> robust as written. Nobody's going to be happy if there are reasonably\n> high-probability scenarios where it turns checksums part way on and\n> then just stops. Now, that can probably be improved to some degree\n> without adding catalog flags, but I bet it can be improved more and\n> for less effort if we do add catalog flags. Maybe being able to\n> survive a cluster restart without losing track of progress is not a\n> hard requirement for this feature, but it certainly seems nice. And I\n\nIt's certainly nice, but that is of course a cost/benefit tradeoff\ncalculation. Our thoughts on that was that the cost was higher than\nthe benefit -- which may of course be wrong, and in that case it's\nbetter to have it changed.\n\n\n> would venture to say that continuing to run without giving up if there\n> happen to be no background workers available for a while IS a hard\n> requirement, because that can easily happen due to normal use of\n> parallel query. We do not normally commit features if, without any\n> error occurring, they might just give up part way through the\n> operation.\n\nThat part I agree with, but I don't think that in itself requires\nper-relation level tracking.\n\n\n> I think the argument about adding catalog flags adding overhead is\n> pretty much bogus. Fixed-width fields in catalogs are pretty cheap.\n\nIf that's the general view, then yeah our \"cost calculations\" were\noff. I guess I may have been colored by the cost of adding statistics\ncounters, and had that influence the thinking. Incorrect judgement on\nthat cost certainly contributed to the decision. back then.\n\nBut as noted, work is being done on adding it, so let's see what that\nends up looking like in reality.\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/\n Work: https://www.redpill-linpro.com/\n\n\n", "msg_date": "Wed, 22 Jan 2020 12:28:21 -0800", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Wed, Jan 22, 2020 at 3:28 PM Magnus Hagander <magnus@hagander.net> wrote:\n> > I think the argument about adding catalog flags adding overhead is\n> > pretty much bogus. Fixed-width fields in catalogs are pretty cheap.\n>\n> If that's the general view, then yeah our \"cost calculations\" were\n> off. I guess I may have been colored by the cost of adding statistics\n> counters, and had that influence the thinking. Incorrect judgement on\n> that cost certainly contributed to the decision. back then.\n\nFor either statistics or for pg_class, the amount of data that we have\nto manage is proportional to the number of relations (which could be\nbig) multiplied by the data stored for each relation. But the\ndifference is that the stats file has to be rewritten, at least on a\nper-database basis, very frequently, while pg_class goes through\nshared-buffers and so doesn't provoke the same stupid\nwrite-the-whole-darn-thing behavior. That is a pretty key difference,\nIMHO.\n\nNow, it would be nice to fix the stats system, but until we do, here we are.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Wed, 22 Jan 2020 17:07:58 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 22 Jan 2020, at 23:07, Robert Haas <robertmhaas@gmail.com> wrote:\n> \n> On Wed, Jan 22, 2020 at 3:28 PM Magnus Hagander <magnus@hagander.net> wrote:\n>>> I think the argument about adding catalog flags adding overhead is\n>>> pretty much bogus. Fixed-width fields in catalogs are pretty cheap.\n>> \n>> If that's the general view, then yeah our \"cost calculations\" were\n>> off. I guess I may have been colored by the cost of adding statistics\n>> counters, and had that influence the thinking. Incorrect judgement on\n>> that cost certainly contributed to the decision. back then.\n> \n> For either statistics or for pg_class, the amount of data that we have\n> to manage is proportional to the number of relations (which could be\n> big) multiplied by the data stored for each relation. But the\n> difference is that the stats file has to be rewritten, at least on a\n> per-database basis, very frequently, while pg_class goes through\n> shared-buffers and so doesn't provoke the same stupid\n> write-the-whole-darn-thing behavior. That is a pretty key difference,\n> IMHO.\n\nI think the cost is less about performance and more about carrying around an\nattribute which wont be terribly interesting during the cluster lifetime,\nexcept for the transition. But, it's as you say probably a manageable expense.\n\nA bigger question is how to handle the offline capabilities. pg_checksums can\nenable or disable checksums in an offline cluster, which will put the cluster\nin a state where the pg_control file and the catalog don't match at startup.\nOne strategy could be to always trust the pg_control file and alter the catalog\naccordingly, but that still leaves a window of inconsistent cluster state.\n\ncheers ./daniel\n\n", "msg_date": "Thu, 23 Jan 2020 12:18:41 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Thu, Jan 23, 2020 at 6:19 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n> A bigger question is how to handle the offline capabilities. pg_checksums can\n> enable or disable checksums in an offline cluster, which will put the cluster\n> in a state where the pg_control file and the catalog don't match at startup.\n> One strategy could be to always trust the pg_control file and alter the catalog\n> accordingly, but that still leaves a window of inconsistent cluster state.\n\nI suggest that we define things so that the catalog state is only\nmeaningful during a state transition. That is, suppose the cluster\nstate is either \"on\", \"enabling\", or \"off\". When it's \"on\", checksums\nare written and verified. When it is \"off\", checksums are not written\nand not verified. When it's \"enabling\", checksums are written but not\nverified. Also, when and only when the state is \"enabling\", the\nbackground workers that try to rewrite relations to add checksums run,\nand those workers look at the catalog state to figure out what to do.\nOnce the state changes to \"on\", those workers don't run any more, and\nso the catalog state does not make any difference.\n\nA tricky problem is to handling the case where the state is switched\nfrom \"enabling\" to \"on\" and then back to \"off\" and then to \"enabling\"\nagain. You don't want to confuse the state from the previous round of\nenabling with the state for the current round of enabling. Suppose in\naddition to storing the cluster-wide state of on/off/enabling, we also\nstore an \"enable counter\" which is incremented every time the state\ngoes from \"off\" to \"enabling\". Then, for each database and relation,\nwe store a counter that indicates the value of the enable counter at\nthe time we last scanned/rewrote that relation to set checksums. Now,\nyou're covered. And, to save space, it can probably be a 32-bit\ncounter, since 4 billion disable/reenable cycles ought to be enough\nfor anybody.\n\nIt would not be strictly necessary to store this in pg_class. Another\nthing that could be done is to store it in a separate system table\nthat could even be truncated when enabling is not in progress - though\nit would be unwise to assume that it's always truncated at the\nbeginning of an enabling cycle, since it would be hard to guarantee\nthat the previous enabling cycle didn't fail when trying to truncate.\nSo you'd probably still end up with something like the counter\napproach. I am inclined to think that inventing a whole new catalog\nfor this is over-engineering, but someone might think differently.\nNote that creating a table while enabling is in progress needs to set\nthe enabling counter for the new table to the new value of the\nenabling counter, not the old one, because the new table starts empty\nand won't end up with any pages that don't have valid checksums.\nSimilarly, TRUNCATE, CLUSTER, VACUUM FULL, and rewriting variants of\nALTER TABLE can set the new value for the enabling counter as a side\neffect. That's probably easier and more efficient if it's just value\nin pg_class than if they have to go poking around in another catalog.\nSo I am tentatively inclined to think that just putting it in pg_class\nmakes more sense.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 23 Jan 2020 12:23:09 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "Hi,\n\nOn 2020-01-23 12:23:09 -0500, Robert Haas wrote:\n> On Thu, Jan 23, 2020 at 6:19 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n> > A bigger question is how to handle the offline capabilities. pg_checksums can\n> > enable or disable checksums in an offline cluster, which will put the cluster\n> > in a state where the pg_control file and the catalog don't match at startup.\n> > One strategy could be to always trust the pg_control file and alter the catalog\n> > accordingly, but that still leaves a window of inconsistent cluster state.\n> \n> I suggest that we define things so that the catalog state is only\n> meaningful during a state transition. That is, suppose the cluster\n> state is either \"on\", \"enabling\", or \"off\". When it's \"on\", checksums\n> are written and verified. When it is \"off\", checksums are not written\n> and not verified. When it's \"enabling\", checksums are written but not\n> verified. Also, when and only when the state is \"enabling\", the\n> background workers that try to rewrite relations to add checksums run,\n> and those workers look at the catalog state to figure out what to do.\n> Once the state changes to \"on\", those workers don't run any more, and\n> so the catalog state does not make any difference.\n> \n> A tricky problem is to handling the case where the state is switched\n> from \"enabling\" to \"on\" and then back to \"off\" and then to \"enabling\"\n> again. You don't want to confuse the state from the previous round of\n> enabling with the state for the current round of enabling. Suppose in\n> addition to storing the cluster-wide state of on/off/enabling, we also\n> store an \"enable counter\" which is incremented every time the state\n> goes from \"off\" to \"enabling\". Then, for each database and relation,\n> we store a counter that indicates the value of the enable counter at\n> the time we last scanned/rewrote that relation to set checksums. Now,\n> you're covered. And, to save space, it can probably be a 32-bit\n> counter, since 4 billion disable/reenable cycles ought to be enough\n> for anybody.\n> \n> It would not be strictly necessary to store this in pg_class. Another\n> thing that could be done is to store it in a separate system table\n> that could even be truncated when enabling is not in progress - though\n> it would be unwise to assume that it's always truncated at the\n> beginning of an enabling cycle, since it would be hard to guarantee\n> that the previous enabling cycle didn't fail when trying to truncate.\n> So you'd probably still end up with something like the counter\n> approach. I am inclined to think that inventing a whole new catalog\n> for this is over-engineering, but someone might think differently.\n> Note that creating a table while enabling is in progress needs to set\n> the enabling counter for the new table to the new value of the\n> enabling counter, not the old one, because the new table starts empty\n> and won't end up with any pages that don't have valid checksums.\n> Similarly, TRUNCATE, CLUSTER, VACUUM FULL, and rewriting variants of\n> ALTER TABLE can set the new value for the enabling counter as a side\n> effect. That's probably easier and more efficient if it's just value\n> in pg_class than if they have to go poking around in another catalog.\n> So I am tentatively inclined to think that just putting it in pg_class\n> makes more sense.\n\nI'm somewhat inclined to think that it's worth first making this robust\nwithout catalog state - even though I find restartability\nimportant. Especially due to not having convenient ways to have cross\ndatabase state that we can reset without again needing background\nworkers. I also wonder if it's not worthwhile to design the feature in a\nway that, *in the future*, checksums could be separately set on the\nstandby/primary - without needing to ship the whole database through\nWAL.\n\nOh, if all relation types had a metapage with a common header, this\nwould be so much easier...\n\nIt'd also be a lot easier if we could map from relfilenode back to a\nrelation oid, without needing catalog access. That'd allow us to acquire\nlocks on the relation for a filenode, without needing to be connected to\na database. Again, with a metapage, that'd be quite doable.\n\n\nProbably not worth doing just for this, but I'm wondering about solving\nthe metapage issue by just adding a metadata relation fork. Sucks to\nincrease the number of files further, but I don't really see a path\ntowards having a metapage for everything, given pg_upgrade compat\nrequirements. Such a metadata fork, in contrast, could easily be filled\nby pg_upgrade. That metadata file could perhaps replace init forks too.\n\nFor debuggability storing some information about the relation in that\nmetadata fork would be great. Being able to identify the type of\nrelation etc from there, and perhaps even the relname at creation, would\ncertainly be helpful for cases the database doesn't start up anymore.\n\nWith a bit of care, we could allow AMs to store additional information\nin there, by having a offset pointer for am information in the common\nheader.\n\nE.g. for tables it'd be feasible to have the types of columns in there\n(since it's associated with a relfilenode, rather than relation, there's\nno problem with rewrites), allowing to correctly interpret data without\ncatalog access when shit has hit the fan.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sun, 26 Jan 2020 13:03:03 -0800", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On 1/18/20 6:18 PM, Daniel Gustafsson wrote:\n> \n> Attached is a v16 rebased on top of current master which addresses the above\n> commented points, and which I am basing the concurrency work on.\n\nThis patch no longer applies cleanly: \nhttp://cfbot.cputube.org/patch_27_2260.log\n\nThe CF entry has been updated to Waiting on Author.\n\nRegards,\n\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Wed, 1 Apr 2020 11:30:57 -0400", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On 4/1/20 11:30 AM, David Steele wrote:\n> On 1/18/20 6:18 PM, Daniel Gustafsson wrote:\n>>\n>> Attached is a v16 rebased on top of current master which addresses the \n>> above\n>> commented points, and which I am basing the concurrency work on.\n> \n> This patch no longer applies cleanly: \n> http://cfbot.cputube.org/patch_27_2260.log\n> \n> The CF entry has been updated to Waiting on Author.\n> \n> Regards,\n\nThere has been review on this patch but no updates in some time. As far \nas I can see there's debate on how to mark relations as fully \nchecksummed and/or how to resume.\n\nI'm marking this patch Returned with Feedback. Please feel free to \nresubmit when it is again ready for review.\n\nRegards,\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Wed, 8 Apr 2020 10:24:19 -0400", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 23 Jan 2020, at 18:23, Robert Haas <robertmhaas@gmail.com> wrote:\n\n> ..That's probably easier and more efficient if it's just value\n> in pg_class than if they have to go poking around in another catalog.\n> So I am tentatively inclined to think that just putting it in pg_class\n> makes more sense.\n\n..which is what I did, but more on that later.\n\nAttached is a new version of the online checksums patch which, I hope, address\nmost of the concerns raised in previous reviews. There has been a fair amount\nof fiddling done, so below is a summary of what has been done.\n\nError handling and synchronization around pg_control have been overhauled as\nwell as the absorption of the process barriers. The comment there suggested\nthat the absorbing function shouldn't reside with the procsignal code, input is\ngladly received on where it makes the most sense since I can see merit to quite\na few places.\n\nThe checksumhelper is renamed datachecksumsworker, since checksumhelper is now\nused since c12e43a2e0d45a6b59f2. I think there is room for better casing here\nand there on this.\n\nRestartability is implemented by keeping state in pg_class. I opted for a bool\nwhich is cleared as the first step of checksum enable, since it offers fewer\nsynchronization cornercases I think. The field is only useful during\nprocessing, and is not guaranteed to reflect reality outside of processing.\nThe current name I came up with does not convey that, better suggestions are\nmore than welcome. For now, the process must be restarted manually by running\npg_enable_data_checksums() again, which I sort of like but that might just be\nStockholm syndrome from having enabled/disabled checksums locally a gazillion\ntimes.\n\nTesting has been extended to cover basics but also restartability. Testing a\nresumed restart is a tad tricky while still avoiding timing related tests, so\nI've (possibly ab-)used an interactive psql session to act as a blocker to keep\nprocessing from finishing. I did extend poll_query_until to take a non-default\ntimeout to make sure these tests finish in a reasonable time during hacking,\nbut thats left out of this version.\n\nThere are a few TODO markers left where I'd appreciate input from reviewers,\nfor example what to do for disabling already disabled checksums (is it a LOG,\nNOTICE, ERROR or silent return?)\n\nThis is an executive summary of hacking done, and I have most likely forgotten\nto mention something important, but I hope it covers most things. Few, if any,\nchanges are made to the interface of this, changes are contained under the\nhood. I will stick this patch in the upcoming commitfest.\n\ncheers ./daniel", "msg_date": "Mon, 22 Jun 2020 14:27:47 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Mon, Jun 22, 2020 at 8:27 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n> Restartability is implemented by keeping state in pg_class. I opted for a bool\n> which is cleared as the first step of checksum enable, since it offers fewer\n> synchronization cornercases I think.\n\nUnless you take AccessExclusiveLock on the table, this probably needs\nto be three-valued. Or maybe I am misunderstanding the design...\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Mon, 22 Jun 2020 12:29:51 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 22 Jun 2020, at 18:29, Robert Haas <robertmhaas@gmail.com> wrote:\n> \n> On Mon, Jun 22, 2020 at 8:27 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n>> Restartability is implemented by keeping state in pg_class. I opted for a bool\n>> which is cleared as the first step of checksum enable, since it offers fewer\n>> synchronization cornercases I think.\n> \n> Unless you take AccessExclusiveLock on the table, this probably needs\n> to be three-valued. Or maybe I am misunderstanding the design...\n\nSorry being a bit thick, can you elaborate which case you're thinking about?\nCREATE TABLE sets the attribute according to the value of data_checksums, and\nbefore enabling checksums (and before changing data_checksums to inprogress)\nthe bgworker will update all relhaschecksums from true (if any) to false. Once\nthe state is set to inprogress all new relations will set relhaschecksums to\ntrue.\n\nThe attached v19 fixes a few doc issues I had missed.\n\ncheers ./daniel", "msg_date": "Thu, 25 Jun 2020 11:43:00 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Thu, Jun 25, 2020 at 5:43 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n> Sorry being a bit thick, can you elaborate which case you're thinking about?\n> CREATE TABLE sets the attribute according to the value of data_checksums, and\n> before enabling checksums (and before changing data_checksums to inprogress)\n> the bgworker will update all relhaschecksums from true (if any) to false. Once\n> the state is set to inprogress all new relations will set relhaschecksums to\n> true.\n\nOh, I think I was the one who was confused. I guess relhaschecksums\nonly really has meaning when we're in the process of enabling\nchecksums? So if we're in that state, then the Boolean tells us\nwhether a particular relation is done, and otherwise it doesn't\nmatter?\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 26 Jun 2020 08:12:30 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 26 Jun 2020, at 14:12, Robert Haas <robertmhaas@gmail.com> wrote:\n> \n> On Thu, Jun 25, 2020 at 5:43 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n>> Sorry being a bit thick, can you elaborate which case you're thinking about?\n>> CREATE TABLE sets the attribute according to the value of data_checksums, and\n>> before enabling checksums (and before changing data_checksums to inprogress)\n>> the bgworker will update all relhaschecksums from true (if any) to false. Once\n>> the state is set to inprogress all new relations will set relhaschecksums to\n>> true.\n> \n> Oh, I think I was the one who was confused. I guess relhaschecksums\n> only really has meaning when we're in the process of enabling\n> checksums? So if we're in that state, then the Boolean tells us\n> whether a particular relation is done, and otherwise it doesn't\n> matter?\n\nThat is correct (which is why the name is terrible since it doesn't convey\nthat at all).\n\ncheers ./daniel\n\n", "msg_date": "Fri, 26 Jun 2020 14:34:11 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Thu, Jun 25, 2020 at 11:43:00AM +0200, Daniel Gustafsson wrote:\n> The attached v19 fixes a few doc issues I had missed.\n\n+ They can also be enabled or disabled at a later timne, either as an offline\n=> time\n\n+\t * awaiting shutdown, but we can continue turning off checksums anyway\n=> a waiting\n\n+\t * We are starting a checksumming process scratch, and need to start by\n=> FROM scratch\n\n+\t * to inprogress new relations will set relhaschecksums in pg_class so it\n=> inprogress COMMA\n\n+\t\t * Relation no longer exist. We don't consider this an error since\n=> exists\n\n+\t * so when the cluster comes back up processing will habe to be resumed.\n=> have\n\n+\t\t\t \"completed one pass over all databases for checksum enabling, %i databases processed\",\n=> I think this will be confusing to be hardcoded \"one\". It'll say \"one\" over\nand over.\n\n+\t\t * still exist.\n=> exists\n\nIn many places, you refer to \"datachecksumsworker\" (sums) but in nine places\nyou refer to datachecksumworker (sum).\n\n+ProcessSingleRelationFork(Relation reln, ForkNumber forkNum, BufferAccessStrategy strategy)\n+{\n+\tBlockNumber numblocks = RelationGetNumberOfBlocksInFork(reln, forkNum);\n\n=> I think looping over numblocks is safe since new blocks are intended to be\nwritten with checksum, right? Maybe it's good to say that here.\n\n+\tBlockNumber b;\n\nblknum will be easier to grep for\n\n+\t\t\t(errmsg(\"background worker \\\"datachecksumsworker\\\" starting for database oid %d\",\n=> Should be %u or similar (several of these)\n\nSome questions:\n\nIt looks like you rewrite every page, even if it already has correct checksum,\nto handle replicas. I wonder if it's possible/reasonable/good to skip pages\nwith correct checksum when wal_level=minimal ?\n\nIt looks like it's not possible to change the checksum delay while a checksum\nworker is already running. That may be important to allow: 1) decreased delay\nduring slow periods; 2) increased delay if the process is significantly done,\nbut needs to be throttled to avoid disrupting production environment.\n\nHave you collaborated with Julien about this one? His patch adds new GUCs:\nhttps://www.postgresql.org/message-id/20200714090808.GA20780@nol\nchecksum_cost_delay\nchecksum_cost_page\nchecksum_cost_limit\n\nMaybe you'd say that Julien's pg_check_relation() should accept parameters\ninstead of adding GUCs. I think you should be in agreement on that. It'd be\nsilly if the verification function added three GUCs and allowed adjusting\nthrottle midcourse, but the checksum writer process didn't use them.\n\nIf you used something like that, I guess you'd also want to distinguish\nchecksum_cost_page_read vs write. Possibly, the GUCs part should be a\npreliminary shared patch 0001 that you both used.\n\n-- \nJustin\n\n\n", "msg_date": "Mon, 27 Jul 2020 21:33:46 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Mon, Jun 22, 2020 at 8:27 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n> Attached is a new version of the online checksums patch which, I hope, address\n> most of the concerns raised in previous reviews. There has been a fair amount\n> of fiddling done, so below is a summary of what has been done.\n\nHere are a bunch of comments based on a partial read-through of this\npatch. The most serious concerns, around synchronization, are down\ntoward at the bottom. Sorry this is a bit eclectic as a review, but I\nwrote things down as I read through the patch more or less in the\norder I ran across them.\n\nRegarding disable_data_checksums(), I disagree with ereport(LOG, ...)\nhere. If you want to indicate to the caller whether or not a state\nchange occurred, you could consider returning a Boolean instead of\nvoid. If you want to do it with log messages, I vote for NOTICE, not\nLOG. Maybe NOTICE is better, because enable_data_checksums() seems to\nwant to convey more information that you can represent in a Boolean,\nbut then it should use NOTICE consistently, not a mix of NOTICE and\nLOG.\n\nFormatting needs work for project style: typically no braces around\nsingle statements, \"ereport(WHATEVER,\" should always have a line break\nat that point.\n\n+ * cluster, which was not initialized with checksums, this worker will ensure\n\n\"which was not initialized with checksums\" => \"that does not running\nwith checksums enabled\"?\n\n+ * turned on. In the case of disabling checksums, the state transition is\n+ * recorded in the catalog and controlfile, no changes are performed\n+ * on the data pages or in the catalog.\n\nComma splice. Either write \"controlfile; no\" or \"controlfile, and no\".\n\nMy spell-checker complains that controfile, clusterwide, inprogress,\nand endstate are not words. I think you should think about inserting\nspaces or, in the case of cluster-wide, a dash, unless they are being\nused as literals, in which case perhaps those instances should be\nquoted. \"havent\" needs an apostrophe.\n\n+ * DataChecksumsWorker will compile a list of databases which exists at the\n\nwhich exist\n\n+ * For each database, all relations which have storage are read and every data\n+ * page is marked dirty to force a write with the checksum, this will generate\n\nComma splice. Split into two sentences.\n\n+ * In case checksums have been enabled and later disabled, when re-enabling\n+ * pg_class.relhaschecksums will be reset to false before entering inprogress\n+ * mode to ensure that all relations are re-processed.\n\n\"If checksums are enabled, then disabled, and then re-enabled, every\nrelation's pg_class.relhaschecksums field will be reset to false\nbefore entering the in-progress mode.\"\n\n+ * Disabling checksums is done as an immediate operation as it only updates\n\ns/done as //\n\n+ * to pg_class.relhaschecksums is performed as it only tracks state during\n\nis performed -> are necessary\n\n+ * Access to other members can be done without a lock, as while they are\n+ * in shared memory, they are never concurrently accessed. When a worker\n+ * is running, the launcher is only waiting for that worker to finish.\n\nThe way this is written, it sounds like you're saying that concurrent\naccess might be possible when this structure isn't in shared memory.\nBut since it's called DatachecksumsWorkerShmemStruct that's not likely\na correct conclusion, so I think it needs rephrasing.\n\n+ if (DatachecksumsWorkerShmem->launcher_started &&\n!DatachecksumsWorkerShmem->abort)\n+ started = true;\n\nWhy not started = a && b instead of started = false; if (a && b) started = true?\n\n+ {\n+ LWLockRelease(DatachecksumsWorkerLock);\n+ ereport(ERROR,\n+ (errmsg(\"data checksums worker has been aborted\")));\n+ }\n\nErrors always release LWLocks, so this seems unnecessary. Also, the\nerror message looks confusing from a user perspective. What does it\nmean if I ask you to make me a cheeseburger and you tell me the\ncheeseburger has been eaten? I'm asking for a *new* cheeseburger (or\nin this case, a new worker).\n\nI wonder why this thing is inventing a brand new way of aborting a\nworker, anyway. Why not just keep track of the PID and send it SIGINT\nand have it use CHECK_FOR_INTERRUPTS()? That's already sprinkled all\nover the code, so it's likely to work better than some brand-new\nmechanism that will probably have checks in a lot fewer places.\n\n+ vacuum_delay_point();\n\nHuh? Why?\n\n+ elog(DEBUG2,\n+ \"background worker \\\"datachecksumsworker\\\" starting to process relation %u\",\n+ relationId);\n\nThis and similar messages seem likely they refer needlessly to\ninternals, e.g. this could be \"adding checksums to relation with OID\n%u\" without needing to reference background workers or\ndatachecksumworker. It would be even better if we could find a way to\nreport relation names.\n\n+ * so when the cluster comes back up processing will habe to be resumed.\n\nhabe -> have\n\n+ ereport(FATAL,\n+ (errmsg(\"cannot enable checksums without the postmaster process\"),\n+ errhint(\"Restart the database and restart the checksumming process\nby calling pg_enable_data_checksums().\")));\n\nI understand the motivation for this design and it may be the best we\ncan do, but honestly it kinda sucks. It would be nice if the system\nitself figured out whether or not the worker should be running and, if\nyes, ran it. Like, if we're in this state when we exit recovery (or\ndecide to skip recovery), just register the worker then automatically.\nNow that could still fail for lack of slots, so I guess to make this\nreally robust we'd need a way for the registration to get retried,\ne.g. autovacuum could try to reregister it periodically, and we could\njust blow off the case where autovacuum=off. I don't know. I'd rather\navoid burdening users with an implementation detail if we can get\nthere, or at least minimize what they need to worry about.\n\n+ snprintf(activity, sizeof(activity) - 1,\n+ \"Waiting for worker in database %s (pid %d)\", db->dbname, pid);\n+ pgstat_report_activity(STATE_RUNNING, activity);\n\nSo we only know how to run one such worker at a time?\n\nMaybe WaitForAllTransactionsToFinish should advertise something in\npg_stat_activity.\n\nI think you should try to give all of the functions header comments,\nor at least all the bigger ones.\n\n+ else if (result == DATACHECKSUMSWORKER_ABORTED)\n+ /* Abort flag set, so exit the whole process */\n+ return false;\n\nI'd put braces here. And also, why bail out like this instead of\nretrying periodically until we succeed?\n\n+ * True if all data pages of the relation have data checksums.\n\nNot fully accurate, right?\n\n+ /*\n+ * Force a checkpoint to get everything out to disk. TODO: we probably\n+ * don't want to use a CHECKPOINT_IMMEDIATE here but it's very convenient\n+ * for testing until the patch is fully baked, as it may otherwise make\n+ * tests take a lot longer.\n+ */\n+ RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT | CHECKPOINT_IMMEDIATE);\n\nDo we need to verify that the checkpoint succeeded before we can\ndeclare victory and officially change state?\n\n+ PROCSIGNAL_BARRIER_CHECKSUM_OFF = 0,\n+ PROCSIGNAL_BARRIER_CHECKSUM_INPROGRESS_ON,\n+ PROCSIGNAL_BARRIER_CHECKSUM_ON\n\nI don't think it's a good idea to have three separate types of barrier\nhere. I think you should just have a barrier indicating that the state\nhas changed, and then backends need to reread the state from shared\nmemory when they absorb the barrier.\n\nBut the bigger problem here, and the thing that makes me intensely\ndoubtful that the synchronization in this patch is actually correct,\nis that I can't find any machinery in the patch guarding against\nTOCTTOU issues, nor any comments explaining why I shouldn't be afraid\nof them. Suppose you got rid of the barriers and just changed all the\nplaces that check LocalDataChecksumVersion to read from a shared\nmemory value directly instead. Would that be equivalent to what you've\ngot here, or would it break something? If you can't clearly explain\nwhy that would be broken as compared with what you have, then either\nthe barriers aren't really necessary (which I doubt) or the\nsynchronization isn't really right (which I suspect to be true).\n\nIn the case of the ALTER SYSTEM READ ONLY patch, this was by far the\nhardest part to get right, and I'm still not positive that it's\ncompletely correct, but the basic thing we figured out there is that\nyou are in big trouble if the system goes read-only AFTER you've\ndecided to write a WAL record. That is, this is bugged:\n\nif (WALIsProhibited())\n ereport(ERROR, errmsg(\"i'm sorry i can't do that\"));\n...\nCHECK_FOR_INTERRUPTS();\n...\nSTART_CRIT_SECTION();\nXLogBeginInsert();\n\nIf the CHECK_FOR_INTERRUPTS() absorbs a state change, then the\nXLogBeginInsert() is going to hit an elog(ERROR) which, because we're\nin a critical section, will be promoted to PANIC, which is bad. To\navoid that, the patch introduces a whole hairy system to make sure\nthat there can never be a CFI after we check whether it's OK to insert\nWAL and before we actually do it. That stuff is designed in such a way\nthat it will make assertion fail even if you're not actually *trying*\nto make the system read-only.\n\nSo the comparable problem here would be if we decide that we don't\nneed to set checksums on a page when modifying it, and then we absorb\na barrier that flips the state to in-progress, and then we actually\nperform the page modification. Now you have a race condition: the page\nwas modified without checksums after we'd acknowledged to the process\npushing out the barrier that all of our future page modifications\nwould set checksums. So, maybe that's not possible here. For instance,\nif we never examine the checksum-enabled state outside of a critical\nsection, then we're fine, because we can't absorb a barrier without\nprocessing an interrupt, and we don't process interrupts in critical\nsections. But if that's the case, then it seems to me that it would be\ngood to insert some cross-checks. Like, suppose we only ever access\nthe local variable that contains this state through a static inline\nfunction that also asserts that InteruptHoldoffCount > 0 ||\nCritSectionCount > 0. Then, if there is a place where we don't\nactually follow that rule (only rely on that value within critical\nsections) we're pretty likely to trip an assert just running the\nregression tests. It's not foolproof, not only because the regression\ntests are incomplete but because in theory we could fetch the value in\na crit section and then keep it around and rely on it some more after\nwe've processed interrupts again, but that seems like a less-likely\nthing for somebody to do.\n\nIf, on the other hand, there are stretches of code that fetch this\nvalue outside of a crit section and without interrupts held, then we\nneed some other kind of mechanism here to make it safe. We have to\nmake sure that not only does the present code not permit race\nconditions of the type described above, but that future modifications\nare quite unlikely to introduce any. I might be missing something, but\nI don't see any kind of checks like this in the patch now. I think\nthere should be, and the rationale behind them should be written up,\ntoo.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Wed, 29 Jul 2020 13:58:11 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 29 Jul 2020, at 19:58, Robert Haas <robertmhaas@gmail.com> wrote:\n\n> Here are a bunch of comments based on a partial read-through of this\n> patch.\n\nThanks a lot Robert and Justin for the reviews! With the commitfest wrap-up\nimminent and being on vacation I will have a hard time responding properly\nbefore the end of CF so I'm moving it to the next CF for now.\n\ncheers ./daniel\n\n\n", "msg_date": "Fri, 31 Jul 2020 00:21:11 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 28 Jul 2020, at 04:33, Justin Pryzby <pryzby@telsasoft.com> wrote:\n> \n> On Thu, Jun 25, 2020 at 11:43:00AM +0200, Daniel Gustafsson wrote:\n>> The attached v19 fixes a few doc issues I had missed.\n> \n> + They can also be enabled or disabled at a later timne, either as an offline\n> => time\n\nFixed.\n\n> +\t * awaiting shutdown, but we can continue turning off checksums anyway\n> => a waiting\n\nThis was intentional, as it refers to the impending requested shutdown and not\none which is blocked waiting. I've reworded the comment to make this clearer.\n\n> +\t * We are starting a checksumming process scratch, and need to start by\n> => FROM scratch\n\nFixed.\n\n> +\t * to inprogress new relations will set relhaschecksums in pg_class so it\n> => inprogress COMMA\n\nFixed.\n\n> +\t\t * Relation no longer exist. We don't consider this an error since\n> => exists\n\nFixed.\n\n> +\t * so when the cluster comes back up processing will habe to be resumed.\n> => have\n\nFixed.\n\n> +\t\t\t \"completed one pass over all databases for checksum enabling, %i databases processed\",\n> => I think this will be confusing to be hardcoded \"one\". It'll say \"one\" over\n> and over.\n\nGood point, I've reworded this based on the number of processed databases to\nindicate what will happen next. This call should probably be removed in case\nwe merge and ship this feature, but it's handy for this part of the patch\nprocess.\n\n> +\t\t * still exist.\n> => exists\n\nFixed.\n\n> In many places, you refer to \"datachecksumsworker\" (sums) but in nine places\n> you refer to datachecksumworker (sum).\n\nGood catch, they should all be using \"sums\". Fixed.\n\n> +ProcessSingleRelationFork(Relation reln, ForkNumber forkNum, BufferAccessStrategy strategy)\n> +{\n> +\tBlockNumber numblocks = RelationGetNumberOfBlocksInFork(reln, forkNum);\n> \n> => I think looping over numblocks is safe since new blocks are intended to be\n> written with checksum, right? Maybe it's good to say that here.\n\nFixed.\n\n> +\tBlockNumber b;\n> \n> blknum will be easier to grep for\n\nFixed.\n\n> +\t\t\t(errmsg(\"background worker \\\"datachecksumsworker\\\" starting for database oid %d\",\n> => Should be %u or similar (several of these)\n\nFixed. As per Roberts review downthread, these will be reworded in a future\nversion.\n\n> It looks like you rewrite every page, even if it already has correct checksum,\n> to handle replicas. I wonder if it's possible/reasonable/good to skip pages\n> with correct checksum when wal_level=minimal ?\n\nThat would AFAICT be possible, but I'm not sure it's worth adding that before\nthe patch is deemed safe in its simpler form. I've added a comment to record\nthis as a potential future optimization.\n\n> It looks like it's not possible to change the checksum delay while a checksum\n> worker is already running. That may be important to allow: 1) decreased delay\n> during slow periods; 2) increased delay if the process is significantly done,\n> but needs to be throttled to avoid disrupting production environment.\n> \n> Have you collaborated with Julien about this one? His patch adds new GUCs:\n> https://www.postgresql.org/message-id/20200714090808.GA20780@nol\n> checksum_cost_delay\n> checksum_cost_page\n> checksum_cost_limit\n\nI honestly hadn't thought about that, but I very much agree that any controls\nintroduced should work the same for both of these patches.\n\n> Maybe you'd say that Julien's pg_check_relation() should accept parameters\n> instead of adding GUCs. I think you should be in agreement on that. It'd be\n> silly if the verification function added three GUCs and allowed adjusting\n> throttle midcourse, but the checksum writer process didn't use them.\n\nAgreed. I'm not a fan of using yet more GUCs for controlling this, but I don't\na good argument against it. It's in line with the cost-based vacuum delays so\nI guess it's the most appropriate interface.\n\n> If you used something like that, I guess you'd also want to distinguish\n> checksum_cost_page_read vs write. Possibly, the GUCs part should be a\n> preliminary shared patch 0001 that you both used.\n\n+1.\n\nThanks for the review! I will attach a v20 to Robers email with these changes\nincluded as well.\n\ncheers ./daniel\n\n\n\n", "msg_date": "Tue, 1 Sep 2020 15:50:13 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 29 Jul 2020, at 19:58, Robert Haas <robertmhaas@gmail.com> wrote:\n> \n> On Mon, Jun 22, 2020 at 8:27 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n>> Attached is a new version of the online checksums patch which, I hope, address\n>> most of the concerns raised in previous reviews. There has been a fair amount\n>> of fiddling done, so below is a summary of what has been done.\n> \n> Here are a bunch of comments based on a partial read-through of this\n> patch. The most serious concerns, around synchronization, are down\n> toward at the bottom. Sorry this is a bit eclectic as a review, but I\n> wrote things down as I read through the patch more or less in the\n> order I ran across them.\n\nNot need to apologize, many thanks for the review! This is a partial response,\nsince I need to spend a bit more time to properly respond to the\nsynchronization questions, but I also wanted to submit a new version which\napplies in the CF patch tester. Anything not addressed here will be be in a\nfollow-up version.\n\nThe attached v20 contains fixes from this review as well as Justin's review\nupthread.\n\n> Regarding disable_data_checksums(), I disagree with ereport(LOG, ...)\n> here. If you want to indicate to the caller whether or not a state\n> change occurred, you could consider returning a Boolean instead of\n> void. If you want to do it with log messages, I vote for NOTICE, not\n> LOG. Maybe NOTICE is better, because enable_data_checksums() seems to\n> want to convey more information that you can represent in a Boolean,\n> but then it should use NOTICE consistently, not a mix of NOTICE and\n> LOG.\n\nI agree with this, I've moved to returning a bool rather than ereporting NOTICE\n(or LOG).\n\n> Formatting needs work for project style: typically no braces around\n> single statements, \"ereport(WHATEVER,\" should always have a line break\n> at that point.\n\nI think I've fixed all these instances, and the attached patch have been run\nthrough pgindent as well.\n\n> + * cluster, which was not initialized with checksums, this worker will ensure\n> \n> \"which was not initialized with checksums\" => \"that does not running\n> with checksums enabled\"?\n\nFixed, but it's \"run\" rather than \"running\" right?\n\n> + * turned on. In the case of disabling checksums, the state transition is\n> + * recorded in the catalog and controlfile, no changes are performed\n> + * on the data pages or in the catalog.\n> \n> Comma splice. Either write \"controlfile; no\" or \"controlfile, and no\".\n\nFixed.\n\t\n> My spell-checker complains that controfile, clusterwide, inprogress,\n> and endstate are not words. I think you should think about inserting\n> spaces or, in the case of cluster-wide, a dash, unless they are being\n> used as literals, in which case perhaps those instances should be\n> quoted. \"havent\" needs an apostrophe.\n\nThis is me writing Swedish in English. Fixed.\n\n> + * DataChecksumsWorker will compile a list of databases which exists at the\n> \n> which exist\n\nFixed.\n\n> + * For each database, all relations which have storage are read and every data\n> + * page is marked dirty to force a write with the checksum, this will generate\n> \n> Comma splice. Split into two sentences.\n\nFixed.\n\n> + * In case checksums have been enabled and later disabled, when re-enabling\n> + * pg_class.relhaschecksums will be reset to false before entering inprogress\n> + * mode to ensure that all relations are re-processed.\n> \n> \"If checksums are enabled, then disabled, and then re-enabled, every\n> relation's pg_class.relhaschecksums field will be reset to false\n> before entering the in-progress mode.\"\n\nReplaced with your version, thanks.\n\n> + * Disabling checksums is done as an immediate operation as it only updates\n> \n> s/done as //\n\nFixed.\n\n> + * to pg_class.relhaschecksums is performed as it only tracks state during\n> \n> is performed -> are necessary\n\nFixed.\n\n> + * Access to other members can be done without a lock, as while they are\n> + * in shared memory, they are never concurrently accessed. When a worker\n> + * is running, the launcher is only waiting for that worker to finish.\n> \n> The way this is written, it sounds like you're saying that concurrent\n> access might be possible when this structure isn't in shared memory.\n> But since it's called DatachecksumsWorkerShmemStruct that's not likely\n> a correct conclusion, so I think it needs rephrasing.\n\nRight, that was a pretty poorly worded comment. Rewritten and expanded upon.\n\n> + if (DatachecksumsWorkerShmem->launcher_started &&\n> !DatachecksumsWorkerShmem->abort)\n> + started = true;\n> \n> Why not started = a && b instead of started = false; if (a && b) started = true?\n\nI don't have strong feelings either format, so changed according to your suggestion.\n\n> + {\n> + LWLockRelease(DatachecksumsWorkerLock);\n> + ereport(ERROR,\n> + (errmsg(\"data checksums worker has been aborted\")));\n> + }\n> \n> Errors always release LWLocks, so this seems unnecessary. Also, the\n> error message looks confusing from a user perspective. What does it\n> mean if I ask you to make me a cheeseburger and you tell me the\n> cheeseburger has been eaten? I'm asking for a *new* cheeseburger (or\n> in this case, a new worker).\n\nNow you made me hungry for a green chili cheeseburger..\n\nThis case covers when the user disables a running datachecksumsworker and\nthen enables it again before the worker has finished the current page and thus\nobserved the abort request.\n\nIf the worker learns to distinguish between a user abort request and and an\ninternal cancellation (due to WL_POSTMASTER_DEATH) this window could be handled\nby clearing the user request and keep going. It would be the same thing as\nkilling the worker and restarting, except fewer moving parts. Either way, I\nagree that it's a confusing error path, and one which should be addressed.\n\n> I wonder why this thing is inventing a brand new way of aborting a\n> worker, anyway. Why not just keep track of the PID and send it SIGINT\n> and have it use CHECK_FOR_INTERRUPTS()? That's already sprinkled all\n> over the code, so it's likely to work better than some brand-new\n> mechanism that will probably have checks in a lot fewer places.\n\nI'm not convinced that the current coding is less responsive, and signalling\nfor launcher/worker isn't entirely straightforward, but I agree that it's\nbetter to stick to established patterns. Will rewrite to use pqsignal/SIGINT\nand will address the previous paragraph in that as well.\n\n> + vacuum_delay_point();\n> \n> Huh? Why?\n\nThe datachecksumsworker is using the same machinery for throttling as the\ncost-based vacuum delay, hence this call. Do you object to using that same\nmachinery, or the implementation and/or documentation of it?\n\n> + elog(DEBUG2,\n> + \"background worker \\\"datachecksumsworker\\\" starting to process relation %u\",\n> + relationId);\n> \n> This and similar messages seem likely they refer needlessly to\n> internals, e.g. this could be \"adding checksums to relation with OID\n> %u\" without needing to reference background workers or\n> datachecksumworker.\n\nI have reworded these as well as removed a few that seemed a bit uninteresting.\n\n> It would be even better if we could find a way to\n> report relation names.\n\nTrue, but doesn't really seem worth the overhead for a debug log.\n\n> + * so when the cluster comes back up processing will habe to be resumed.\n> \n> habe -> have\n\nFixed (also noted by Justin upthread).\n\n> + ereport(FATAL,\n> + (errmsg(\"cannot enable checksums without the postmaster process\"),\n> + errhint(\"Restart the database and restart the checksumming process\n> by calling pg_enable_data_checksums().\")));\n> \n> I understand the motivation for this design and it may be the best we\n> can do, but honestly it kinda sucks. It would be nice if the system\n> itself figured out whether or not the worker should be running and, if\n> yes, ran it. Like, if we're in this state when we exit recovery (or\n> decide to skip recovery), just register the worker then automatically.\n> Now that could still fail for lack of slots, so I guess to make this\n> really robust we'd need a way for the registration to get retried,\n> e.g. autovacuum could try to reregister it periodically, and we could\n> just blow off the case where autovacuum=off. I don't know. I'd rather\n> avoid burdening users with an implementation detail if we can get\n> there, or at least minimize what they need to worry about.\n\nI don't disagree with you, but I don't see how an automatic restart could be\nmade safe/good enough to be worth the complexity, since it's nigh impossible to\nmake it always Just Work. Exposing implementation details to users is clearly\nnot a good design choice, if it can be avoided.\n\n> + snprintf(activity, sizeof(activity) - 1,\n> + \"Waiting for worker in database %s (pid %d)\", db->dbname, pid);\n> + pgstat_report_activity(STATE_RUNNING, activity);\n> \n> So we only know how to run one such worker at a time?\n\nCorrect, there is currently one worker at a time.\n\n> Maybe WaitForAllTransactionsToFinish should advertise something in\n> pg_stat_activity.\n\nIt currently does this:\n\n snprintf(activity,\n sizeof(activity),\n \"Waiting for current transactions to finish (waiting for %u)\",\n waitforxid);\n pgstat_report_activity(STATE_RUNNING, activity);\n\nDid you have anything else in mind?\n\n> I think you should try to give all of the functions header comments,\n> or at least all the bigger ones.\n\nI've done a first pass over the patch.\n\n> + else if (result == DATACHECKSUMSWORKER_ABORTED)\n> + /* Abort flag set, so exit the whole process */\n> + return false;\n> \n> I'd put braces here.\n\nFixed.\n\n> And also, why bail out like this instead of\n> retrying periodically until we succeed?\n\nCurrently, the abort request can come from the user disabling data checksums\nduring processing, postmaster dying or SIGINT. Neither of these cases qualify\nfor retrying in the current design.\n\n> + * True if all data pages of the relation have data checksums.\n> \n> Not fully accurate, right?\n\nUgh.. thats a leftover from previous hacking that I've since ripped out.\nSorry about that, it's been removed.\n\n> + /*\n> + * Force a checkpoint to get everything out to disk. TODO: we probably\n> + * don't want to use a CHECKPOINT_IMMEDIATE here but it's very convenient\n> + * for testing until the patch is fully baked, as it may otherwise make\n> + * tests take a lot longer.\n> + */\n> + RequestCheckpoint(CHECKPOINT_FORCE | CHECKPOINT_WAIT | CHECKPOINT_IMMEDIATE);\n> \n> Do we need to verify that the checkpoint succeeded before we can\n> declare victory and officially change state?\n\nI don't think we need a verification step here. With CHECKPOINT_WAIT we are\nblocking until the checkpoint has completed. If it fails we won't enable data\nchecksums until the process has been restarted and a subsequent checkpoint\nsucceeded.\n\n> + PROCSIGNAL_BARRIER_CHECKSUM_OFF = 0,\n> + PROCSIGNAL_BARRIER_CHECKSUM_INPROGRESS_ON,\n> + PROCSIGNAL_BARRIER_CHECKSUM_ON\n> \n> I don't think it's a good idea to have three separate types of barrier\n> here. I think you should just have a barrier indicating that the state\n> has changed, and then backends need to reread the state from shared\n> memory when they absorb the barrier.\n\nI'm not sure I follow why, my understanding of the infrastructure was to make\nit finegrained like this. But, you have clearly spent more time thinking about\nthis functionality so I'm curious to learn. Can you elaborate on your\nthinking?\n\n> But the bigger problem here, and the thing that makes me intensely\n> doubtful that the synchronization in this patch is actually correct,\n> is that I can't find any machinery in the patch guarding against\n> TOCTTOU issues, nor any comments explaining why I shouldn't be afraid\n> of them.\n\n<snip>\n\nI unfortunately haven't had time to read the READ ONLY patch so I can't comment\non how these two patches do things in relation to each other.\n\nThe main synchronization mechanisms are the use of the inprogress mode where\ndata checksums are written but not verified, and by waiting for all\npre-existing non-compatible processes (transactions, temp tables) to disappear\nbefore enabling.\n\nThat being handwavily said, I've started to write down a matrix with classes of\npossible synchronization bugs and how the patch handles them in order to\nproperly respond.\n\ncheers ./daniel", "msg_date": "Wed, 2 Sep 2020 14:22:25 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Wed, Sep 02, 2020 at 02:22:25PM +0200, Daniel Gustafsson wrote:\n> I unfortunately haven't had time to read the READ ONLY patch so I can't comment\n> on how these two patches do things in relation to each other.\n> \n> The main synchronization mechanisms are the use of the inprogress mode where\n> data checksums are written but not verified, and by waiting for all\n> pre-existing non-compatible processes (transactions, temp tables) to disappear\n> before enabling.\n\nThe CF bot is complaining on this one with a TAP test failure:\nhttps://travis-ci.org/github/postgresql-cfbot/postgresql/builds/724717901\n\nt/003_standby_checksum.pl .. 1/10\n# Failed test 'ensure checksums are on or in progress on standby_1'\n# at t/003_standby_checksum.pl line 59.\n# 'off'\n# ~~\n# 'ARRAY(0x1d38c10)'\n# Looks like you failed 1 test of 10.\nt/003_standby_checksum.pl .. Dubious, test returned 1 (wstat 256,\n0x100)\nFailed 1/10 subtests\n\nDaniel, could you look at that?\n--\nMichael", "msg_date": "Mon, 7 Sep 2020 16:17:11 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 2 Sep 2020, at 14:22, Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> The main synchronization mechanisms are the use of the inprogress mode where\n> data checksums are written but not verified, and by waiting for all\n> pre-existing non-compatible processes (transactions, temp tables) to disappear\n> before enabling.\n> \n> That being handwavily said, I've started to write down a matrix with classes of\n> possible synchronization bugs and how the patch handles them in order to\n> properly respond.\n\nHaving spent some more time on this, I believe I have a better answer (and\npatch version) to give.\n\nFirst, a thank you for asking insightful questions. While working through the\ncases I realized that the previous version has a problematic window: when\ndisabling checksums, if backend A absorbs the data checksums \"off\" barrier (or\nstarts after the controlfile has been changed) and writes a page without a\nchecksum, while backend B has yet to absorb the barrier and is still in \"on\"\nand reads that very same page. The solution IMO is to introduce an inprogress\nstate for disabling as well where all backends keep writing checksums but not\nvalidating them until no backend is in \"on\" state anymore. Once all backends\nare in \"inprogress-off\", they can stop writing checksums and transition to\n\"off\". I even had this state in a previous unsubmitted version, embarrassingly\nso to the point of the function prototype being there as a leftover in v19.\n\nNow, synchronization happens on two levels in this patch for both the enable\nand disable case : (i) between backends when transitioning between states and\n(ii) inside the worker when synchronizing the current backends.\n\nFor (i) it's using \"inprogress\" states to ensure a safe transition to \"on\" or\n\"off\". The states are themselves transitioned to via procsignalbarriers. Both\nenabling and disabling follow the same logic, with the only difference being\nthe order in which operations are switched on/off during inprogress. For (ii)\nthe workers are waiting for incompatible concurrent processing to end, such as\ntemporary tables etc (only affects enabling data checksums).\n\nI've tried to write down the synchronization steps in datachecksumsworker.c to\ndocument the code, and for ease of discussion I've pasted that part of the diff\nbelow as well:\n\n * Synchronization and Correctness\n * -------------------------------\n * The processes involved in enabling, or disabling, data checksums in an\n * online cluster must be properly synchronized with the normal backends\n * serving concurrent queries to ensure correctness. Correctness is defined\n * as the following:\n *\n *\t\t- Backends SHALL NOT violate local datachecksum state\n *\t\t- Data checksums SHALL NOT be considered enabled cluster-wide until all\n *\t\t currently connected backends have the local state \"enabled\"\n *\n * There are two levels of synchronization required for enabling data checksums\n * in an online cluster: (i) changing state in the active backends (\"on\",\n * \"off\", \"inprogress-on\" and \"inprogress-off\"), and (ii) ensuring no\n * incompatible objects and processes are left in a database when workers end.\n * The former deals with cluster-wide agreement on data checksum state and the\n * latter with ensuring that any concurrent activity cannot break the data\n * checksum contract during processing.\n *\n * Synchronizing the state change is done with procsignal barriers, where the\n * backend updating the global state in the controlfile will wait for all other\n * backends to absorb the barrier before WAL logging. Barrier absorption will\n * happen during interrupt processing, which means that connected backends will\n * change state at different times.\n *\n * When Enabling Data Checksums\n *\t ----------------------------\n *\t A process which fails to observe data checksums being enabled can induce\n *\t two types of errors: failing to write the checksum when modifying the page\n *\t and failing to validate the data checksum on the page when reading it.\n *\n * When the DataChecksumsWorker has finished writing checksums on all pages\n * and enable data checksums cluster-wide, there are three sets of backends:\n *\n * Bg: Backend updating the global state and emitting the procsignalbarrier\n * Bd: Backends on \"off\" state\n * Be: Backends in \"on\" state\n * Bi: Backends in \"inprogress-on\" state\n *\n * Backends transition from the Bd state to Be like so: Bd -> Bi -> Be\n *\n * Backends in Bi and Be will write checksums when modifying a page, but only\n * backends in Be will verify the checksum during reading. The Bg backend is\n * blocked waiting for all backends in Bi to process interrupts and move to\n * Be. Any backend starting will observe the global state being \"on\" and will\n * thus automatically belong to Be. Checksums are enabled cluster-wide when\n * Bi is an empty set. All sets are compatible while still operating based on\n * their local state.\n *\n *\t When Disabling Data Checksums\n *\t -----------------------------\n *\t A process which fails to observe data checksums being disabled can induce\n *\t two types of errors: writing the checksum when modifying the page and\n *\t validating a data checksum which is no longer correct due to modifications\n *\t to the page.\n *\n * Bg: Backend updating the global state and emitting the procsignalbarrier\n * Bd: Backands in \"off\" state\n * Be: Backends in \"on\" state\n * Bi: Backends in \"inprogress-off\" state\n *\n * Backends transition from the Be state to Bd like so: Be -> Bi -> Bd\n *\n * The goal is to transition all backends to Bd making the others empty sets.\n * Backends in Bi writes data checksums, but don't validate them, such that\n * backends still in Be can continue to validate pages until the barrier has\n * been absorbed such that they are in Bi. Once all backends are in Bi, the\n * barrier to transition to \"off\" can be raised and all backends can safely\n * stop writing data checksums as no backend is enforcing data checksum\n * validation.\n\nI hope this clarifies the reasoning behind the implementation.\n\nThis has been implemented in the attached v21 patch. \"inprogress\" was in need\nof a new name before, and with \"inprogress-{on|off}\" the need is even bigger.\nSuggestions for better names are highly appreciated, I'm drawing blanks here.\n\nThere are some minor fixes and documentation touchups in this version as well,\nbut not the SIGINT handling since I wanted to focus on one thing at a time.\n\ncheers ./daniel", "msg_date": "Wed, 9 Sep 2020 16:23:01 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 7 Sep 2020, at 09:17, Michael Paquier <michael@paquier.xyz> wrote:\n\n> Daniel, could you look at that?\n\nI believe this boils down to a timing issue, I've included a fix in the v21\npatch attached to a previous mail upthread.\n\ncheers ./daniel\n\n\n", "msg_date": "Wed, 9 Sep 2020 16:24:10 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "+ * changed to \"inprogress-off\", the barrier for mvoving to \"off\" can be\nmoving\n\n+ * When disabling checksums, data_checksums will be set of \"inprogress-off\"\nset *to*\n\n+\tget_namespace_name(RelationGetNamespace(reln)), RelationGetRelationName(reln),\n\nI think this palloc()s a new copy of the namespace every 100 blocks.\nBetter do it outside the loop.\n\n+\t{\"inprogress-on\", DATA_CHECKSUMS_INPROGRESS_ON, true},\n+\t{\"inprogress-off\", DATA_CHECKSUMS_INPROGRESS_OFF, true},\n\nenabling / disabling ?\n\n+typedef enum ChecksumType\n+{\n+\tDATA_CHECKSUMS_OFF = 0,\n+\tDATA_CHECKSUMS_ON,\n+\tDATA_CHECKSUMS_INPROGRESS_ON,\n+\tDATA_CHECKSUMS_INPROGRESS_OFF\n+}\t\t\tChecksumType;\n\nShould this be an bitmask, maybe\nDATA_CHECKSUMS_WRITE = 1 \nDATA_CHECKSUMS_VERIFY = 2,\n\nIt occured to me that you could rephrase this patch as \"Make checksum state\nper-relation rather than cluster granularity\". That's currently an\nimplementation detail, but could be exposed as a feature. That could be a\npreliminary 0001 patch. Half the existing patch would be 0002 \"Allow\nonline enabling checksums for a given relation/database/cluster\". You might\nsave some of the existing effort of synchronize the cluster-wide checksum\nstate, since it doesn't need to be synchronized. The \"data_checksums\" GUC\nmight be removed, or changed to an enum: on/off/per_relation. Moving from\n\"per_relation\" to \"on\" would be an optional metadata-only change, allowed only\nwhen all rels in all dbs are checksumed. I'm not sure if you'd even care about\ntemp tables, since \"relhaschecksum\" would be authoritative, rather than a\nsecondary bit only used during processing.\n\nXLogHintBitIsNeeded() and DataChecksumsEnabled() would need to check\nrelhaschecksum, which tentatively seems possible.\n\nI'm not sure if it's possible, but maybe pg_checksums would be able to skip\nrels which had already been checksummed \"online\" (with an option to force\nreprocessing).\n\nMaybe some people would want (no) checksums on specific tables, and that could\neventually be implemented as 0003: \"ALTER TABLE SET checksums=\". I'm thinking\nof that being used immediately after an CREATE, but I suppose ON would cause\nthe backend to rewrite the table with checksums synchronously (not in the BGW),\neither with AEL or by calling ProcessSingleRelationByOid().\n\n-- \nJustin\n\n\n", "msg_date": "Fri, 18 Sep 2020 21:18:11 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 19 Sep 2020, at 04:18, Justin Pryzby <pryzby@telsasoft.com> wrote:\n\nThanks for reviewing!\n\n> + * changed to \"inprogress-off\", the barrier for mvoving to \"off\" can be\n> moving\n\nFixed.\n\n> + * When disabling checksums, data_checksums will be set of \"inprogress-off\"\n> set *to*\n\nFixed.\n\n> +\tget_namespace_name(RelationGetNamespace(reln)), RelationGetRelationName(reln),\n> \n> I think this palloc()s a new copy of the namespace every 100 blocks.\n> Better do it outside the loop.\n\nGood point, fixed.\n\n> +\t{\"inprogress-on\", DATA_CHECKSUMS_INPROGRESS_ON, true},\n> +\t{\"inprogress-off\", DATA_CHECKSUMS_INPROGRESS_OFF, true},\n> \n> enabling / disabling ?\n\nPerhaps, but it doesn't match the grammatical tense of others though?\n\n> +typedef enum ChecksumType\n> +{\n> +\tDATA_CHECKSUMS_OFF = 0,\n> +\tDATA_CHECKSUMS_ON,\n> +\tDATA_CHECKSUMS_INPROGRESS_ON,\n> +\tDATA_CHECKSUMS_INPROGRESS_OFF\n> +}\t\t\tChecksumType;\n> \n> Should this be an bitmask, maybe\n> DATA_CHECKSUMS_WRITE = 1 \n> DATA_CHECKSUMS_VERIFY = 2,\n\nThat's an option, not sure if it would improve readability though. Anyone else\nhave opinions on that?\n\n> It occured to me that you could rephrase this patch as \"Make checksum state\n> per-relation rather than cluster granularity\". That's currently an\n> implementation detail, but could be exposed as a feature.\n\nThats not entirely correct. The patch tracks checksum status *during\ninprogress-on* with per-relation granularity, but as it stands it doesn't\nsupport per-relation during state \"on\" in any way.\n\nA per-relation checksum mode where every relation at any point can enable or\ndisable checksums would require a very different synchronization mechanism from\nthe all-or-nothing one (which while simpler, IMO is complicated enough). My\nhope is that this patch brings solid infrastructure for anyone interested in\npersuing per-relation checksums, but IMHO we should focus on getting\nper-cluster rock-solid first.\n\n> That could be a\n> preliminary 0001 patch. Half the existing patch would be 0002 \"Allow\n> online enabling checksums for a given relation/database/cluster\". You might\n> save some of the existing effort of synchronize the cluster-wide checksum\n> state, since it doesn't need to be synchronized.\n\nI don't follow, how would a finer-grain resolution remove the need for\nsynchronization?\n\n> The \"data_checksums\" GUC\n> might be removed, or changed to an enum: on/off/per_relation. Moving from\n> \"per_relation\" to \"on\" would be an optional metadata-only change, allowed only\n> when all rels in all dbs are checksumed.\n\nHow would you guarantee that such a state change isn't happening concurrently\nwith a user doing ALTER TABLE .. checksums=off;? It would still require\nsynchronization along the lines of what this patch does unless I'm missing\nsomething.\n\n> I'm not sure if you'd even care about\n> temp tables, since \"relhaschecksum\" would be authoritative, rather than a\n> secondary bit only used during processing.\n> \n> XLogHintBitIsNeeded() and DataChecksumsEnabled() would need to check\n> relhaschecksum, which tentatively seems possible.\n\nWhile possible, that's a pretty hot codepath so any additional checking will\nneed proper benchmarking.\n\nrelhaschecksum isn't guaranteed to be correct at any point other than during\nchecksum enabling, it's only used for tracking progress in case of a cluster\nrestart during processing. To better convey this, I asked for suggestions for\nbetter name upthread since relhaschecksum carries the risk of overpromise/\nunderdeliver. Perhaps relchecksumprocessed would be better?\n\nA real per-relation relhaschecksum in pg_class would also need to solve how to\nkeep it accurate for offline enable/disable via pg_checksums.\n\n> I'm not sure if it's possible, but maybe pg_checksums would be able to skip\n> rels which had already been checksummed \"online\" (with an option to force\n> reprocessing).\n\npg_checksums can't read the catalog state of the relations, so is has no\nknowledge on where an online processing left off. That should probably be made\nclearer in the docs though, so added a note on that.\n\n> Maybe some people would want (no) checksums on specific tables, and that could\n> eventually be implemented as 0003: \"ALTER TABLE SET checksums=\". I'm thinking\n> of that being used immediately after an CREATE, but I suppose ON would cause\n> the backend to rewrite the table with checksums synchronously (not in the BGW),\n> either with AEL or by calling ProcessSingleRelationByOid().\n\nHolding an AEL while changing state would be easier as it skips the need for\nthe complex synchronization, but is that really what users would expect?\nEspecially if cluster-wide enable is done transparent to the user.\n\nMore importantly though, what is the use-case for per-relation that we'd be\nlooking at solving? Discussing the implementation without framing it in an\nactual use-case runs the risk of performing successful surgery where the\npatient still dies. Performing ETL ingestion without the overhead of writing\nchecksums? Ephemeral data? Maybe unlogged tables can handle some situation\nwhere checksums would be appealing?\n\nWhile in the patch I realized that the relationlist saved the relkind but the\ncode wasn't actually using it, so I've gone ahead and removed that with a lot\nfewer palloc calls as a result. The attached v22 fixes that and the above.\n\ncheers ./daniel", "msg_date": "Wed, 23 Sep 2020 14:34:36 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Wed, Sep 23, 2020 at 02:34:36PM +0200, Daniel Gustafsson wrote:\n> While in the patch I realized that the relationlist saved the relkind but the\n> code wasn't actually using it, so I've gone ahead and removed that with a lot\n> fewer palloc calls as a result. The attached v22 fixes that and the above.\n\nSome of the TAP tests are blowing up here, as the CF bot is telling:\nt/003_standby_checksum.pl .. 1/11 # Looks like you planned 11 tests but ran 4.\n# Looks like your test exited with 29 just after 4.\nt/003_standby_checksum.pl .. Dubious, test returned 29 (wstat 7424, 0x1d00)\n--\nMichael", "msg_date": "Thu, 24 Sep 2020 13:27:42 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 24 Sep 2020, at 06:27, Michael Paquier <michael@paquier.xyz> wrote:\n> \n> On Wed, Sep 23, 2020 at 02:34:36PM +0200, Daniel Gustafsson wrote:\n>> While in the patch I realized that the relationlist saved the relkind but the\n>> code wasn't actually using it, so I've gone ahead and removed that with a lot\n>> fewer palloc calls as a result. The attached v22 fixes that and the above.\n> \n> Some of the TAP tests are blowing up here, as the CF bot is telling:\n> t/003_standby_checksum.pl .. 1/11 # Looks like you planned 11 tests but ran 4.\n> # Looks like your test exited with 29 just after 4.\n> t/003_standby_checksum.pl .. Dubious, test returned 29 (wstat 7424, 0x1d00)\n\nInteresting, I've been unable to trigger a fault and the latest Travis build\nwas green. I'll continue to try and see if I can shake something loose.\n\ncheers ./daniel\n\n\n\n", "msg_date": "Thu, 24 Sep 2020 09:24:19 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "I looked at patch v22, and I can see two main issues:\n\n1. The one that Robert talked about earlier: A backend checks the local \n\"checksums\" state. If it's 'off', it writes a page without checksums. \nHow do you guarantee that the local state doesn't change in between? The \nimplicit assumption seems to be that there MUST NOT be any \nCHECK_FOR_INTERRUPTS() calls between DataChecksumsNeedWrite() and the \nwrite (or read and DataChecksumsNeedVerify()).\n\nIn most code, the DataChecksumsNeedWrite() call is very close to writing \nout the page, often in the same critical section. But this is an \nundocumented assumption.\n\nThe code in sendFile() in basebackup.c seems suspicious in that regard. \nIt calls DataChecksumsNeedVerify() once before starting to read the \nfile. Isn't it possible for the checksums flag to change while it's \nreading the file and sending it to the client? I hope there are \nCHECK_FOR_INTERRUPTS() calls buried somewhere in the loop, because it \ncould take minutes to send the whole file.\n\nI would feel better if the state transition of the \"checksums\" flag \ncould only happen in a few safe places, or there were some other \nsafeguards for this. I think that's what Andres was trying to say \nearlier in the thread on ProcSignalBarriers. I'm not sure what the \ninterface to that should be. It could be something like \nHOLD/RESUME_INTERRUPTS(), where normally all procsignals are handled on \nCHECK_FOR_INTERRUPTS(), but you could \"hold off\" some if needed. Or \nsomething else. Or maybe we can just use HOLD/RESUME_INTERRUPTS() for \nthis. It's more coarse-grained than necessary, but probably doesn't \nmatter in practice.\n\nAt minimum, there needs to be comments in DataChecksumsNeedWrite() and \nDataChecksumsNeedVerify(), instructing how to use them safely. Namely, \nyou must ensure that there are no interrupts between the \nDataChecksumsNeedWrite() and writing out the page, or between reading \nthe page and the DataChecksumsNeedVerify() call. You can achieve that \nwith HOLD_INTERRUPTS() or a critical section, or simply ensuring that \nthere is no substantial code in between that could call \nCHECK_FOR_INTERRUPTS(). And sendFile() in basebackup.c needs to be fixed.\n\nPerhaps you could have \"Assert(InteruptHoldOffCount > 0)\" in \nDataChecksumsNeedWrite() and DataChecksumsNeedVerify()? There could be \nother ways that callers could avoid the TOCTOU issue, but it would \nprobably catch most of the unsafe call patterns, and you could always \nwrap the DataChecksumsNeedWrite/verify() call in a dummy \nHOLD_INTERRUPTS() block to work around the assertion if you know what \nyou're doing.\n\n\n2. The signaling between enable_data_checksums() and the launcher \nprocess looks funny to me. The general idea seems to be that \nenable_data_checksums() just starts the launcher process, and the \nlauncher process figures out what it need to do and makes all the \nchanges to the global state. But then there's this violation of the \nidea: enable_data_checksums() checks DataChecksumsOnInProgress(), and \ntells the launcher process whether it should continue a previously \ncrashed operation or start from scratch. I think it would be much \ncleaner if the launcher process figured that out itself, and \nenable_data_checksums() would just tell the launcher what the target \nstate is.\n\nenable_data_checksums() and disable_data_checksums() seem prone to race \nconditions. If you call enable_data_checksums() in two backends \nconcurrently, depending on the timing, there are two possible outcomes:\n\na) One call returns true, and launches the background process. The other \ncall returns false.\n\nb) Both calls return true, but one of them emits a \"NOTICE: data \nchecksums worker is already running\".\n\nIn disable_data_checksum() imagine what happens if another backend calls \nenable_data_checksums() in between the \nShutdownDatachecksumsWorkerIfRunning() and SetDataChecksumsOff() calls.\n\n\n> \t\t/*\n> \t\t * Mark the buffer as dirty and force a full page write. We have to\n> \t\t * re-write the page to WAL even if the checksum hasn't changed,\n> \t\t * because if there is a replica it might have a slightly different\n> \t\t * version of the page with an invalid checksum, caused by unlogged\n> \t\t * changes (e.g. hintbits) on the master happening while checksums\n> \t\t * were off. This can happen if there was a valid checksum on the page\n> \t\t * at one point in the past, so only when checksums are first on, then\n> \t\t * off, and then turned on again. Iff wal_level is set to \"minimal\",\n> \t\t * this could be avoided iff the checksum is calculated to be correct.\n> \t\t */\n> \t\tSTART_CRIT_SECTION();\n> \t\tMarkBufferDirty(buf);\n> \t\tlog_newpage_buffer(buf, false);\n> \t\tEND_CRIT_SECTION();\n\nIt's really unfortunate that we have to dirty the page even if the \nchecksum already happens to match. Could we only do the \nlog_newpage_buffer() call and skip MarkBufferDirty() in that case?\n\nCould we get away with a more lightweight WAL record that doesn't \ncontain the full-page image, but just the block number? On replay, the \nredo routine would read the page from disk.\n\n- Heikki\n\n\n", "msg_date": "Mon, 5 Oct 2020 14:36:39 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "Replying to an older message in this thread:\n\n>> + /*\n>> + * If we reach this point with checksums in inprogress state, we notify\n>> + * the user that they need to manually restart the process to enable\n>> + * checksums. This is because we cannot launch a dynamic background worker\n>> + * directly from here, it has to be launched from a regular backend.\n>> + */\n>> + if (ControlFile->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_VERSION)\n>> + ereport(WARNING,\n>> + (errmsg(\"checksum state is \\\"inprogress\\\" with no worker\"),\n>> + errhint(\"Either disable or enable checksums by calling the\n>> pg_disable_data_checksums() or pg_enable_data_checksums()\n>> functions.\")));\n>> \n>> This seems pretty half-baked.\n> \n> I don't disagree with that. However, given that enabling checksums is a pretty\n> intensive operation it seems somewhat unfriendly to automatically restart. As\n> a DBA I wouldn't want that to kick off without manual intervention, but there\n> is also the risk of this being missed due to assumptions that it would restart.\n> Any ideas on how to treat this?\n> \n> If/when we can restart the processing where it left off, without the need to go\n> over all data again, things might be different wrt the default action.\n\nThe later patch version do support restarting, so I think we should \nrevisit this issue. I would expect the checksums worker to be \nautomatically started at postmaster startup. Can we make that happen?\n\n- Heikki\n\n\n", "msg_date": "Mon, 5 Oct 2020 15:14:31 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On 2020-Oct-05, Heikki Linnakangas wrote:\n\n> The code in sendFile() in basebackup.c seems suspicious in that regard. It\n> calls DataChecksumsNeedVerify() once before starting to read the file. Isn't\n> it possible for the checksums flag to change while it's reading the file and\n> sending it to the client? I hope there are CHECK_FOR_INTERRUPTS() calls\n> buried somewhere in the loop, because it could take minutes to send the\n> whole file.\n> \n> I would feel better if the state transition of the \"checksums\" flag could\n> only happen in a few safe places, or there were some other safeguards for\n> this. I think that's what Andres was trying to say earlier in the thread on\n> ProcSignalBarriers. I'm not sure what the interface to that should be. It\n> could be something like HOLD/RESUME_INTERRUPTS(), where normally all\n> procsignals are handled on CHECK_FOR_INTERRUPTS(), but you could \"hold off\"\n> some if needed. Or something else. Or maybe we can just use\n> HOLD/RESUME_INTERRUPTS() for this. It's more coarse-grained than necessary,\n> but probably doesn't matter in practice.\n\nI hope you're not suggesting that interrupts would be held for the whole\ntransmission of a file, which you say could take minutes. If we do have\nan interrupt holdoff, then it has to be pretty short; users (and\nsystemd) despair if service shutdown is delayed more than a few seconds.\n\n\n\n", "msg_date": "Mon, 5 Oct 2020 11:25:51 -0300", "msg_from": "=?iso-8859-1?Q?=C1lvaro?= Herrera <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On 05/10/2020 17:25, Álvaro Herrera wrote:\n> On 2020-Oct-05, Heikki Linnakangas wrote:\n> \n>> The code in sendFile() in basebackup.c seems suspicious in that regard. It\n>> calls DataChecksumsNeedVerify() once before starting to read the file. Isn't\n>> it possible for the checksums flag to change while it's reading the file and\n>> sending it to the client? I hope there are CHECK_FOR_INTERRUPTS() calls\n>> buried somewhere in the loop, because it could take minutes to send the\n>> whole file.\n>>\n>> I would feel better if the state transition of the \"checksums\" flag could\n>> only happen in a few safe places, or there were some other safeguards for\n>> this. I think that's what Andres was trying to say earlier in the thread on\n>> ProcSignalBarriers. I'm not sure what the interface to that should be. It\n>> could be something like HOLD/RESUME_INTERRUPTS(), where normally all\n>> procsignals are handled on CHECK_FOR_INTERRUPTS(), but you could \"hold off\"\n>> some if needed. Or something else. Or maybe we can just use\n>> HOLD/RESUME_INTERRUPTS() for this. It's more coarse-grained than necessary,\n>> but probably doesn't matter in practice.\n> \n> I hope you're not suggesting that interrupts would be held for the whole\n> transmission of a file, which you say could take minutes. If we do have\n> an interrupt holdoff, then it has to be pretty short; users (and\n> systemd) despair if service shutdown is delayed more than a few seconds.\n\nI'm not suggesting that, sorry I wasn't clear. That would indeed be \nhorrible.\n\nsendFile() needs a different solution, but all the other places where \nDataChecksumsNeedWrite/Verify() is called need to be inspected to make \nsure that they hold interrupts, or ensure some other way that an \ninterrupt doesn't change the local checksums flag between the \nDataChecksumsNeedWrite/Verify() call and the read/write.\n\nI think sendFile() needs to re-check the local checksums state before \neach read. It also needs to ensure that an interrupt doesn't occur and \nchange the local checksums state between read and the \nDataChecksumsNeedVerify() calls, but that's a very short period if you \ncall DataChecksumsNeedVerify() again for each block.\n\n- Heikki\n\n\n", "msg_date": "Mon, 5 Oct 2020 17:46:17 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 5 Oct 2020, at 14:14, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> \n> Replying to an older message in this thread:\n> \n>>> + /*\n>>> + * If we reach this point with checksums in inprogress state, we notify\n>>> + * the user that they need to manually restart the process to enable\n>>> + * checksums. This is because we cannot launch a dynamic background worker\n>>> + * directly from here, it has to be launched from a regular backend.\n>>> + */\n>>> + if (ControlFile->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_VERSION)\n>>> + ereport(WARNING,\n>>> + (errmsg(\"checksum state is \\\"inprogress\\\" with no worker\"),\n>>> + errhint(\"Either disable or enable checksums by calling the\n>>> pg_disable_data_checksums() or pg_enable_data_checksums()\n>>> functions.\")));\n>>> This seems pretty half-baked.\n>> I don't disagree with that. However, given that enabling checksums is a pretty\n>> intensive operation it seems somewhat unfriendly to automatically restart. As\n>> a DBA I wouldn't want that to kick off without manual intervention, but there\n>> is also the risk of this being missed due to assumptions that it would restart.\n>> Any ideas on how to treat this?\n>> If/when we can restart the processing where it left off, without the need to go\n>> over all data again, things might be different wrt the default action.\n> \n> The later patch version do support restarting, so I think we should revisit this issue.\n\nAgreed, now it makes sense to restart automatically.\n\n> I would expect the checksums worker to be automatically started at postmaster startup. Can we make that happen?\n\nA dynamic background worker has to be registered from a regular backend, so\nit's not entirely clear to me where in startup processing that would take\nplace. Do you have any good suggestions?\n\ncheers ./daniel\n\n", "msg_date": "Thu, 12 Nov 2020 14:17:31 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On 12/11/2020 15:17, Daniel Gustafsson wrote:\n>> On 5 Oct 2020, at 14:14, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>> I would expect the checksums worker to be automatically started at postmaster startup. Can we make that happen?\n> \n> A dynamic background worker has to be registered from a regular backend, so\n> it's not entirely clear to me where in startup processing that would take\n> place. Do you have any good suggestions?\n\nCould you launch it from the startup process, in StartupXLOG()?\nDoes it have to be dynamic?\n\n- Heikki\n\n\n", "msg_date": "Fri, 13 Nov 2020 13:22:41 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Fri, Nov 13, 2020 at 12:22 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n\n> On 12/11/2020 15:17, Daniel Gustafsson wrote:\n> >> On 5 Oct 2020, at 14:14, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> >> I would expect the checksums worker to be automatically started at\n> postmaster startup. Can we make that happen?\n> >\n> > A dynamic background worker has to be registered from a regular backend,\n> so\n> > it's not entirely clear to me where in startup processing that would take\n> > place. Do you have any good suggestions?\n>\n> Could you launch it from the startup process, in StartupXLOG()?\n> Does it have to be dynamic?\n>\n\n\nIf it's not dynamic, you can't start it from a regular backend can you? So\nthen you'd need a restart for it to happen?\n\nAs for launching it from the startup process I don't know, that might be a\nviable path. The code specifically explains why it's not possible to launch\nit from the postmaster, but I don't see anything that would make it\nimpossible from the startup process.\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/ <http://www.hagander.net/>\n Work: https://www.redpill-linpro.com/ <http://www.redpill-linpro.com/>\n\nOn Fri, Nov 13, 2020 at 12:22 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:On 12/11/2020 15:17, Daniel Gustafsson wrote:\n>> On 5 Oct 2020, at 14:14, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>> I would expect the checksums worker to be automatically started at postmaster startup. Can we make that happen?\n> \n> A dynamic background worker has to be registered from a regular backend, so\n> it's not entirely clear to me where in startup processing that would take\n> place.  Do you have any good suggestions?\n\nCould you launch it from the startup process, in StartupXLOG()?\nDoes it have to be dynamic?If it's not dynamic, you can't start it from a regular backend can you?  So then you'd need a restart for it to happen?As for launching it from the startup process I don't know, that might be a viable path. The code specifically explains why it's not possible to launch it from the postmaster, but I don't see anything that would make it impossible from the startup process.--  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Sun, 15 Nov 2020 16:51:34 +0100", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 5 Oct 2020, at 13:36, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> \n> I looked at patch v22, and I can see two main issues:\n\nThanks for reviewing!\n\n> 1. The one that Robert talked about earlier: A backend checks the local \"checksums\" state. If it's 'off', it writes a page without checksums. How do you guarantee that the local state doesn't change in between? The implicit assumption seems to be that there MUST NOT be any CHECK_FOR_INTERRUPTS() calls between DataChecksumsNeedWrite() and the write (or read and DataChecksumsNeedVerify()).\n> \n> In most code, the DataChecksumsNeedWrite() call is very close to writing out the page, often in the same critical section. But this is an undocumented assumption.\n\nI've extended the documentation on this.\n\n> The code in sendFile() in basebackup.c seems suspicious in that regard. It calls DataChecksumsNeedVerify() once before starting to read the file. Isn't it possible for the checksums flag to change while it's reading the file and sending it to the client? I hope there are CHECK_FOR_INTERRUPTS() calls buried somewhere in the loop, because it could take minutes to send the whole file.\n\nAgreed, fixed.\n\n> I would feel better if the state transition of the \"checksums\" flag could only happen in a few safe places, or there were some other safeguards for this. I think that's what Andres was trying to say earlier in the thread on ProcSignalBarriers. I'm not sure what the interface to that should be. It could be something like HOLD/RESUME_INTERRUPTS(), where normally all procsignals are handled on CHECK_FOR_INTERRUPTS(), but you could \"hold off\" some if needed. Or something else. Or maybe we can just use HOLD/RESUME_INTERRUPTS() for this. It's more coarse-grained than necessary, but probably doesn't matter in practice.\n> \n> At minimum, there needs to be comments in DataChecksumsNeedWrite() and DataChecksumsNeedVerify(), instructing how to use them safely. Namely, you must ensure that there are no interrupts between the DataChecksumsNeedWrite() and writing out the page, or between reading the page and the DataChecksumsNeedVerify() call. You can achieve that with HOLD_INTERRUPTS() or a critical section, or simply ensuring that there is no substantial code in between that could call CHECK_FOR_INTERRUPTS(). And sendFile() in basebackup.c needs to be fixed.\n> \n> Perhaps you could have \"Assert(InteruptHoldOffCount > 0)\" in DataChecksumsNeedWrite() and DataChecksumsNeedVerify()? There could be other ways that callers could avoid the TOCTOU issue, but it would probably catch most of the unsafe call patterns, and you could always wrap the DataChecksumsNeedWrite/verify() call in a dummy HOLD_INTERRUPTS() block to work around the assertion if you know what you're doing.\n\nThe attached holds off interrupt processing for the NeedWrite and NeedVerify\ncases, and holds them for what I hope is the right duration for the respective\ncallsites.\n\nOne thing I realized in doing this is that the pg_stat_database checksums\nstatistics are set to NULL when checksums are disabled. That makes perfect\nsense when checksum state is static, but not when it can be turned on/off. For\nnow I've made it so that stats are set to zero instead, and will continue\nshowing stats even if checksums gets disabled. Not sure what the best option\nwould be here.\n\n> 2. The signaling between enable_data_checksums() and the launcher process looks funny to me. The general idea seems to be that enable_data_checksums() just starts the launcher process, and the launcher process figures out what it need to do and makes all the changes to the global state. But then there's this violation of the idea: enable_data_checksums() checks DataChecksumsOnInProgress(), and tells the launcher process whether it should continue a previously crashed operation or start from scratch. I think it would be much cleaner if the launcher process figured that out itself, and enable_data_checksums() would just tell the launcher what the target state is.\n> \n> enable_data_checksums() and disable_data_checksums() seem prone to race conditions. If you call enable_data_checksums() in two backends concurrently, depending on the timing, there are two possible outcomes:\n> \n> a) One call returns true, and launches the background process. The other call returns false.\n> \n> b) Both calls return true, but one of them emits a \"NOTICE: data checksums worker is already running\".\n> \n> In disable_data_checksum() imagine what happens if another backend calls enable_data_checksums() in between the ShutdownDatachecksumsWorkerIfRunning() and SetDataChecksumsOff() calls.\n\nI've reworked this in the attached such that the enable_ and disable_ functions\nmerely call into the launcher with the desired outcome, and the launcher is\nresponsible for figuring out the rest. The datachecksumworker is now the sole\nplace which initiates a state transfer.\n\n>> \t\t/*\n>> \t\t * Mark the buffer as dirty and force a full page write. We have to\n>> \t\t * re-write the page to WAL even if the checksum hasn't changed,\n>> \t\t * because if there is a replica it might have a slightly different\n>> \t\t * version of the page with an invalid checksum, caused by unlogged\n>> \t\t * changes (e.g. hintbits) on the master happening while checksums\n>> \t\t * were off. This can happen if there was a valid checksum on the page\n>> \t\t * at one point in the past, so only when checksums are first on, then\n>> \t\t * off, and then turned on again. Iff wal_level is set to \"minimal\",\n>> \t\t * this could be avoided iff the checksum is calculated to be correct.\n>> \t\t */\n>> \t\tSTART_CRIT_SECTION();\n>> \t\tMarkBufferDirty(buf);\n>> \t\tlog_newpage_buffer(buf, false);\n>> \t\tEND_CRIT_SECTION();\n> \n> It's really unfortunate that we have to dirty the page even if the checksum already happens to match. Could we only do the log_newpage_buffer() call and skip MarkBufferDirty() in that case?\n\nI think we can, but I've intentionally stayed away from such optimizations\nuntil the basic version of the patch was deemed safe and approaching done.\nIt's complicated enough as it is IMO.\n\n> Could we get away with a more lightweight WAL record that doesn't contain the full-page image, but just the block number? On replay, the redo routine would read the page from disk.\n\nQuite possibly, but I'm not sure how to reason about such a change to ensure\nit's safety. I would love any ideas you'd have.\n\nThe attached fixes the above plus a few other small things found while hacking\non this version.\n\ncheers ./daniel", "msg_date": "Tue, 17 Nov 2020 09:56:27 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On 17/11/2020 10:56, Daniel Gustafsson wrote:\n>> On 5 Oct 2020, at 13:36, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>> 2. The signaling between enable_data_checksums() and the launcher process looks funny to me. The general idea seems to be that enable_data_checksums() just starts the launcher process, and the launcher process figures out what it need to do and makes all the changes to the global state. But then there's this violation of the idea: enable_data_checksums() checks DataChecksumsOnInProgress(), and tells the launcher process whether it should continue a previously crashed operation or start from scratch. I think it would be much cleaner if the launcher process figured that out itself, and enable_data_checksums() would just tell the launcher what the target state is.\n>>\n>> enable_data_checksums() and disable_data_checksums() seem prone to race conditions. If you call enable_data_checksums() in two backends concurrently, depending on the timing, there are two possible outcomes:\n>>\n>> a) One call returns true, and launches the background process. The other call returns false.\n>>\n>> b) Both calls return true, but one of them emits a \"NOTICE: data checksums worker is already running\".\n>>\n>> In disable_data_checksum() imagine what happens if another backend calls enable_data_checksums() in between the ShutdownDatachecksumsWorkerIfRunning() and SetDataChecksumsOff() calls.\n> \n> I've reworked this in the attached such that the enable_ and disable_ functions\n> merely call into the launcher with the desired outcome, and the launcher is\n> responsible for figuring out the rest. The datachecksumworker is now the sole\n> place which initiates a state transfer.\n\nWell, you still fill the DatachecksumsWorkerShmem->operations array in \nthe backend process that launches the datacheckumworker, not in the \nworker process. I find that still a bit surprising, but I believe it works.\n\n>>> \t\t/*\n>>> \t\t * Mark the buffer as dirty and force a full page write. We have to\n>>> \t\t * re-write the page to WAL even if the checksum hasn't changed,\n>>> \t\t * because if there is a replica it might have a slightly different\n>>> \t\t * version of the page with an invalid checksum, caused by unlogged\n>>> \t\t * changes (e.g. hintbits) on the master happening while checksums\n>>> \t\t * were off. This can happen if there was a valid checksum on the page\n>>> \t\t * at one point in the past, so only when checksums are first on, then\n>>> \t\t * off, and then turned on again. Iff wal_level is set to \"minimal\",\n>>> \t\t * this could be avoided iff the checksum is calculated to be correct.\n>>> \t\t */\n>>> \t\tSTART_CRIT_SECTION();\n>>> \t\tMarkBufferDirty(buf);\n>>> \t\tlog_newpage_buffer(buf, false);\n>>> \t\tEND_CRIT_SECTION();\n>>\n>> It's really unfortunate that we have to dirty the page even if the checksum already happens to match. Could we only do the log_newpage_buffer() call and skip MarkBufferDirty() in that case?\n> \n> I think we can, but I've intentionally stayed away from such optimizations\n> until the basic version of the patch was deemed safe and approaching done.\n> It's complicated enough as it is IMO.\n\nFair enough.\n\n> The attached fixes the above plus a few other small things found while hacking\n> on this version.\n\nI haven't read through the whole patch, but a few random comments below, \nin no particular order:\n\npg_enable/disable_data_checksums() should perform a superuser-check. I \ndon't think we want to expose them to any users.\n\n> +/*\n> + * Local state for Controlfile data_checksum_version. After initialization,\n> + * this is only updated when absorbing a procsignal barrier during interrupt\n> + * processing. Thus, it can be read by backends without the need for a lock.\n> + * Possible values are the checksum versions defined in storage/bufpage.h and\n> + * zero for when checksums are disabled.\n> + */\n> +static uint32 LocalDataChecksumVersion = 0;\n\nThe comment is a bit confusing: \"Thus, it can be read by backends \nwithout the need for a lock\". Since it's a variable in backend-private \nmemory, it can only be read by the same backend, not \"backends\". And \nthat's also why you don't need a lock, not because it's updated during \ninterrupt processing. I understand how this works, but maybe rephrase \nthe comment a bit.\n\n> +/*\n> + * DataChecksumsOnInProgress\n> + * Returns whether data checksums are being enabled\n> + *\n> + * Most callsites shouldn't need to worry about the \"inprogress\" states, since\n> + * they should check the requirement for verification or writing. Some low-\n> + * level callsites dealing with page writes need however to know. It's also\n> + * used to check for aborted checksum processing which need to be restarted.\n> */\n> bool\n> -DataChecksumsEnabled(void)\n> +DataChecksumsOnInProgress(void)\n> +{\n> + return (LocalDataChecksumVersion == PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION);\n> +}\n\ns/need/needs/. The whole paragraph feels a bit awkwardly worded in \ngeneral. I'd suggest something like: \"Most operations don't need to \nworry about the \"inprogress\" states, and should use \nDataChecksumsNeedVerify() or DataChecksumsNeedWrite()\". \nDataChecksumsOffInProgress() is called from \nStartDatachecksumsWorkerLauncher(), which I wouldn't call a \"low-level \ncallsite\".\n\n> @@ -1079,7 +1091,7 @@ XLogInsertRecord(XLogRecData *rdata,\n> \t\tAssert(RedoRecPtr < Insert->RedoRecPtr);\n> \t\tRedoRecPtr = Insert->RedoRecPtr;\n> \t}\n> -\tdoPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites);\n> +\tdoPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites || DataChecksumsOnInProgress());\n> \n> \tif (doPageWrites &&\n> \t\t(!prevDoPageWrites ||\n\nThe comment above this deserves to be updated. Also, this is a very hot \ncodepath; will this slow down WAL-logging, when full-page writes are \ndisabled? Could we inline DataChecksumsOnInProgress() or set \nInsert->forcePageWrites when checksums are being computed or something?\n\nIn StartupXLOG():\n> +\t/*\n> +\t * If data checksums were being disabled when the cluster was shutdown, we\n> +\t * know that we have a state where all backends have stopped validating\n> +\t * checksums and we can move to off instead.\n> +\t */\n> +\tif (ControlFile->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_OFF_VERSION)\n> +\t{\n> +\t\tLWLockAcquire(ControlFileLock, LW_EXCLUSIVE);\n> +\t\tControlFile->data_checksum_version = 0;\n> +\t\tLWLockRelease(ControlFileLock);\n> +\t}\n> +\n\nShould this be WAL-logged, like in SetDataChecksumsOff()?\n\nIn SetDataChecksumsOff():\n> +\tControlFile->data_checksum_version = 0;\n> +\tUpdateControlFile();\n> +\tLWLockRelease(ControlFileLock);\n> +\n> +\tXlogChecksums(0);\n> +\tWaitForProcSignalBarrier(EmitProcSignalBarrier(PROCSIGNAL_BARRIER_CHECKSUM_OFF));\n> +}\n\nWhat happens is if you crash between UpdateControlFile() and XlogChecksum()?\n\n- Heikki\n\n\n", "msg_date": "Mon, 23 Nov 2020 19:36:06 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 23 Nov 2020, at 18:36, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> \n> On 17/11/2020 10:56, Daniel Gustafsson wrote:\n>>> On 5 Oct 2020, at 13:36, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>>> 2. The signaling between enable_data_checksums() and the launcher process looks funny to me. The general idea seems to be that enable_data_checksums() just starts the launcher process, and the launcher process figures out what it need to do and makes all the changes to the global state. But then there's this violation of the idea: enable_data_checksums() checks DataChecksumsOnInProgress(), and tells the launcher process whether it should continue a previously crashed operation or start from scratch. I think it would be much cleaner if the launcher process figured that out itself, and enable_data_checksums() would just tell the launcher what the target state is.\n>>> \n>>> enable_data_checksums() and disable_data_checksums() seem prone to race conditions. If you call enable_data_checksums() in two backends concurrently, depending on the timing, there are two possible outcomes:\n>>> \n>>> a) One call returns true, and launches the background process. The other call returns false.\n>>> \n>>> b) Both calls return true, but one of them emits a \"NOTICE: data checksums worker is already running\".\n>>> \n>>> In disable_data_checksum() imagine what happens if another backend calls enable_data_checksums() in between the ShutdownDatachecksumsWorkerIfRunning() and SetDataChecksumsOff() calls.\n>> I've reworked this in the attached such that the enable_ and disable_ functions\n>> merely call into the launcher with the desired outcome, and the launcher is\n>> responsible for figuring out the rest. The datachecksumworker is now the sole\n>> place which initiates a state transfer.\n> \n> Well, you still fill the DatachecksumsWorkerShmem->operations array in the backend process that launches the datacheckumworker, not in the worker process. I find that still a bit surprising, but I believe it works.\n\nI'm open to changing it in case there are strong opinions, it just seemed the\nmost natural to me.\n\n> pg_enable/disable_data_checksums() should perform a superuser-check. I don't think we want to expose them to any users.\n\nFixed.\n\n>> +/*\n>> + * Local state for Controlfile data_checksum_version. After initialization,\n>> + * this is only updated when absorbing a procsignal barrier during interrupt\n>> + * processing. Thus, it can be read by backends without the need for a lock.\n>> + * Possible values are the checksum versions defined in storage/bufpage.h and\n>> + * zero for when checksums are disabled.\n>> + */\n>> +static uint32 LocalDataChecksumVersion = 0;\n> \n> The comment is a bit confusing: \"Thus, it can be read by backends without the need for a lock\". Since it's a variable in backend-private memory, it can only be read by the same backend, not \"backends\". And that's also why you don't need a lock, not because it's updated during interrupt processing. I understand how this works, but maybe rephrase the comment a bit.\n\nFixed.\n\n>> +/*\n>> + * DataChecksumsOnInProgress\n>> + * Returns whether data checksums are being enabled\n>> + *\n>> + * Most callsites shouldn't need to worry about the \"inprogress\" states, since\n>> + * they should check the requirement for verification or writing. Some low-\n>> + * level callsites dealing with page writes need however to know. It's also\n>> + * used to check for aborted checksum processing which need to be restarted.\n>> */\n>> bool\n>> -DataChecksumsEnabled(void)\n>> +DataChecksumsOnInProgress(void)\n>> +{\n>> + return (LocalDataChecksumVersion == PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION);\n>> +}\n> \n> s/need/needs/. The whole paragraph feels a bit awkwardly worded in general. I'd suggest something like: \"Most operations don't need to worry about the \"inprogress\" states, and should use DataChecksumsNeedVerify() or DataChecksumsNeedWrite()\". DataChecksumsOffInProgress() is called from StartDatachecksumsWorkerLauncher(), which I wouldn't call a \"low-level callsite\".\n\nFixed, and a few related surrounding comments expanded and tweaked.\n\n>> @@ -1079,7 +1091,7 @@ XLogInsertRecord(XLogRecData *rdata,\n>> \t\tAssert(RedoRecPtr < Insert->RedoRecPtr);\n>> \t\tRedoRecPtr = Insert->RedoRecPtr;\n>> \t}\n>> -\tdoPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites);\n>> +\tdoPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites || DataChecksumsOnInProgress());\n>> \tif (doPageWrites &&\n>> \t\t(!prevDoPageWrites ||\n> \n> The comment above this deserves to be updated.\n\nFixed.\n\n> Also, this is a very hot codepath; will this slow down WAL-logging, when full-page writes are disabled? Could we inline DataChecksumsOnInProgress() or set Insert->forcePageWrites when checksums are being computed or something?\n\nWouldn't setting forcePageWrites risk causing other side effects that we don't\nwant here? I've changed DataChecksumsOnInProgress to inline as a start.\n\n> In StartupXLOG():\n>> +\t/*\n>> +\t * If data checksums were being disabled when the cluster was shutdown, we\n>> +\t * know that we have a state where all backends have stopped validating\n>> +\t * checksums and we can move to off instead.\n>> +\t */\n>> +\tif (ControlFile->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_OFF_VERSION)\n>> +\t{\n>> +\t\tLWLockAcquire(ControlFileLock, LW_EXCLUSIVE);\n>> +\t\tControlFile->data_checksum_version = 0;\n>> +\t\tLWLockRelease(ControlFileLock);\n>> +\t}\n>> +\n> \n> Should this be WAL-logged, like in SetDataChecksumsOff()?\n\nMy initial thinking was that we wouldn't need to, as all nodes would process\nthe controlfile equally. The more I think about it the more I think we need to\nhave an XLOG record of it. Added.\n\nIt would be good to stress this in a TAP test, but I haven't been able to write\none yet.\n\n> In SetDataChecksumsOff():\n>> +\tControlFile->data_checksum_version = 0;\n>> +\tUpdateControlFile();\n>> +\tLWLockRelease(ControlFileLock);\n>> +\n>> +\tXlogChecksums(0);\n>> +\tWaitForProcSignalBarrier(EmitProcSignalBarrier(PROCSIGNAL_BARRIER_CHECKSUM_OFF));\n>> +}\n> \n> What happens is if you crash between UpdateControlFile() and XlogChecksum()?\n\nGood point, that would not get the cluster to a consistent state. The\nXlogChecksum should be performed before controlfile is udpated.\n\nThe attached patch contains these fixes as well as a rebase on top of todays\nGit HEAD.\n\ncheers ./daniel", "msg_date": "Wed, 25 Nov 2020 14:20:42 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On 25/11/2020 15:20, Daniel Gustafsson wrote:\n>> On 23 Nov 2020, at 18:36, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>> What happens is if you crash between UpdateControlFile() and XlogChecksum()?\n> \n> Good point, that would not get the cluster to a consistent state. The\n> XlogChecksum should be performed before controlfile is udpated.\n> \n> +void\n> +SetDataChecksumsOff(void)\n> +{\n> +\tLWLockAcquire(ControlFileLock, LW_EXCLUSIVE);\n> +\n> +\tif (ControlFile->data_checksum_version == 0)\n> +\t{\n> +\t\tLWLockRelease(ControlFileLock);\n> +\t\treturn;\n> +\t}\n> +\n> +\tif (ControlFile->data_checksum_version == PG_DATA_CHECKSUM_VERSION)\n> +\t{\n> +\t\tControlFile->data_checksum_version = PG_DATA_CHECKSUM_INPROGRESS_OFF_VERSION;\n> +\t\tUpdateControlFile();\n> +\t\tLWLockRelease(ControlFileLock);\n> +\n> +\t\t/*\n> +\t\t * Update local state in all backends to ensure that any backend in\n> +\t\t * \"on\" state is changed to \"inprogress-off\".\n> +\t\t */\n> +\t\tXlogChecksums(PG_DATA_CHECKSUM_INPROGRESS_OFF_VERSION);\n> +\t\tWaitForProcSignalBarrier(EmitProcSignalBarrier(PROCSIGNAL_BARRIER_CHECKSUM_INPROGRESS_OFF));\n> +\n> +\t\t/*\n> +\t\t * At this point we know that no backends are verifying data checksums\n> +\t\t * during reading. Next, we can safely move to state \"off\" to also\n> +\t\t * stop writing checksums.\n> +\t\t */\n> +\t}\n> +\n> +\tXlogChecksums(0);\n> +\n> +\tLWLockAcquire(ControlFileLock, LW_EXCLUSIVE);\n> +\tControlFile->data_checksum_version = 0;\n> +\tUpdateControlFile();\n> +\tLWLockRelease(ControlFileLock);\n> +\n> +\tWaitForProcSignalBarrier(EmitProcSignalBarrier(PROCSIGNAL_BARRIER_CHECKSUM_OFF));\n> +}\n\nThe lwlocking doesn't look right here. If \nControlFile->data_checksum_version != PG_DATA_CHECKSUM_VERSION, \nLWLockAcquire is called twice without a LWLockRelease in between.\n\nWhat if a checkpoint, and a crash, happens just after the WAL record has \nbeen written, but before the control file is updated? That's a \nridiculously tight window for a whole checkpoint cycle to happen, but in \nprinciple I think that would spell trouble. I think you could set \ndelayChkpt to prevent the checkpoint from happening in that window, \nsimilar to how we avoid this problem with the clog updates at commit. \nAlso, I think this should be in a critical section; we don't want the \nprocess to error out in between for any reason, and if it does happen, \nit's panic time.\n\n- Heikki\n\n\n", "msg_date": "Wed, 25 Nov 2020 15:33:32 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 25 Nov 2020, at 14:33, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n\n> The lwlocking doesn't look right here. If ControlFile->data_checksum_version != PG_DATA_CHECKSUM_VERSION, LWLockAcquire is called twice without a LWLockRelease in between.\n\nRight, fixed.\n\n> What if a checkpoint, and a crash, happens just after the WAL record has been written, but before the control file is updated? That's a ridiculously tight window for a whole checkpoint cycle to happen, but in principle I think that would spell trouble. I think you could set delayChkpt to prevent the checkpoint from happening in that window, similar to how we avoid this problem with the clog updates at commit. Also, I think this should be in a critical section; we don't want the process to error out in between for any reason, and if it does happen, it's panic time.\n\nGood points. The attached patch performs the state changes inside a critical\nsection with checkpoints delayed, as well as emit the barrier inside the\ncritical section while awaiting the barrier outside to keep it open as short as\npossible.\n\nI've also done some tweaks to the tests to make them more robust as well as\ncomment updates and general tidying up here and there.\n\ncheers ./daniel", "msg_date": "Thu, 3 Dec 2020 10:37:58 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 3 Dec 2020, at 10:37, Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> I've also done some tweaks to the tests to make them more robust as well as\n> comment updates and general tidying up here and there.\n\nAttached is a rebase of the patch on top of current HEAD.\n\ncheers ./daniel", "msg_date": "Tue, 5 Jan 2021 00:18:07 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "Hi,\n\nOn Tue, Jan 05, 2021 at 12:18:07AM +0100, Daniel Gustafsson wrote:\n> > On 3 Dec 2020, at 10:37, Daniel Gustafsson <daniel@yesql.se> wrote:\n> > I've also done some tweaks to the tests to make them more robust as well as\n> > comment updates and general tidying up here and there.\n> \n> Attached is a rebase of the patch on top of current HEAD.\n\nI only looked through the documentation this time, and have one\nsuggestion:\n \n> diff --git a/doc/src/sgml/ref/initdb.sgml b/doc/src/sgml/ref/initdb.sgml\n> index 385ac25150..e3b0048806 100644\n> --- a/doc/src/sgml/ref/initdb.sgml\n> +++ b/doc/src/sgml/ref/initdb.sgml\n> @@ -219,6 +219,7 @@ PostgreSQL documentation\n> failures will be reported in the\n> <link linkend=\"monitoring-pg-stat-database-view\">\n> <structname>pg_stat_database</structname></link> view.\n> + See <xref linkend=\"checksums\" /> for details.\n> </para>\n> </listitem>\n> </varlistentry>\n\n> diff --git a/doc/src/sgml/wal.sgml b/doc/src/sgml/wal.sgml\n> index f4bc147b10..5dcfcdd2ff 100644\n> --- a/doc/src/sgml/wal.sgml\n> +++ b/doc/src/sgml/wal.sgml\n> @@ -230,6 +230,103 @@\n> </para>\n> </sect1>\n> \n> + <sect1 id=\"checksums\">\n> + <title>Data Checksums</title>\n> + <indexterm>\n> + <primary>checksums</primary>\n> + </indexterm>\n> +\n> + <para>\n> + Data pages are not checksum protected by default, but this can optionally be\n> + enabled for a cluster. When enabled, each data page will be assigned a\n> + checksum that is updated when the page is written and verified every time\n> + the page is read. Only data pages are protected by checksums, internal data\n> + structures and temporary files are not.\n> + </para>\n> +\n> + <para>\n> + Checksums are normally enabled when the cluster is initialized using <link\n> + linkend=\"app-initdb-data-checksums\"><application>initdb</application></link>.\n> + They can also be enabled or disabled at a later time, either as an offline\n> + operation or in a running cluster. In all cases, checksums are enabled or\n> + disabled at the full cluster level, and cannot be specified individually for\n> + databases or tables.\n> + </para>\n> +\n> + <para>\n> + The current state of checksums in the cluster can be verified by viewing the\n> + value of the read-only configuration variable <xref\n> + linkend=\"guc-data-checksums\" /> by issuing the command <command>SHOW\n> + data_checksums</command>.\n> + </para>\n> +\n> + <para>\n> + When attempting to recover from corrupt data it may be necessary to bypass\n> + the checksum protection in order to recover data. To do this, temporarily\n> + set the configuration parameter <xref linkend=\"guc-ignore-checksum-failure\" />.\n> + </para>\n\nI think the above is rather informative about checksums in general and\nnot specific to online activation of checksusm, so could pretty much be\ncommitted verbatim right now, except for the \"either as an offline\noperation or in a running cluster\" bit which would have to be rewritten.\n\n> +\n> + <sect2 id=\"checksums-offline-enable-disable\">\n> + <title>Off-line Enabling of Checksums</title>\n> +\n> + <para>\n> + The <link linkend=\"app-pgchecksums\"><application>pg_checksums</application></link>\n> + application can be used to enable or disable data checksums, as well as \n> + verify checksums, on an offline cluster.\n> + </para>\n> +\n> + </sect2>\n> + </sect1>\n> +\n> <sect1 id=\"wal-intro\">\n> <title>Write-Ahead Logging (<acronym>WAL</acronym>)</title>\n\nThis as well.\n\n\nMichael\n\n-- \nMichael Banck\nProjektleiter / Senior Berater\nTel.: +49 2166 9901-171\nFax: +49 2166 9901-100\nEmail: michael.banck@credativ.de\n\ncredativ GmbH, HRB M�nchengladbach 12080\nUSt-ID-Nummer: DE204566209\nTrompeterallee 108, 41189 M�nchengladbach\nGesch�ftsf�hrung: Dr. Michael Meskes, J�rg Folz, Sascha Heuer\n\nUnser Umgang mit personenbezogenen Daten unterliegt\nfolgenden Bestimmungen: https://www.credativ.de/datenschutz\n\n\n", "msg_date": "Tue, 5 Jan 2021 18:19:31 +0100", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "Hi,\n\nOn Tue, Jan 05, 2021 at 12:18:07AM +0100, Daniel Gustafsson wrote:\n> Attached is a rebase of the patch on top of current HEAD.\n> \n> cheers ./daniel\n\nSome more comments/questions:\n\n> diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c\n> index 53e997cd55..06c001f8ff 100644\n> --- a/src/backend/access/heap/heapam.c\n> +++ b/src/backend/access/heap/heapam.c\n> @@ -7284,7 +7284,7 @@ log_heap_freeze(Relation reln, Buffer buffer, TransactionId cutoff_xid,\n> * and dirtied.\n> *\n> * If checksums are enabled, we also generate a full-page image of\n> - * heap_buffer, if necessary.\n> + * heap_buffer.\n\nThat sounds like it has nothing to do with online (de)activation of\nchecksums?\n\n> */\n> XLogRecPtr\n> log_heap_visible(RelFileNode rnode, Buffer heap_buffer, Buffer vm_buffer,\n> @@ -7305,11 +7305,13 @@ log_heap_visible(RelFileNode rnode, Buffer heap_buffer, Buffer vm_buffer,\n> \tXLogRegisterBuffer(0, vm_buffer, 0);\n> \n> \tflags = REGBUF_STANDARD;\n> +\tHOLD_INTERRUPTS();\n> \tif (!XLogHintBitIsNeeded())\n> \t\tflags |= REGBUF_NO_IMAGE;\n> \tXLogRegisterBuffer(1, heap_buffer, flags);\n> \n> \trecptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_VISIBLE);\n> +\tRESUME_INTERRUPTS();\n\nThis could maybe do with a comment on why the HOLD/RESUME_INTERRUPTS()\nis required here, similar as is done in bufpage.c further down.\n \n> diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c\n> index 92cc7ea073..fa074c6046 100644\n> --- a/src/backend/access/rmgrdesc/xlogdesc.c\n> +++ b/src/backend/access/rmgrdesc/xlogdesc.c\n> @@ -18,6 +18,7 @@\n> #include \"access/xlog.h\"\n> #include \"access/xlog_internal.h\"\n> #include \"catalog/pg_control.h\"\n> +#include \"storage/bufpage.h\"\n> #include \"utils/guc.h\"\n> #include \"utils/timestamp.h\"\n> \n> @@ -140,6 +141,20 @@ xlog_desc(StringInfo buf, XLogReaderState *record)\n> \t\t\t\t\t\t xlrec.ThisTimeLineID, xlrec.PrevTimeLineID,\n> \t\t\t\t\t\t timestamptz_to_str(xlrec.end_time));\n> \t}\n> +\telse if (info == XLOG_CHECKSUMS)\n> +\t{\n> +\t\txl_checksum_state xlrec;\n> +\n> +\t\tmemcpy(&xlrec, rec, sizeof(xl_checksum_state));\n> +\t\tif (xlrec.new_checksumtype == PG_DATA_CHECKSUM_VERSION)\n> +\t\t\tappendStringInfo(buf, \"on\");\n> +\t\telse if (xlrec.new_checksumtype == PG_DATA_CHECKSUM_INPROGRESS_OFF_VERSION)\n> +\t\t\tappendStringInfo(buf, \"inprogress-off\");\n> +\t\telse if (xlrec.new_checksumtype == PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION)\n> +\t\t\tappendStringInfo(buf, \"inprogress-on\");\n> +\t\telse\n> +\t\t\tappendStringInfo(buf, \"off\");\n\nWe probably discussed this earlier, but what was the conclusion?\nPG_DATA_CHECKSUM_VERSION = 1 sounds like somebody thought it a good idea\nto not just have a bool here but they probably rather thought about\ndifferent checkumming/hashing algorithms/implentations than about\ninternal state of the checksumming machinery.\n\nIf we decide on v2 of data page checksums, how would that look like?\n\nPG_DATA_CHECKSUM_VERSION_V2 = 4?\n\nIf we think we're done with versions, did we consider removing the\nVERSION here, because it is really confusing in\nPG_DATA_CHECKSUM_INPROGRESS_ON/OFF_VERSION, like\nPG_DATA_CHECKSUM_STATE_ON/INPROGRESS_ON/OFF? Or would removing \"version\"\nalso from pg_controldata be a backwards-incompatible change we don't\nwant to do?\n\nSorry again, I think we discussed it earlier, but maybe at least some\ncomments about what VERSION is supposed to be/mean in bufpage.h would be\nin order: \n\n> --- a/src/include/storage/bufpage.h\n> +++ b/src/include/storage/bufpage.h\n> @@ -198,6 +198,9 @@ typedef PageHeaderData *PageHeader;\n> */\n> #define PG_PAGE_LAYOUT_VERSION\t\t4\n> #define PG_DATA_CHECKSUM_VERSION\t1\n> +#define PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION\t\t2\n> +#define PG_DATA_CHECKSUM_INPROGRESS_OFF_VERSION\t\t3\n> +\n\n> diff --git a/src/backend/access/transam/xlog.c b/src/backend/access/transam/xlog.c\n> index ede93ad7fd..01eca900ac 100644\n> --- a/src/backend/access/transam/xlog.c\n> +++ b/src/backend/access/transam/xlog.c\n> @@ -1089,7 +1102,7 @@ XLogInsertRecord(XLogRecData *rdata,\n> \t\tAssert(RedoRecPtr < Insert->RedoRecPtr);\n> \t\tRedoRecPtr = Insert->RedoRecPtr;\n> \t}\n> -\tdoPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites);\n> +\tdoPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites || DataChecksumsOnInProgress());\n\nIndent, but I guess this will be indented by pg_indent after the fact\nandyway? Or is this how it's supposed to look?\n \n> @@ -4938,13 +4949,299 @@ GetMockAuthenticationNonce(void)\n> }\n> \n> /*\n> - * Are checksums enabled for data pages?\n> + * DataChecksumsNeedWrite\n> + *\t\tReturns whether data checksums must be written or not\n> + *\n> + * Are checksums enabled, or in the process of being enabled, for data pages?\n\nThe second \",\" looks odd and could be ommitted?.\n\n> + * DataChecksumsNeedVerify\n> + *\t\tReturns whether data checksums must be verified or not\n> + *\n> + * Data checksums are only verified if they are fully enabled in the cluster.\n> + * During the \"inprogress-on\" and \"inprogress-off\" states they are only\n> + * updated, not verified.\n> + *\n> + * This function is intended for callsites which have read data and are about\n> + * to perform checksum validation based on the result of this. To avoid the\n> + * the risk of the checksum state changing between reading and performing the\n> + * validation (or not), interrupts must be held off. This implies that calling\n> + * this function must be performed as close to the validation call as possible\n> + * to keep the critical section short. This is in order to protect against\n> + * TOCTOU situations around checksum validation.\n\nI had to google \"TOCTOU\" and this acronym doesn't appear elsewhere in\nthe source tree, so I suggest to spell it out at least here (there's one\nmore occurance of it in this patch)\n\n> + * DataChecksumsOnInProgress\n> + *\t\tReturns whether data checksums are being enabled\n> + *\n> + * Most operations don't need to worry about the \"inprogress\" states, and\n> + * should use DataChecksumsNeedVerify() or DataChecksumsNeedWrite(). The\n> + * \"inprogress\" state for enabling checksums is used when the checksum worker\n> + * is setting checksums on all pages, it can thus be used to check for aborted\n> + * checksum processing which need to be restarted.\n\nThe first \"inprogress\" looks legit as it talks about both states, but\nthe second one should be \"inprogress-on\" I think and ...\n\n> + * DataChecksumsOffInProgress\n> + *\t\tReturns whether data checksums are being disabled\n> + *\n> + * The \"inprogress\" state for disabling checksums is used for when the worker\n> + * resets the catalog state. Operations should use DataChecksumsNeedVerify()\n> + * or DataChecksumsNeedWrite() for deciding whether to read/write checksums.\n\n... \"inprogress-off\" here.\n\n> +void\n> +AbsorbChecksumsOnInProgressBarrier(void)\n> +{\n> + Assert(LocalDataChecksumVersion == 0 || LocalDataChecksumVersion == PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION);\n> + LocalDataChecksumVersion = PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION;\n> +}\n\nBikeshed alert: maybe alo those Absorb*Barrier functions could be lumped\ntogether after the SetDataChecksums*() functions. If not, a function\ncomment would be in order.\n\n> +void\n> +SetDataChecksumsOnInProgress(void)\n> +{\n> +\tuint64\t\tbarrier;\n> +\n> +\tAssert(ControlFile != NULL);\n> +\n> +\tLWLockAcquire(ControlFileLock, LW_EXCLUSIVE);\n> +\n> +\tif (ControlFile->data_checksum_version != 0)\n> +\t{\n> +\t\tLWLockRelease(ControlFileLock);\n> +\t\treturn;\n> +\t}\n> +\tLWLockRelease(ControlFileLock);\n> +\n> +\tMyProc->delayChkpt = true;\n> +\tSTART_CRIT_SECTION();\n> +\n> +\tXlogChecksums(PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION);\n> +\n> +\tLWLockAcquire(ControlFileLock, LW_EXCLUSIVE);\n> +\tControlFile->data_checksum_version = PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION;\n> +\tUpdateControlFile();\n> +\tLWLockRelease(ControlFileLock);\n> +\n> +\tbarrier = EmitProcSignalBarrier(PROCSIGNAL_BARRIER_CHECKSUM_INPROGRESS_ON);\n> +\n> +\tEND_CRIT_SECTION();\n> +\tMyProc->delayChkpt = false;\n> +\n> +\tWaitForProcSignalBarrier(barrier);\n> +}\n\nThis function doesn't have the customary function header comment nor any\ncomments in the body and it looks like it's doing some pretty important\nstuff, so I think some comments would be in order, e.g.\nexplaining that \"data_checksum_version != 0\" means we've already got\nchecksums enabled or are in the process of enabling/disabling them.\n\nThe corresponding SetDataChecksumsOff() function has comments that could\nbe duplicated here. If anything, it could be moved below\nSetDataChecksumsOff() so that the reader potentially already went\nthrough the comments in the other similar functions.\n \n> +/*\n> + * SetDataChecksumsOn\n> + *\t\tEnables data checksums cluster-wide\n> + *\n> + * Enabling data checksums is performed using two barriers, the first one\n> + * sets the checksums state to \"inprogress-on\" and the second one to \"on\".\n> + * During \"inprogress-on\", checksums are written but not verified. When all\n> + * existing pages are guaranteed to have checksums, and all new pages will be\n> + * initiated with checksums, the state can be changed to \"on\".\n\nThis should proabably go above SetDataChecksumsOnInProgress() because\neven though I've just reviewed this, I looked at the following function\nbody and wondered where the second barrier went...\n\n> + */\n> +void\n> +SetDataChecksumsOn(void)\n> {\n> +\tuint64\t\tbarrier;\n> +\n> \tAssert(ControlFile != NULL);\n> -\treturn (ControlFile->data_checksum_version > 0);\n> +\n> +\tLWLockAcquire(ControlFileLock, LW_EXCLUSIVE);\n> +\n> +\tif (ControlFile->data_checksum_version != PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION)\n> +\t{\n> +\t\tLWLockRelease(ControlFileLock);\n> +\t\telog(ERROR, \"checksums not in \\\"inprogress-on\\\" mode\");\n> +\t}\n> +\n> +\tLWLockRelease(ControlFileLock);\n> +\n> +\tMyProc->delayChkpt = true;\n> +\tSTART_CRIT_SECTION();\n> +\n> +\tXlogChecksums(PG_DATA_CHECKSUM_VERSION);\n> +\n> +\tLWLockAcquire(ControlFileLock, LW_EXCLUSIVE);\n> +\tControlFile->data_checksum_version = PG_DATA_CHECKSUM_VERSION;\n> +\tUpdateControlFile();\n> +\tLWLockRelease(ControlFileLock);\n> +\n> +\tbarrier = EmitProcSignalBarrier(PROCSIGNAL_BARRIER_CHECKSUM_ON);\n> +\n> +\tEND_CRIT_SECTION();\n> +\tMyProc->delayChkpt = false;\n> +\n> +\tWaitForProcSignalBarrier(barrier);\n> +}\n> +\n> + * SetDataChecksumsOff\n> + *\t\tDisables data checksums cluster-wide\n> + *\n> + * Disabling data checksums must be performed with two sets of barriers, each\n> + * carrying a different state. The state is first set to \"inprogress-off\"\n> + * during which checksums are still written but not verified. This ensures that\n> + * backends which have yet to observe the state change from \"on\" won't get\n> + * validation errors on concurrently modified pages. Once all backends have\n> + * changed to \"inprogress-off\", the barrier for moving to \"off\" can be\n> + * emitted.\n> + */\n> +void\n> +SetDataChecksumsOff(void)\n> +{\n> +\tuint64\t\tbarrier;\n> +\n> +\tAssert(ControlFile);\n> +\n> +\tLWLockAcquire(ControlFileLock, LW_EXCLUSIVE);\n> +\n> +\t/* If data checksums are already disabled there is nothing to do */\n> +\tif (ControlFile->data_checksum_version == 0)\n> +\t{\n> +\t\tLWLockRelease(ControlFileLock);\n> +\t\treturn;\n> +\t}\n> +\n> +\t/*\n> +\t * If data checksums are currently enabled we first transition to the\n> +\t * inprogress-off state during which backends continue to write checksums\n\nThe inprogress-off is in \" \" everywhere else.\n\n> +\t * without verifying them. When all backends are in \"inprogress-off\" the\n> +\t * next transition to \"off\" can be performed, after which all data checksum\n> +\t * processing is disabled.\n> +\t */\n> +\tif (ControlFile->data_checksum_version == PG_DATA_CHECKSUM_VERSION)\n> +\t{\n> +\t\tLWLockRelease(ControlFileLock);\n> +\n> +\t\tMyProc->delayChkpt = true;\n> +\t\tSTART_CRIT_SECTION();\n> +\n> +\t\tXlogChecksums(PG_DATA_CHECKSUM_INPROGRESS_OFF_VERSION);\n> +\n> +\t\tLWLockAcquire(ControlFileLock, LW_EXCLUSIVE);\n> +\t\tControlFile->data_checksum_version = PG_DATA_CHECKSUM_INPROGRESS_OFF_VERSION;\n> +\t\tUpdateControlFile();\n> +\t\tLWLockRelease(ControlFileLock);\n> +\n> +\t\tbarrier = EmitProcSignalBarrier(PROCSIGNAL_BARRIER_CHECKSUM_INPROGRESS_OFF);\n> +\n> +\t\tEND_CRIT_SECTION();\n> +\t\tMyProc->delayChkpt = false;\n> +\n> +\t\t/*\n> +\t\t * Update local state in all backends to ensure that any backend in\n> +\t\t * \"on\" state is changed to \"inprogress-off\".\n> +\t\t */\n> +\t\tWaitForProcSignalBarrier(barrier);\n> +\n> +\t\t/*\n> +\t\t * At this point we know that no backends are verifying data checksums\n> +\t\t * during reading. Next, we can safely move to state \"off\" to also\n> +\t\t * stop writing checksums.\n> +\t\t */\n> +\t}\n> +\telse\n> +\t{\n> +\t\t/*\n> +\t\t * Ending up here implies that the checksums state is \"inprogress-on\"\n> +\t\t * and we can transition directly to \"off\" from there.\n\nCan you explain that a bit more? Is \"inprogress-on\" a typo for\n\"inprogress-off\", or do you really mean that we can just switch off\nchecksums during \"inprogress-on\"? If so, the rationale should be\nexplained a bit more.\n\n> @@ -7929,6 +8226,32 @@ StartupXLOG(void)\n> \t */\n> \tCompleteCommitTsInitialization();\n> \n> +\t/*\n> +\t * If we reach this point with checksums in progress state (either being\n> +\t * enabled or being disabled), we notify the user that they need to\n> +\t * manually restart the process to enable checksums. This is because we\n\nI think this could rephrased to \"If we reach this point with checksums\nbeing enabled, we notify...\" because the disable case is different and\nhandled in the following block.\n\n> +\t * cannot launch a dynamic background worker directly from here, it has to\n> +\t * be launched from a regular backend.\n> +\t */\n> +\tif (ControlFile->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION)\n> +\t\tereport(WARNING,\n> +\t\t\t\t(errmsg(\"data checksums are being enabled, but no worker is running\"),\n> +\t\t\t\t errhint(\"Either disable or enable data checksums by calling the pg_disable_data_checksums() or pg_enable_data_checksums() functions.\")));\n> +\n> +\t/*\n> +\t * If data checksums were being disabled when the cluster was shutdown, we\n> +\t * know that we have a state where all backends have stopped validating\n> +\t * checksums and we can move to off instead.\n> +\t */\n> +\tif (ControlFile->data_checksum_version == PG_DATA_CHECKSUM_INPROGRESS_OFF_VERSION)\n> +\t{\n> +\t\tXlogChecksums(0);\n> +\n> +\t\tLWLockAcquire(ControlFileLock, LW_EXCLUSIVE);\n> +\t\tControlFile->data_checksum_version = 0;\n> +\t\tLWLockRelease(ControlFileLock);\n> +\t}\n> +\n> \t/*\n> \t * All done with end-of-recovery actions.\n> \t *\n \n> index 21f2240ade..a5e715f19c 100644\n> --- a/src/backend/catalog/heap.c\n> +++ b/src/backend/catalog/heap.c\n> @@ -965,10 +965,13 @@ InsertPgClassTuple(Relation pg_class_desc,\n> \t/* relpartbound is set by updating this tuple, if necessary */\n> \tnulls[Anum_pg_class_relpartbound - 1] = true;\n> \n> +\tHOLD_INTERRUPTS();\n> +\tvalues[Anum_pg_class_relhaschecksums - 1] = BoolGetDatum(DataChecksumsNeedWrite());\n> \ttup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);\n> \n> \t/* finally insert the new tuple, update the indexes, and clean up */\n> \tCatalogTupleInsert(pg_class_desc, tup);\n> +\tRESUME_INTERRUPTS();\n> \n> \theap_freetuple(tup);\n\nMaybe add a comment here why we now HOLD/RESUME_INTERRUPTS.\n\n> diff --git a/src/backend/postmaster/datachecksumsworker.c b/src/backend/postmaster/datachecksumsworker.c\n> new file mode 100644\n> index 0000000000..5d94db95f9\n> --- /dev/null\n> +++ b/src/backend/postmaster/datachecksumsworker.c\n> @@ -0,0 +1,1527 @@\n> +/*-------------------------------------------------------------------------\n> + *\n> + * datachecksumsworker.c\n> + *\t Background worker for enabling or disabling data checksums online\n> + *\n> + * When enabling data checksums on a database at initdb time or with\n> + * pg_checksums, no extra process is required as each page is checksummed, and\n> + * verified, when accessed. When enabling checksums on an already running\n> + * cluster, which does not run with checksums enabled, this worker will ensure\n> + * that all pages are checksummed before verification of the checksums is\n> + * turned on. In the case of disabling checksums, the state transition is\n> + * recorded in the catalog and control file, and no changes are performed\n> + * on the data pages or in the catalog.\n> + *\n> + * Checksums can be either enabled or disabled cluster-wide, with on/off being\n> + * the end state for data_checksums.\n> + *\n> + * Enabling checksums\n> + * ------------------\n> + * When enabling checksums in an online cluster, data_checksums will be set to\n> + * \"inprogress-on\" which signals that write operations MUST compute and write\n> + * the checksum on the data page, but during reading the checksum SHALL NOT be\n> + * verified. This ensures that all objects created during checksumming will\n> + * have checksums set, but no reads will fail due to incorrect checksum. The\n> + * DataChecksumsWorker will compile a list of databases which exist at the\n> + * start of checksumming, and all of these which haven't been dropped during\n> + * the processing MUST have been processed successfully in order for checksums\n> + * to be enabled. Any new relation created during processing will see the\n> + * in-progress state and will automatically be checksummed as well as have its\n> + * state recorded in the catalog to avoid the datachecksumsworker having to\n> + * process it when already checksummed.\n> + *\n> + * For each database, all relations which have storage are read and every data\n> + * page is marked dirty to force a write with the checksum. This will generate\n> + * a lot of WAL as the entire database is read and written. Once all datapages\n\nIt's \"data page\" with a space in between everywhere else.\n\n> + * Synchronization and Correctness\n> + * -------------------------------\n> + * The processes involved in enabling, or disabling, data checksums in an\n> + * online cluster must be properly synchronized with the normal backends\n> + * serving concurrent queries to ensure correctness. Correctness is defined\n> + * as the following:\n> + *\n> + *\t\t- Backends SHALL NOT violate local datachecksum state\n> + *\t\t- Data checksums SHALL NOT be considered enabled cluster-wide until all\n\nLinewrap.\n\n> + *\t\t currently connected backends have the local state \"enabled\"\n\n> + * Synchronizing the state change is done with procsignal barriers, where the\n> + * backend updating the global state in the controlfile will wait for all other\n> + * backends to absorb the barrier before WAL logging. Barrier absorption will\n> + * happen during interrupt processing, which means that connected backends will\n> + * change state at different times.\n> + *\n> + * When Enabling Data Checksums\n> + *\t ----------------------------\n\nThere's something off with the indentation of either the title or the\nline seperator here.\n\n> + *\t A process which fails to observe data checksums being enabled can induce\n> + *\t two types of errors: failing to write the checksum when modifying the page\n> + *\t and failing to validate the data checksum on the page when reading it.\n> + *\n> + * When the DataChecksumsWorker has finished writing checksums on all pages\n> + * and enable data checksums cluster-wide, there are three sets of backends:\n\n\"enables\"\n\n> + * Bg: Backend updating the global state and emitting the procsignalbarrier\n> + * Bd: Backends on \"off\" state\n\ns/on/in/\n\nAlso, given that \"When the DataChecksumsWorker has finished writing\nchecksums on all pages and enable[s] data checksums cluster-wide\",\nshouldn't that mean that all other backends are either in \"on\" or\n\"inprogress-on\" state, because the Bd -> Bi transition happened during a\nprevious barrier? Maybe that should be first explained?\n\n> + * Be: Backends in \"on\" state\n> + * Bi: Backends in \"inprogress-on\" state\n> + *\n> + * Backends transition from the Bd state to Be like so: Bd -> Bi -> Be\n> + *\n> + * Backends in Bi and Be will write checksums when modifying a page, but only\n> + * backends in Be will verify the checksum during reading. The Bg backend is\n> + * blocked waiting for all backends in Bi to process interrupts and move to\n> + * Be. Any backend starting will observe the global state being \"on\" and will\n\n\"Any backend starting while Bg is waiting for the barrier\" right?\n\n> + * All sets are compatible while still operating based on\n> + * their local state.\n\nWhoa, you lost me there.\n\n> + *\t When Disabling Data Checksums\n> + *\t -----------------------------\n> + *\t A process which fails to observe data checksums being disabled can induce\n> + *\t two types of errors: writing the checksum when modifying the page and\n\nCan you rephrase what you mean with \"being disabled\"? If you mean we're\nin the \"inprogress-off\" state, then why is that an error? Do you mean\n\"writing *no* checksum\" because AIUI we should still write checksums at\nthis point? Or are you talking about a different state?\n\n> + *\t validating a data checksum which is no longer correct due to modifications\n> + *\t to the page.\n> + *\n> + * Bg: Backend updating the global state and emitting the procsignalbarrier\n> + * Bd: Backands in \"off\" state\n\ns/Backands/Backends/\n\n> + * Be: Backends in \"on\" state\n> + * Bi: Backends in \"inprogress-off\" state\n\nI suggest using a different symbol here for \"inprogress-off\" in order\nnot to confuse the two (different right?) Bi.\n\n> + * Backends transition from the Be state to Bd like so: Be -> Bi -> Bd\n> + *\n> + * The goal is to transition all backends to Bd making the others empty sets.\n> + * Backends in Bi writes data checksums, but don't validate them, such that\n\ns/writes/write/\n\n> + * backends still in Be can continue to validate pages until the barrier has\n> + * been absorbed such that they are in Bi. Once all backends are in Bi, the\n> + * barrier to transition to \"off\" can be raised and all backends can safely\n> + * stop writing data checksums as no backend is enforcing data checksum\n> + * validation.\n\n... \"anymore\" maybe.\n\n> + * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group\n\nCopyright year bump, there's two other occurances.\n\n> + * IDENTIFICATION\n> + *\t src/backend/postmaster/datachecksumsworker.c\n> + *\n> + *-------------------------------------------------------------------------\n> + */\n> +#include \"postgres.h\"\n> +\n> +#include \"access/genam.h\"\n> +#include \"access/heapam.h\"\n> +#include \"access/htup_details.h\"\n> +#include \"access/xact.h\"\n> +#include \"catalog/indexing.h\"\n> +#include \"catalog/pg_class.h\"\n> +#include \"catalog/pg_database.h\"\n> +#include \"commands/vacuum.h\"\n> +#include \"common/relpath.h\"\n> +#include \"miscadmin.h\"\n> +#include \"pgstat.h\"\n> +#include \"postmaster/bgworker.h\"\n> +#include \"postmaster/bgwriter.h\"\n> +#include \"postmaster/datachecksumsworker.h\"\n> +#include \"storage/bufmgr.h\"\n> +#include \"storage/checksum.h\"\n> +#include \"storage/lmgr.h\"\n> +#include \"storage/ipc.h\"\n> +#include \"storage/procarray.h\"\n> +#include \"storage/smgr.h\"\n> +#include \"tcop/tcopprot.h\"\n> +#include \"utils/fmgroids.h\"\n> +#include \"utils/lsyscache.h\"\n> +#include \"utils/ps_status.h\"\n> +#include \"utils/syscache.h\"\n> +\n> +#define DATACHECKSUMSWORKER_MAX_DB_RETRIES 5\n> +\n> +#define MAX_OPS 4\n> +\n> +typedef enum DataChecksumOperation\n> +{\n> +\tENABLE_CHECKSUMS = 1,\n> +\tDISABLE_CHECKSUMS,\n> +\tRESET_STATE,\n> +\tSET_INPROGRESS_ON,\n> +\tSET_CHECKSUMS_ON\n> +}\t\t\tDataChecksumOperation;\n> +\n> +typedef enum\n> +{\n> +\tDATACHECKSUMSWORKER_SUCCESSFUL = 0,\n> +\tDATACHECKSUMSWORKER_ABORTED,\n> +\tDATACHECKSUMSWORKER_FAILED,\n> +\tDATACHECKSUMSWORKER_RETRYDB,\n> +}\t\t\tDatachecksumsWorkerResult;\n> +\n> +typedef struct DatachecksumsWorkerShmemStruct\n> +{\n> +\t/*\n> +\t * Access to launcher_started and abort must be protected by\n> +\t * DatachecksumsWorkerLock.\n> +\t */\n> +\tbool\t\tlauncher_started;\n> +\tbool\t\tabort;\n> +\n> +\t/*\n> +\t * Variables for the worker to signal the launcher, or subsequent workers\n> +\t * in other databases. As there is only a single worker, and the launcher\n> +\t * won't read these until the worker exits, they can be accessed without\n> +\t * the need for a lock. If multiple workers are supported then this will\n> +\t * have to be revisited.\n> +\t */\n> +\tDatachecksumsWorkerResult success;\n> +\tbool\t\tprocess_shared_catalogs;\n> +\n> +\t/*\n> +\t * The below members are set when the launcher starts, and are only\n> +\t * accessed read-only by the single worker. Thus, we can access these\n> +\t * without a lock. If multiple workers, or dynamic cost parameters, are\n> +\t * supported at some point then this would need to be revisited.\n> +\t */\n> +\tint\t\t\tcost_delay;\n> +\tint\t\t\tcost_limit;\n> +\tint\t\t\toperations[MAX_OPS];\n> +\tbool\t\ttarget;\n\nThis \"target\" bool isn't documented very well (at least here). AIUI,\nit's true if we enable checksums and false if we disable them?\n\n> +}\t\t\tDatachecksumsWorkerShmemStruct;\n> +\n> +/* Shared memory segment for datachecksumsworker */\n> +static DatachecksumsWorkerShmemStruct * DatachecksumsWorkerShmem;\n> +\n> +/* Bookkeeping for work to do */\n> +typedef struct DatachecksumsWorkerDatabase\n> +{\n> +\tOid\t\t\tdboid;\n> +\tchar\t *dbname;\n> +}\t\t\tDatachecksumsWorkerDatabase;\n> +\n> +typedef struct DatachecksumsWorkerResultEntry\n> +{\n> +\tOid\t\t\tdboid;\n> +\tDatachecksumsWorkerResult result;\n> +\tint\t\t\tretries;\n> +}\t\t\tDatachecksumsWorkerResultEntry;\n> +\n> +\n> +/* Prototypes */\n> +static List *BuildDatabaseList(void);\n> +static List *BuildRelationList(bool temp_relations, bool include_shared);\n> +static DatachecksumsWorkerResult ProcessDatabase(DatachecksumsWorkerDatabase *db, const char *bgw_func_name);\n> +static bool ProcessAllDatabases(bool *already_connected, const char *bgw_func_name);\n> +static bool ProcessSingleRelationFork(Relation reln, ForkNumber forkNum, BufferAccessStrategy strategy);\n> +static void launcher_cancel_handler(SIGNAL_ARGS);\n> +static void SetRelHasChecksums(Oid relOid);\n> +static void WaitForAllTransactionsToFinish(void);\n> +\n> +/*\n> + * DataChecksumsWorkerStarted\n> + *\t\t\tInformational function to query the state of the worker\n> + */\n> +bool\n> +DataChecksumsWorkerStarted(void)\n> +{\n> +\tbool\t\tstarted;\n> +\n> +\tLWLockAcquire(DatachecksumsWorkerLock, LW_EXCLUSIVE);\n> +\tstarted = DatachecksumsWorkerShmem->launcher_started && !DatachecksumsWorkerShmem->abort;\n> +\tLWLockRelease(DatachecksumsWorkerLock);\n> +\n> +\treturn started;\n> +}\n> +\n> +\n> +/*\n> + * StartDataChecksumsWorkerLauncher\n> + *\t\tMain entry point for datachecksumsworker launcher process\n> + *\n> + * The main entrypoint for starting data checksums processing for enabling as\n> + * well as disabling.\n> + */\n> +void\n> +StartDatachecksumsWorkerLauncher(bool enable_checksums, int cost_delay, int cost_limit)\n\nAfter reading through the function I find this 'bool enable_checksums'\na bit confusing, I think something like 'int operation' and then\ncomparing it to either ENABLE or DISABLE or whatever would make the code\nmore readable, but it's a minor nitpick.\n\n> +{\n> +\tBackgroundWorker bgw;\n> +\tBackgroundWorkerHandle *bgw_handle;\n> +\n> +\t/*\n> +\t * Given that any backend can initiate a data checksum operation, the\n> +\t * launcher can at this point be in one of the below distinct states:\n> +\t *\n> +\t * A: Started and performing an operation; B: Started and in the\n> +\t * process of aborting; C: Not started\n> +\t *\n> +\t * If the launcher is in state A, and the requested target state is equal\n> +\t * to the currently performed operation then we can return immediately.\n> +\t * This can happen if two users enable checksums simultaneously. If the\n> +\t * requested target is to disable checksums while they are being enabled,\n> +\t * we must abort the current processing. This can happen if a user\n> +\t * enables data checksums and then, before checksumming is done, disables\n> +\t * data checksums again.\n> +\t *\n> +\t * If the launcher is in state B, we need to wait for processing to end\n> +\t * and the abort flag be cleared before we can restart with the requested\n> +\t * operation. Here we will exit immediately and leave it to the user to\n> +\t * restart processing at a later time.\n> +\t *\n> +\t * If the launcher is in state C we can start performing the requested\n> +\t * operation immediately.\n> +\t */\n> +\n> +\tLWLockAcquire(DatachecksumsWorkerLock, LW_EXCLUSIVE);\n> +\n> +\t/*\n> +\t * If the launcher is already started, the only operation we can perform\n> +\t * is to cancel it iff the user requested for checksums to be disabled.\n> +\t * That doesn't however mean that all other cases yield an error, as some\n> +\t * might be perfectly benevolent.\n> +\t */\n> +\tif (DatachecksumsWorkerShmem->launcher_started)\n> +\t{\n> +\t\tif (DatachecksumsWorkerShmem->abort)\n> +\t\t{\n> +\t\t\tereport(NOTICE,\n> +\t\t\t\t\t(errmsg(\"data checksum processing is concurrently being aborted, please retry\")));\n> +\n> +\t\t\tLWLockRelease(DatachecksumsWorkerLock);\n> +\t\t\treturn;\n> +\t\t}\n> +\n> +\t\t/*\n> +\t\t * If the launcher is started data checksums cannot be on or off, but\n> +\t\t * it may be in an inprogress state. Since the state transition may\n> +\t\t * not have happened yet (in case of rapidly initiated checksum enable\n> +\t\t * calls for example) we inspect the target state of the currently\n> +\t\t * running launcher.\n> +\t\t */\n> +\n\nextra newline\n\n> +\t\tif (enable_checksums)\n> +\t\t{\n> +\t\t\t/*\n> +\t\t\t * If we are asked to enable checksums when they are already being\n> +\t\t\t * enabled, there is nothing to do so exit.\n> +\t\t\t */\n> +\t\t\tif (DatachecksumsWorkerShmem->target)\n\nWould \"if (DatachecksumsWorkerShmem->target == enable_checksums)\" maybe\nbe better, or does that change the meaning?\n\n> +\t}\n> +\n> +\t/*\n> +\t * The launcher is currently not running, so we need to query the system\n> +\t * data checksum state to determine how to proceed based on the requested\n> +\t * target state.\n> +\t */\n> +\telse\n> +\t{\n\nThat's a slightly weird comment placement, maybe put it below the '{' so\nthat that the '} else {' is kept intact?\n\n> +\t\tmemset(DatachecksumsWorkerShmem->operations, 0, sizeof(DatachecksumsWorkerShmem->operations));\n> +\t\tDatachecksumsWorkerShmem->target = enable_checksums;\n\nThis one is especially confusing as it looks like we're unconditionally\nenabling checksums but instead we're just setting the target based on\nthe bool (see above). It might be our standard notation though.\n\n[...]\n\n> +/*\n> + * ProcessDatabase\n> + *\t\tEnable data checksums in a single database.\n> + *\n> + * We do this by launching a dynamic background worker into this database, and\n> + * waiting for it to finish. We have to do this in a separate worker, since\n> + * each process can only be connected to one database during its lifetime.\n> + */\n> +static DatachecksumsWorkerResult\n> +ProcessDatabase(DatachecksumsWorkerDatabase * db, const char *bgw_func_name)\n\n> +\t/*\n> +\t * If the postmaster crashed we cannot end up with a processed database so\n> +\t * we have no alternative other than exiting. When enabling checksums we\n> +\t * won't at this time have changed the pg_control version to enabled so\n> +\t * when the cluster comes back up processing will have to be resumed. When\n> +\t * disabling, the pg_control version will be set to off before this so\n> +\t * when the cluster comes up checksums will be off as expected. In the\n> +\t * latter case we might have stale relhaschecksums flags in pg_class which\n> +\t * need to be handled in some way. TODO\n\nAny idea on how? Or is that for a future feature and can just be documented\nfor now? In any case, one can just run pg_disable_checksums() again as\nmentioned elsewhere so maybe just rephrase the comment to say the admin\nneeds to do that?\n\n(skipped the rest of this file for now)\n\n> diff --git a/src/backend/utils/init/postinit.c b/src/backend/utils/init/postinit.c\n> index 59b3f4b135..ce933a9d08 100644\n> --- a/src/backend/utils/init/postinit.c\n> +++ b/src/backend/utils/init/postinit.c\n> @@ -605,6 +605,11 @@ InitPostgres(const char *in_dbname, Oid dboid, const char *username,\n> \tif (MyBackendId > MaxBackends || MyBackendId <= 0)\n> \t\telog(FATAL, \"bad backend ID: %d\", MyBackendId);\n> \n> +\t/*\n> +\t * Set up local cache of Controldata values.\n> +\t */\n> +\tInitLocalControldata();\n\nThis just sets LocalDataChecksumVersion for now, is it expected to cache\nother ControlData values in the future? Maybe clarifying the current\nstate in the comment would be in order.\n\n> diff --git a/src/backend/utils/misc/guc.c b/src/backend/utils/misc/guc.c\n> index 2779da8a69..d583a052e2 100644\n> --- a/src/backend/utils/misc/guc.c\n> +++ b/src/backend/utils/misc/guc.c\n> @@ -498,6 +500,17 @@ static struct config_enum_entry shared_memory_options[] = {\n> \t{NULL, 0, false}\n> };\n> \n> +/*\n> + * Options for data_checksums enum.\n> + */\n> +static const struct config_enum_entry data_checksum_options[] = {\n> +\t{\"on\", DATA_CHECKSUMS_ON, true},\n> +\t{\"off\", DATA_CHECKSUMS_OFF, true},\n> +\t{\"inprogress-on\", DATA_CHECKSUMS_INPROGRESS_ON, true},\n> +\t{\"inprogress-off\", DATA_CHECKSUMS_INPROGRESS_OFF, true},\n> +\t{NULL, 0, false}\n> +};\n> +\n> /*\n> * Options for enum values stored in other modules\n> */\n> @@ -607,7 +620,7 @@ static int\tmax_identifier_length;\n> static int\tblock_size;\n> static int\tsegment_size;\n> static int\twal_block_size;\n> -static bool data_checksums;\n> +static int\tdata_checksums_tmp;\n\nWhy the _tmp, is that required for enum GUCs?\n\n\nMichael\n\n-- \nMichael Banck\nProjektleiter / Senior Berater\nTel.: +49 2166 9901-171\nFax: +49 2166 9901-100\nEmail: michael.banck@credativ.de\n\ncredativ GmbH, HRB M�nchengladbach 12080\nUSt-ID-Nummer: DE204566209\nTrompeterallee 108, 41189 M�nchengladbach\nGesch�ftsf�hrung: Dr. Michael Meskes, J�rg Folz, Sascha Heuer\n\nUnser Umgang mit personenbezogenen Daten unterliegt\nfolgenden Bestimmungen: https://www.credativ.de/datenschutz\n\n\n", "msg_date": "Tue, 5 Jan 2021 21:29:31 +0100", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Tue, Jan 05, 2021 at 09:29:31PM +0100, Michael Banck wrote:\n> > @@ -4938,13 +4949,299 @@ GetMockAuthenticationNonce(void)\n> > /*\n> > - * Are checksums enabled for data pages?\n> > + * DataChecksumsNeedWrite\n> > + *\t\tReturns whether data checksums must be written or not\n> > + *\n> > + * Are checksums enabled, or in the process of being enabled, for data pages?\n> \n> The second \",\" looks odd and could be ommitted?.\n\nMaybe write:\n\n> > + * Are checksums on data pages enabled, or in the process of being enabled ?\n\n\n\n", "msg_date": "Tue, 5 Jan 2021 14:40:04 -0600", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 5 Jan 2021, at 21:29, Michael Banck <michael.banck@credativ.de> wrote:\n> On Tue, Jan 05, 2021 at 12:18:07AM +0100, Daniel Gustafsson wrote:\n\n>> Attached is a rebase of the patch on top of current HEAD.\n> \n> Some more comments/questions:\n\nThanks for reviewing, much appreciated!\n\n>> diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c\n>> index 53e997cd55..06c001f8ff 100644\n>> --- a/src/backend/access/heap/heapam.c\n>> +++ b/src/backend/access/heap/heapam.c\n>> @@ -7284,7 +7284,7 @@ log_heap_freeze(Relation reln, Buffer buffer, TransactionId cutoff_xid,\n>> * and dirtied.\n>> *\n>> * If checksums are enabled, we also generate a full-page image of\n>> - * heap_buffer, if necessary.\n>> + * heap_buffer.\n> \n> That sounds like it has nothing to do with online (de)activation of\n> checksums?\n\nRight, it's a fix which is independent of this which could be broken out into a\nseparate docs patch along with the suggestions in your previous mail.\n\n>> */\n>> XLogRecPtr\n>> log_heap_visible(RelFileNode rnode, Buffer heap_buffer, Buffer vm_buffer,\n>> @@ -7305,11 +7305,13 @@ log_heap_visible(RelFileNode rnode, Buffer heap_buffer, Buffer vm_buffer,\n>> \tXLogRegisterBuffer(0, vm_buffer, 0);\n>> \n>> \tflags = REGBUF_STANDARD;\n>> +\tHOLD_INTERRUPTS();\n>> \tif (!XLogHintBitIsNeeded())\n>> \t\tflags |= REGBUF_NO_IMAGE;\n>> \tXLogRegisterBuffer(1, heap_buffer, flags);\n>> \n>> \trecptr = XLogInsert(RM_HEAP2_ID, XLOG_HEAP2_VISIBLE);\n>> +\tRESUME_INTERRUPTS();\n> \n> This could maybe do with a comment on why the HOLD/RESUME_INTERRUPTS()\n> is required here, similar as is done in bufpage.c further down.\n\nFixed.\n\n>> diff --git a/src/backend/access/rmgrdesc/xlogdesc.c b/src/backend/access/rmgrdesc/xlogdesc.c\n>> index 92cc7ea073..fa074c6046 100644\n>> --- a/src/backend/access/rmgrdesc/xlogdesc.c\n>> +++ b/src/backend/access/rmgrdesc/xlogdesc.c\n>> @@ -18,6 +18,7 @@\n>> #include \"access/xlog.h\"\n>> #include \"access/xlog_internal.h\"\n>> #include \"catalog/pg_control.h\"\n>> +#include \"storage/bufpage.h\"\n>> #include \"utils/guc.h\"\n>> #include \"utils/timestamp.h\"\n>> \n>> @@ -140,6 +141,20 @@ xlog_desc(StringInfo buf, XLogReaderState *record)\n>> \t\t\t\t\t\t xlrec.ThisTimeLineID, xlrec.PrevTimeLineID,\n>> \t\t\t\t\t\t timestamptz_to_str(xlrec.end_time));\n>> \t}\n>> +\telse if (info == XLOG_CHECKSUMS)\n>> +\t{\n>> +\t\txl_checksum_state xlrec;\n>> +\n>> +\t\tmemcpy(&xlrec, rec, sizeof(xl_checksum_state));\n>> +\t\tif (xlrec.new_checksumtype == PG_DATA_CHECKSUM_VERSION)\n>> +\t\t\tappendStringInfo(buf, \"on\");\n>> +\t\telse if (xlrec.new_checksumtype == PG_DATA_CHECKSUM_INPROGRESS_OFF_VERSION)\n>> +\t\t\tappendStringInfo(buf, \"inprogress-off\");\n>> +\t\telse if (xlrec.new_checksumtype == PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION)\n>> +\t\t\tappendStringInfo(buf, \"inprogress-on\");\n>> +\t\telse\n>> +\t\t\tappendStringInfo(buf, \"off\");\n> \n> We probably discussed this earlier, but what was the conclusion?\n> PG_DATA_CHECKSUM_VERSION = 1 sounds like somebody thought it a good idea\n> to not just have a bool here but they probably rather thought about\n> different checkumming/hashing algorithms/implentations than about\n> internal state of the checksumming machinery.\n\nCommit 443951748ce4c94b001877c7cf88b0ee969c79e7 explicitly moved from a bool to\nbe able to handle changes to the checksum field. I don't recall it being\ndiscussed in the context of this patch.\n\n> If we decide on v2 of data page checksums, how would that look like?\n> \n> PG_DATA_CHECKSUM_VERSION_V2 = 4?\n\nSomething like that yes.\n\n> If we think we're done with versions, did we consider removing the\n> VERSION here, because it is really confusing in\n> PG_DATA_CHECKSUM_INPROGRESS_ON/OFF_VERSION, like\n> PG_DATA_CHECKSUM_STATE_ON/INPROGRESS_ON/OFF? Or would removing \"version\"\n> also from pg_controldata be a backwards-incompatible change we don't\n> want to do?\n\nWe could rename the _INPROGRESS states to not have the _VERSION suffix, but\nthen we'd end up in a discussion around what a checksum version is, and we'd be\nassigning something not named _VERSION to a version field . I think the\ncurrent state of the patch is the least surprising.\n\n> Sorry again, I think we discussed it earlier, but maybe at least some\n> comments about what VERSION is supposed to be/mean in bufpage.h would be\n> in order:\n\nThat I don't disagree with, but it can be done separately from this work. I\ndidn't chase down the thread which led to 443951748ce4c94b but I assume the\ndiscussion there would be useful for documenting this.\n\n>> -\tdoPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites);\n>> +\tdoPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites || DataChecksumsOnInProgress());\n> \n> Indent, but I guess this will be indented by pg_indent after the fact\n> andyway? Or is this how it's supposed to look?\n\nThe patch has been through pgindent so I think it's by design.\n\n>> + * Are checksums enabled, or in the process of being enabled, for data pages?\n> \n> The second \",\" looks odd and could be ommitted?.\n\nI think that was correct, but not being a native speaker I might be wrong.\nEither way I've reworded the comment to make it clearer since it on the whole\nseemed a bit cobbled together.\n\n>> + * to keep the critical section short. This is in order to protect against\n>> + * TOCTOU situations around checksum validation.\n> \n> I had to google \"TOCTOU\" and this acronym doesn't appear elsewhere in\n> the source tree, so I suggest to spell it out at least here (there's one\n> more occurance of it in this patch)\n\nFair enough, both places fixed. The comment in RelationBuildLocalRelation was\nalso reworded a bit to try and make a tad clearer.\n\n>> + * DataChecksumsOnInProgress\n>> + *\t\tReturns whether data checksums are being enabled\n>> + *\n>> + * Most operations don't need to worry about the \"inprogress\" states, and\n>> + * should use DataChecksumsNeedVerify() or DataChecksumsNeedWrite(). The\n>> + * \"inprogress\" state for enabling checksums is used when the checksum worker\n>> + * is setting checksums on all pages, it can thus be used to check for aborted\n>> + * checksum processing which need to be restarted.\n> \n> The first \"inprogress\" looks legit as it talks about both states, but\n> the second one should be \"inprogress-on\" I think and ...\n\nThe sentence was as intended, but I agree that spelling out the state name is\nbetter. Fixed.\n\n>> + * DataChecksumsOffInProgress\n>> + *\t\tReturns whether data checksums are being disabled\n>> + *\n>> + * The \"inprogress\" state for disabling checksums is used for when the worker\n>> + * resets the catalog state. Operations should use DataChecksumsNeedVerify()\n>> + * or DataChecksumsNeedWrite() for deciding whether to read/write checksums.\n> \n> ... \"inprogress-off\" here.\n\nSame as the above, but also fixed (with some additional wordsmithing).\n\n>> +void\n>> +AbsorbChecksumsOnInProgressBarrier(void)\n>> +{\n>> + Assert(LocalDataChecksumVersion == 0 || LocalDataChecksumVersion == PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION);\n>> + LocalDataChecksumVersion = PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION;\n>> +}\n> \n> Bikeshed alert: maybe alo those Absorb*Barrier functions could be lumped\n> together after the SetDataChecksums*() functions. If not, a function\n> comment would be in order.\n\nI moved all the Absorb* functions into a single place since they very similar.\n\n>> +void\n>> +SetDataChecksumsOnInProgress(void)\n\n> This function doesn't have the customary function header comment nor any\n> comments in the body and it looks like it's doing some pretty important\n> stuff, so I think some comments would be in order, e.g.\n> explaining that \"data_checksum_version != 0\" means we've already got\n> checksums enabled or are in the process of enabling/disabling them.\n\nThat was indeed sloppy, fixed.\n\n>> +/*\n>> + * SetDataChecksumsOn\n>> + *\t\tEnables data checksums cluster-wide\n>> + *\n>> + * Enabling data checksums is performed using two barriers, the first one\n>> + * sets the checksums state to \"inprogress-on\" and the second one to \"on\".\n>> + * During \"inprogress-on\", checksums are written but not verified. When all\n>> + * existing pages are guaranteed to have checksums, and all new pages will be\n>> + * initiated with checksums, the state can be changed to \"on\".\n> \n> This should proabably go above SetDataChecksumsOnInProgress() because\n> even though I've just reviewed this, I looked at the following function\n> body and wondered where the second barrier went...\n\nI kept the ordering but reworded to comment to make it clearer.\n\n>> +\t * inprogress-off state during which backends continue to write checksums\n> \n> The inprogress-off is in \" \" everywhere else.\n\nFixed.\n\n>> +\telse\n>> +\t{\n>> +\t\t/*\n>> +\t\t * Ending up here implies that the checksums state is \"inprogress-on\"\n>> +\t\t * and we can transition directly to \"off\" from there.\n> \n> Can you explain that a bit more? Is \"inprogress-on\" a typo for\n> \"inprogress-off\", or do you really mean that we can just switch off\n> checksums during \"inprogress-on\"? If so, the rationale should be\n> explained a bit more.\n\nThe reason why we need \"inprogress-off\", where checksums are written but not\nverified, is to ensure that backends still in the \"on\" state have checksums\nupdated to not incur verification failures on concurrent writes.\n\nIf the state is \"inprogress-on\" then checksums are being written but not\nverified, so we can transition directly to \"off\" as there are no backends\nverifying data checksums so there is to need to keep writing them.\n\n>> @@ -7929,6 +8226,32 @@ StartupXLOG(void)\n>> \t */\n>> \tCompleteCommitTsInitialization();\n>> \n>> +\t/*\n>> +\t * If we reach this point with checksums in progress state (either being\n>> +\t * enabled or being disabled), we notify the user that they need to\n>> +\t * manually restart the process to enable checksums. This is because we\n> \n> I think this could rephrased to \"If we reach this point with checksums\n> being enabled, we notify...\" because the disable case is different and\n> handled in the following block.\n\nCorrect, that sentence was a leftover from a previous version of this codepath,\nfixed.\n\n>> @@ -965,10 +965,13 @@ InsertPgClassTuple(Relation pg_class_desc,\n>> \t/* relpartbound is set by updating this tuple, if necessary */\n>> \tnulls[Anum_pg_class_relpartbound - 1] = true;\n>> \n>> +\tHOLD_INTERRUPTS();\n>> +\tvalues[Anum_pg_class_relhaschecksums - 1] = BoolGetDatum(DataChecksumsNeedWrite());\n>> \ttup = heap_form_tuple(RelationGetDescr(pg_class_desc), values, nulls);\n>> \n>> \t/* finally insert the new tuple, update the indexes, and clean up */\n>> \tCatalogTupleInsert(pg_class_desc, tup);\n>> +\tRESUME_INTERRUPTS();\n>> \n>> \theap_freetuple(tup);\n> \n> Maybe add a comment here why we now HOLD/RESUME_INTERRUPTS.\n\nFixed.\n\n>> + * a lot of WAL as the entire database is read and written. Once all datapages\n> \n> It's \"data page\" with a space in between everywhere else.\n\nFixed.\n\n>> + *\t\t- Backends SHALL NOT violate local datachecksum state\n>> + *\t\t- Data checksums SHALL NOT be considered enabled cluster-wide until all\n> \n> Linewrap.\n\nNot sure what you mean here, sentence is too long to fit on one line.\n\n>> + * When Enabling Data Checksums\n>> + *\t ----------------------------\n> \n> There's something off with the indentation of either the title or the\n> line seperator here.\n\nThere was a mix of tab and space, fixed to consistently use spaces for\nindentation here.\n\n>> + * When the DataChecksumsWorker has finished writing checksums on all pages\n>> + * and enable data checksums cluster-wide, there are three sets of backends:\n> \n> \"enables\"\n\nFixed.\n\n>> + * Bg: Backend updating the global state and emitting the procsignalbarrier\n>> + * Bd: Backends on \"off\" state\n> \n> s/on/in/\n> \n> Also, given that \"When the DataChecksumsWorker has finished writing\n> checksums on all pages and enable[s] data checksums cluster-wide\",\n> shouldn't that mean that all other backends are either in \"on\" or\n> \"inprogress-on\" state, because the Bd -> Bi transition happened during a\n> previous barrier? Maybe that should be first explained?\n\nRight, I've reworded this and wordsmithed a bit to make it a bit less\nconvoluted.\n\n>> + * Be: Backends in \"on\" state\n>> + * Bi: Backends in \"inprogress-on\" state\n>> + *\n>> + * Backends transition from the Bd state to Be like so: Bd -> Bi -> Be\n>> + *\n>> + * Backends in Bi and Be will write checksums when modifying a page, but only\n>> + * backends in Be will verify the checksum during reading. The Bg backend is\n>> + * blocked waiting for all backends in Bi to process interrupts and move to\n>> + * Be. Any backend starting will observe the global state being \"on\" and will\n> \n> \"Any backend starting while Bg is waiting for the barrier\" right?\n\nCorrect, fixed.\n\n>> + * All sets are compatible while still operating based on\n>> + * their local state.\n> \n> Whoa, you lost me there.\n\nWhat I meant was that Bi and Be are compatible as they both satisfy the\nrequirement of each other (both write checksums), so they can concurrently\nexist in a cluster without false negatives occurring. Reworded.\n\n>> + *\t When Disabling Data Checksums\n>> + *\t -----------------------------\n>> + *\t A process which fails to observe data checksums being disabled can induce\n>> + *\t two types of errors: writing the checksum when modifying the page and\n> \n> Can you rephrase what you mean with \"being disabled\"? If you mean we're\n> in the \"inprogress-off\" state, then why is that an error? Do you mean\n> \"writing *no* checksum\" because AIUI we should still write checksums at\n> this point? Or are you talking about a different state?\n\nThis was referring to the \"off\" state, but it wasn't terribly clear. I've\nreworded that part.\n\n>> + *\t validating a data checksum which is no longer correct due to modifications\n>> + *\t to the page.\n>> + *\n>> + * Bg: Backend updating the global state and emitting the procsignalbarrier\n>> + * Bd: Backands in \"off\" state\n> \n> s/Backands/Backends/\n\nFixed.\n\n>> + * Be: Backends in \"on\" state\n>> + * Bi: Backends in \"inprogress-off\" state\n> \n> I suggest using a different symbol here for \"inprogress-off\" in order\n> not to confuse the two (different right?) Bi.\n\nGood point, fixed.\n\n>> + * Backends transition from the Be state to Bd like so: Be -> Bi -> Bd\n>> + *\n>> + * The goal is to transition all backends to Bd making the others empty sets.\n>> + * Backends in Bi writes data checksums, but don't validate them, such that\n> \n> s/writes/write/\n\nFixed.\n\n>> + * backends still in Be can continue to validate pages until the barrier has\n>> + * been absorbed such that they are in Bi. Once all backends are in Bi, the\n>> + * barrier to transition to \"off\" can be raised and all backends can safely\n>> + * stop writing data checksums as no backend is enforcing data checksum\n>> + * validation.\n> \n> ... \"anymore\" maybe.\n\nMakes sense, fixed.\n\n>> + * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group\n> \n> Copyright year bump, there's two other occurances.\n\nFixed.\n\n>> +\tbool\t\ttarget;\n> \n> This \"target\" bool isn't documented very well (at least here). AIUI,\n> it's true if we enable checksums and false if we disable them?\n\nCorrect, and I agree that the name is quite poor. I renamed to\n\"enable_checksums\" and added a comment.\n\n>> +void\n>> +StartDatachecksumsWorkerLauncher(bool enable_checksums, int cost_delay, int cost_limit)\n> \n> After reading through the function I find this 'bool enable_checksums'\n> a bit confusing, I think something like 'int operation' and then\n> comparing it to either ENABLE or DISABLE or whatever would make the code\n> more readable, but it's a minor nitpick.\n\nMaybe, I personally find enable_checksums to be self-explanatory but I'm\nclearly biased. With the small change of renaming \"target\", do you still think\nit should be changed?\n\n>> +\t\t * running launcher.\n>> +\t\t */\n>> +\n> \n> extra newline\n\nFixed.\n\n>> +\t\t\tif (DatachecksumsWorkerShmem->target)\n> \n> Would \"if (DatachecksumsWorkerShmem->target == enable_checksums)\" maybe\n> be better, or does that change the meaning?\n\nIt would change its meaning as it would always be true. Since renaming target\nto enable_checksums I think this condition is quite clear though.\n\n>> +\t/*\n>> +\t * The launcher is currently not running, so we need to query the system\n>> +\t * data checksum state to determine how to proceed based on the requested\n>> +\t * target state.\n>> +\t */\n>> +\telse\n>> +\t{\n> \n> That's a slightly weird comment placement, maybe put it below the '{' so\n> that that the '} else {' is kept intact?\n\nThis style is used in a number of places in the patch, and it's used around the\ntree as well. If it's a common concern/complaint then I'm happy to change them\nall.\n\n>> +\t\tmemset(DatachecksumsWorkerShmem->operations, 0, sizeof(DatachecksumsWorkerShmem->operations));\n>> +\t\tDatachecksumsWorkerShmem->target = enable_checksums;\n> \n> This one is especially confusing as it looks like we're unconditionally\n> enabling checksums but instead we're just setting the target based on\n> the bool (see above). It might be our standard notation though.\n\nAfter the rename of the variable to enable_checkums it reads pretty clear that\nthis operation is caching the passed in value. What do you think about the\ncodepath now?\n\n>> +\t/*\n>> +\t * If the postmaster crashed we cannot end up with a processed database so\n>> +\t * we have no alternative other than exiting. When enabling checksums we\n>> +\t * won't at this time have changed the pg_control version to enabled so\n>> +\t * when the cluster comes back up processing will have to be resumed. When\n>> +\t * disabling, the pg_control version will be set to off before this so\n>> +\t * when the cluster comes up checksums will be off as expected. In the\n>> +\t * latter case we might have stale relhaschecksums flags in pg_class which\n>> +\t * need to be handled in some way. TODO\n> \n> Any idea on how? Or is that for a future feature and can just be documented\n> for now? In any case, one can just run pg_disable_checksums() again as\n> mentioned elsewhere so maybe just rephrase the comment to say the admin\n> needs to do that?\n\nI've reworded the comment to be a nice to have rather than a need to have,\nsince stale flags have no practical implication. Regarding how to address it\nI'm not really sure what the cleanest way would be, and I've deliberately held\noff on it since it's mostly cosmetical and this patch is complicated enough as\nit is.\n\n>> +\t/*\n>> +\t * Set up local cache of Controldata values.\n>> +\t */\n>> +\tInitLocalControldata();\n> \n> This just sets LocalDataChecksumVersion for now, is it expected to cache\n> other ControlData values in the future? Maybe clarifying the current\n> state in the comment would be in order.\n\nI'm a bit hesitant to write in the comment that it's only the data checksums\nstate right now, since such a comment is almost guaranteed to be missed and\nbecome stale when/if InitLocalControldata gains more capabilities. Instead\nI've added a function comment in xlog.c on InitLocalControldata.\n\n>> -static bool data_checksums;\n>> +static int\tdata_checksums_tmp;\n> \n> Why the _tmp, is that required for enum GUCs?\n\nThat is a missed leftover from an earlier version, removed.\n\nAttached is a rebase with the above fixes, thanks for review!\n\ncheers ./daniel", "msg_date": "Thu, 7 Jan 2021 15:03:07 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 5 Jan 2021, at 18:19, Michael Banck <michael.banck@credativ.de> wrote:\n\n>> diff --git a/doc/src/sgml/ref/initdb.sgml b/doc/src/sgml/ref/initdb.sgml\n>> index 385ac25150..e3b0048806 100644\n>> --- a/doc/src/sgml/ref/initdb.sgml\n>> +++ b/doc/src/sgml/ref/initdb.sgml\n>> @@ -219,6 +219,7 @@ PostgreSQL documentation\n>> failures will be reported in the\n>> <link linkend=\"monitoring-pg-stat-database-view\">\n>> <structname>pg_stat_database</structname></link> view.\n>> + See <xref linkend=\"checksums\" /> for details.\n>> </para>\n>> </listitem>\n>> </varlistentry>\n> \n>> diff --git a/doc/src/sgml/wal.sgml b/doc/src/sgml/wal.sgml\n>> index f4bc147b10..5dcfcdd2ff 100644\n>> --- a/doc/src/sgml/wal.sgml\n>> +++ b/doc/src/sgml/wal.sgml\n>> @@ -230,6 +230,103 @@\n>> </para>\n>> </sect1>\n>> \n>> + <sect1 id=\"checksums\">\n>> + <title>Data Checksums</title>\n>> + <indexterm>\n>> + <primary>checksums</primary>\n>> + </indexterm>\n>> +\n>> + <para>\n>> + Data pages are not checksum protected by default, but this can optionally be\n>> + enabled for a cluster. When enabled, each data page will be assigned a\n>> + checksum that is updated when the page is written and verified every time\n>> + the page is read. Only data pages are protected by checksums, internal data\n>> + structures and temporary files are not.\n>> + </para>\n>> +\n>> + <para>\n>> + Checksums are normally enabled when the cluster is initialized using <link\n>> + linkend=\"app-initdb-data-checksums\"><application>initdb</application></link>.\n>> + They can also be enabled or disabled at a later time, either as an offline\n>> + operation or in a running cluster. In all cases, checksums are enabled or\n>> + disabled at the full cluster level, and cannot be specified individually for\n>> + databases or tables.\n>> + </para>\n>> +\n>> + <para>\n>> + The current state of checksums in the cluster can be verified by viewing the\n>> + value of the read-only configuration variable <xref\n>> + linkend=\"guc-data-checksums\" /> by issuing the command <command>SHOW\n>> + data_checksums</command>.\n>> + </para>\n>> +\n>> + <para>\n>> + When attempting to recover from corrupt data it may be necessary to bypass\n>> + the checksum protection in order to recover data. To do this, temporarily\n>> + set the configuration parameter <xref linkend=\"guc-ignore-checksum-failure\" />.\n>> + </para>\n> \n> I think the above is rather informative about checksums in general and\n> not specific to online activation of checksusm, so could pretty much be\n> committed verbatim right now, except for the \"either as an offline\n> operation or in a running cluster\" bit which would have to be rewritten.\n\nThat might indeedbe useful regardless of the state of this patch. Robert and\nHeikki: being committers who have both reviewed recent versions of the patch,\nwould you prefer these sections be broken out into a separate patch?\n\ncheers ./daniel\n\n", "msg_date": "Thu, 7 Jan 2021 15:05:44 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "Hi,\n\nOn Thu, Jan 07, 2021 at 03:05:44PM +0100, Daniel Gustafsson wrote:\n> > On 5 Jan 2021, at 18:19, Michael Banck <michael.banck@credativ.de> wrote:\n> >> + <para>\n> >> + Data pages are not checksum protected by default, but this can optionally be\n> >> + enabled for a cluster. \n\nThis would also have to be rewritten to clarify that it \"can optionally\nbe enabled during cluster creation or when the cluster is offline later\non\" I'd say.\n\n\nMichael\n\n-- \nMichael Banck\nProjektleiter / Senior Berater\nTel.: +49 2166 9901-171\nFax: +49 2166 9901-100\nEmail: michael.banck@credativ.de\n\ncredativ GmbH, HRB M�nchengladbach 12080\nUSt-ID-Nummer: DE204566209\nTrompeterallee 108, 41189 M�nchengladbach\nGesch�ftsf�hrung: Dr. Michael Meskes, J�rg Folz, Sascha Heuer\n\nUnser Umgang mit personenbezogenen Daten unterliegt\nfolgenden Bestimmungen: https://www.credativ.de/datenschutz\n\n\n", "msg_date": "Thu, 7 Jan 2021 15:10:12 +0100", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Thu, Jan 7, 2021 at 3:05 PM Daniel Gustafsson <daniel@yesql.se> wrote:\n>\n> > On 5 Jan 2021, at 18:19, Michael Banck <michael.banck@credativ.de> wrote:\n>\n> >> diff --git a/doc/src/sgml/ref/initdb.sgml b/doc/src/sgml/ref/initdb.sgml\n> >> index 385ac25150..e3b0048806 100644\n> >> --- a/doc/src/sgml/ref/initdb.sgml\n> >> +++ b/doc/src/sgml/ref/initdb.sgml\n> >> @@ -219,6 +219,7 @@ PostgreSQL documentation\n> >> failures will be reported in the\n> >> <link linkend=\"monitoring-pg-stat-database-view\">\n> >> <structname>pg_stat_database</structname></link> view.\n> >> + See <xref linkend=\"checksums\" /> for details.\n> >> </para>\n> >> </listitem>\n> >> </varlistentry>\n> >\n> >> diff --git a/doc/src/sgml/wal.sgml b/doc/src/sgml/wal.sgml\n> >> index f4bc147b10..5dcfcdd2ff 100644\n> >> --- a/doc/src/sgml/wal.sgml\n> >> +++ b/doc/src/sgml/wal.sgml\n> >> @@ -230,6 +230,103 @@\n> >> </para>\n> >> </sect1>\n> >>\n> >> + <sect1 id=\"checksums\">\n> >> + <title>Data Checksums</title>\n> >> + <indexterm>\n> >> + <primary>checksums</primary>\n> >> + </indexterm>\n> >> +\n> >> + <para>\n> >> + Data pages are not checksum protected by default, but this can optionally be\n> >> + enabled for a cluster. When enabled, each data page will be assigned a\n> >> + checksum that is updated when the page is written and verified every time\n> >> + the page is read. Only data pages are protected by checksums, internal data\n> >> + structures and temporary files are not.\n> >> + </para>\n> >> +\n> >> + <para>\n> >> + Checksums are normally enabled when the cluster is initialized using <link\n> >> + linkend=\"app-initdb-data-checksums\"><application>initdb</application></link>.\n> >> + They can also be enabled or disabled at a later time, either as an offline\n> >> + operation or in a running cluster. In all cases, checksums are enabled or\n> >> + disabled at the full cluster level, and cannot be specified individually for\n> >> + databases or tables.\n> >> + </para>\n> >> +\n> >> + <para>\n> >> + The current state of checksums in the cluster can be verified by viewing the\n> >> + value of the read-only configuration variable <xref\n> >> + linkend=\"guc-data-checksums\" /> by issuing the command <command>SHOW\n> >> + data_checksums</command>.\n> >> + </para>\n> >> +\n> >> + <para>\n> >> + When attempting to recover from corrupt data it may be necessary to bypass\n> >> + the checksum protection in order to recover data. To do this, temporarily\n> >> + set the configuration parameter <xref linkend=\"guc-ignore-checksum-failure\" />.\n> >> + </para>\n> >\n> > I think the above is rather informative about checksums in general and\n> > not specific to online activation of checksusm, so could pretty much be\n> > committed verbatim right now, except for the \"either as an offline\n> > operation or in a running cluster\" bit which would have to be rewritten.\n>\n> That might indeedbe useful regardless of the state of this patch. Robert and\n> Heikki: being committers who have both reviewed recent versions of the patch,\n> would you prefer these sections be broken out into a separate patch?\n\nI think it would be ;)\n\nObviously in that case adapted so that it has to be changed offline,\nand the patch would have to change that to say it can be changed\nonline.\n\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/\n Work: https://www.redpill-linpro.com/\n\n\n", "msg_date": "Thu, 7 Jan 2021 16:25:58 +0100", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 7 Jan 2021, at 16:25, Magnus Hagander <magnus@hagander.net> wrote:\n\n> I think it would be ;)\n> \n> Obviously in that case adapted so that it has to be changed offline,\n> and the patch would have to change that to say it can be changed\n> online.\n\nAttached is a v28 which has the docs portion separated out into 0001 with 0002\nchanging the docs in 0001 to mention the online operation.\n\ncheers ./daniel", "msg_date": "Tue, 12 Jan 2021 00:07:57 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 12 Jan 2021, at 00:07, Daniel Gustafsson <daniel@yesql.se> wrote:\n> \n>> On 7 Jan 2021, at 16:25, Magnus Hagander <magnus@hagander.net> wrote:\n> \n>> I think it would be ;)\n>> \n>> Obviously in that case adapted so that it has to be changed offline,\n>> and the patch would have to change that to say it can be changed\n>> online.\n> \n> Attached is a v28 which has the docs portion separated out into 0001 with 0002\n> changing the docs in 0001 to mention the online operation.\n\nAttached is v29 which adds a small test for running pg_checksums on a cluster\nturned off during a checksum enable operation (as well as some minor word-\nsmithing in test comments).\n\ncheers ./daniel", "msg_date": "Tue, 12 Jan 2021 21:54:11 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "The attached v30 adds the proposed optimizations in this thread as previously\nasked for, as well as some small cleanups to the procsignal calling codepath\n(replacing single call functions with just calling the function) and some\nfunction comments which were missing.\n\ncheers ./daniel", "msg_date": "Fri, 15 Jan 2021 11:32:56 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Fri, Jan 15, 2021 at 11:33 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n>\n> The attached v30 adds the proposed optimizations in this thread as previously\n> asked for, as well as some small cleanups to the procsignal calling codepath\n> (replacing single call functions with just calling the function) and some\n> function comments which were missing.\n\nI've applied the docs patch.\n\nI made a tiny change so the reference to \"data page checksums\" was\nchanged to \"data checksums\". Of course, after doing that I realize\nthat we use both terms in different places, but the docs side mostly\ntalked about \"data checksums\". I changed the one reference that was\nalso in wal.sgml, but left the rest alone.\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/\n Work: https://www.redpill-linpro.com/\n\n\n", "msg_date": "Sun, 17 Jan 2021 15:35:26 +0100", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "Hi,\n\nOn Fri, Jan 15, 2021 at 11:32:56AM +0100, Daniel Gustafsson wrote:\n> The attached v30 adds the proposed optimizations in this thread as previously\n> asked for, as well as some small cleanups to the procsignal calling codepath\n> (replacing single call functions with just calling the function) and some\n> function comments which were missing.\n\n0002 (now 0001 I guess) needs a rebase due to a3ed4d1e.\n\n\nMichael\n\n-- \nMichael Banck\nProjektleiter / Senior Berater\nTel.: +49 2166 9901-171\nFax: +49 2166 9901-100\nEmail: michael.banck@credativ.de\n\ncredativ GmbH, HRB M�nchengladbach 12080\nUSt-ID-Nummer: DE204566209\nTrompeterallee 108, 41189 M�nchengladbach\nGesch�ftsf�hrung: Dr. Michael Meskes, J�rg Folz, Sascha Heuer\n\nUnser Umgang mit personenbezogenen Daten unterliegt\nfolgenden Bestimmungen: https://www.credativ.de/datenschutz\n\n\n", "msg_date": "Mon, 18 Jan 2021 19:14:23 +0100", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 18 Jan 2021, at 19:14, Michael Banck <michael.banck@credativ.de> wrote:\n> \n> Hi,\n> \n> On Fri, Jan 15, 2021 at 11:32:56AM +0100, Daniel Gustafsson wrote:\n>> The attached v30 adds the proposed optimizations in this thread as previously\n>> asked for, as well as some small cleanups to the procsignal calling codepath\n>> (replacing single call functions with just calling the function) and some\n>> function comments which were missing.\n> \n> 0002 (now 0001 I guess) needs a rebase due to a3ed4d1e.\n\nCorrect, rebase attached.\n\ncheers ./daniel", "msg_date": "Tue, 19 Jan 2021 13:32:59 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "I read through the latest patch, \nv31-0001-Support-checksum-enable-disable-in-a-running-clu.patch. Some \ncomments below:\n\nOn 19/01/2021 14:32, Daniel Gustafsson wrote:\n> + /*\n> + * Hold interrupts for the duration of xlogging to avoid the state of data\n> + * checksums changing during the processing which would later the premise\n> + * for xlogging hint bits.\n> + */\n\nSentence sense does not make.\n\n> @@ -904,6 +916,7 @@ static void SetLatestXTime(TimestampTz xtime);\n> static void SetCurrentChunkStartTime(TimestampTz xtime);\n> static void CheckRequiredParameterValues(void);\n> static void XLogReportParameters(void);\n> +static void XlogChecksums(ChecksumType new_type);\n> static void checkTimeLineSwitch(XLogRecPtr lsn, TimeLineID newTLI,\n> TimeLineID prevTLI);\n> static void LocalSetXLogInsertAllowed(void);\n\nSpelling: make it \"XLogChecksums\" for consistency.\n\n> /*\n> * DataChecksumsNeedWrite\n> *\t\tReturns whether data checksums must be written or not\n> *\n> * Returns true iff data checksums are enabled or are in the process of being\n> * enabled. In case data checksums are currently being enabled we must write\n> * the checksum even though it's not verified during this stage. Interrupts\n> * need to be held off by the caller to ensure that the returned state is\n> * valid for the duration of the intended processing.\n> */\n> bool\n> DataChecksumsNeedWrite(void)\n> {\n> \tAssert(InterruptHoldoffCount > 0);\n> \treturn (LocalDataChecksumVersion == PG_DATA_CHECKSUM_VERSION ||\n> \t\t\tLocalDataChecksumVersion == PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION ||\n> \t\t\tLocalDataChecksumVersion == PG_DATA_CHECKSUM_INPROGRESS_OFF_VERSION);\n> }\n\nCan you be more precise on the \"duration of the intended processing\"? It \nmeans, until you have actually written out the page, or something like \nthat, right? The similar explanation in DataChecksumsNeedVerify() is \neasier to understand. The two functions are similar, it would be good to \nphrase the comments similarly, so that you can quickly see the \ndifference between the two.\n\n> /*\n> * SetDataChecksumsOnInProgress\n> *\t\tSets the data checksum state to \"inprogress-on\" to enable checksums\n> *\n> * In order to start the process of enabling data checksums in a running\n> * cluster the data_checksum_version state must be changed to \"inprogress-on\".\n> * This state requires data checksums to be written but not verified. The state\n> * transition is performed in a critical section in order to provide crash\n> * safety, and checkpoints are held off. When the emitted procsignalbarrier\n> * has been absorbed by all backends we know that the cluster has started to\n> * enable data checksums.\n> */\n\nThe two \"in order\" are superfluous, it's more concise to say just \"To \nstart the process ...\" (I was made aware of that by J�rgen Purtz's \nrecent patches that removed a couple of \"in order\"s from the docs as \nunnecessary).\n\nIt's a bit confusing to talk about the critical section and \nprocsignalbarrier here. Does the caller need to wait for the \nprocsignalbarrier? No, that's just explaining what the function does \ninternally. Maybe move that explanation inside the function, and say \nhere something like \"This function blocks until all processes have \nacknowledged the state change\" or something like that.\n\n> /*\n> * SetDataChecksumsOn\n> *\t\tEnables data checksums cluster-wide\n> *\n> * Enabling data checksums is performed using two barriers, the first one\n> * sets the checksums state to \"inprogress-on\" (which is performed by\n> * SetDataChecksumsOnInProgress()) and the second one to \"on\" (performed here).\n> * During \"inprogress-on\", checksums are written but not verified. When all\n> * existing pages are guaranteed to have checksums, and all new pages will be\n> * initiated with checksums, the state can be changed to \"on\".\n> */\n\nPerhaps the explanation for how these SetDataChecksumsOn() and \nSetDataChecksumsOnInProgress() functions work together should be moved \nto one place. For example, explain both functions here at \nSetDataChecksumsOn(), and just have a \"see SetDataChecksumsOn()\" in the \nother function, or no comment at all if they're kept next to each other. \nAs it stands, you have to read both comments and piece together the the \nbig picture in your head. Maybe add a \"see datachecksumsworker.c\" here, \nsince there's a longer explanation of the overall mechanism there.\n\n> +/*\n> + * Disables checksums for the cluster, unless already disabled.\n> + *\n> + * Has immediate effect - the checksums are set to off right away.\n> + */\n> +Datum\n> +disable_data_checksums(PG_FUNCTION_ARGS)\n> +{\n> + if (!superuser())\n> + ereport(ERROR,\n> + (errmsg(\"must be superuser\")));\n> +\n> + StartDatachecksumsWorkerLauncher(false, 0, 0);\n> +\n> + PG_RETURN_BOOL(true);\n> +}\n\nThe documentation says \"Returns <literal>false</literal> in case data \nchecksums are disabled already\", but the function always returns true. \nThe enable_data_checksum() function also returns a constant 'true'; why \nnot make it void?\n\nThe \"has immediate effect\" comment seems wrong, given that it actually \nlaunches a worker process.\n\n> + /*\n> + * If the launcher is already started, the only operation we can perform\n> + * is to cancel it iff the user requested for checksums to be disabled.\n> + * That doesn't however mean that all other cases yield an error, as some\n> + * might be perfectly benevolent.\n> + */\n\nThis comment is a bit hard to understand. Maybe something like\n\n\"If the launcher is already started, we cannot launch a new one. But if \nthe user requested for checksums to be disabled, we can cancel it.\"\n\n> + if (DatachecksumsWorkerShmem->launcher_started)\n> + {\n> + if (DatachecksumsWorkerShmem->abort)\n> + {\n> + ereport(NOTICE,\n> + (errmsg(\"data checksum processing is concurrently being aborted, please retry\")));\n> +\n> + LWLockRelease(DatachecksumsWorkerLock);\n> + return;\n> + }\n\nIf it's being aborted, and the user requested to disable checksum, can \nwe leave out the NOTICE? I guess not, because the worker process won't \ncheck the 'abort' flag, if it's already finished processing all data pages.\n\n> + /*\n> + * If the launcher is started data checksums cannot be on or off, but\n> + * it may be in an inprogress state. Since the state transition may\n> + * not have happened yet (in case of rapidly initiated checksum enable\n> + * calls for example) we inspect the target state of the currently\n> + * running launcher.\n> + */\n\nThis comment contradicts itself. If the state transition has not \nhappened yet, then contrary to the first sentence, data checksums *are* \ncurrently on or off.\n\n> + if (enable_checksums)\n> + {\n> + /*\n> + * If we are asked to enable checksums when they are already being\n> + * enabled, there is nothing to do so exit.\n> + */\n> + if (DatachecksumsWorkerShmem->enable_checksums)\n> + {\n> + LWLockRelease(DatachecksumsWorkerLock);\n> + return;\n> + }\n> +\n> + /*\n> + * Disabling checksums is likely to be a very quick operation in\n> + * many cases so trying to abort it to save the checksums would\n> + * run the risk of race conditions.\n> + */\n> + else\n> + {\n> + ereport(NOTICE,\n> + (errmsg(\"data checksums are concurrently being disabled, please retry\")));\n> +\n> + LWLockRelease(DatachecksumsWorkerLock);\n> + return;\n> + }\n> +\n> + /* This should be unreachable */\n> + Assert(false);\n> + }\n> + else if (!enable_checksums)\n> + {\n> + /*\n> + * Data checksums are already being disabled, exit silently.\n> + */\n> + if (DataChecksumsOffInProgress())\n> + {\n> + LWLockRelease(DatachecksumsWorkerLock);\n> + return;\n> + }\n> +\n> + DatachecksumsWorkerShmem->abort = true;\n> + LWLockRelease(DatachecksumsWorkerLock);\n> + return;\n> + }\n\nThe Assert seems unnecessary. The \"if (!enable_checkums)\" also seems \nunnecessary, could be just \"else\".\n\n> + /*\n> + * The launcher is currently not running, so we need to query the system\n> + * data checksum state to determine how to proceed based on the requested\n> + * target state.\n> + */\n\n\"query the system\" makes me think \"checking the catalogs\" or similar, \nbut this just looks at a few variables in shared memory.\n\n> +/*\n> + * ShutdownDatachecksumsWorkerIfRunning\n> + * Request shutdown of the datachecksumsworker\n> + *\n> + * This does not turn off processing immediately, it signals the checksum\n> + * process to end when done with the current block.\n> + */\n> +void\n> +ShutdownDatachecksumsWorkerIfRunning(void)\n> +{\n> + LWLockAcquire(DatachecksumsWorkerLock, LW_EXCLUSIVE);\n> +\n> + /* If the launcher isn't started, there is nothing to shut down */\n> + if (DatachecksumsWorkerShmem->launcher_started)\n> + DatachecksumsWorkerShmem->abort = true;\n> +\n> + LWLockRelease(DatachecksumsWorkerLock);\n> +}\n\nThis function is unused.\n\n> +/*\n> + * launcher_cancel_handler\n> + *\n> + * Internal routine for reacting to SIGINT and flagging the worker to abort.\n> + * The worker won't be interrupted immediately but will check for abort flag\n> + * between each block in a relation.\n> + */\n> +static void\n> +launcher_cancel_handler(SIGNAL_ARGS)\n> +{\n> + LWLockAcquire(DatachecksumsWorkerLock, LW_EXCLUSIVE);\n> + DatachecksumsWorkerShmem->abort = true;\n> + LWLockRelease(DatachecksumsWorkerLock);\n> +}\n\nAcquiring an lwlock in signal handler is not safe.\n\nSince this is a signal handler, it might still get called after the \nprocess has finished processing, and has already set \nDatachecksumsWorkerShmem->launcher_started = false. That seems like an \nunexpected state.\n\n> +/*\n> + * WaitForAllTransactionsToFinish\n> + * Blocks awaiting all current transactions to finish\n> + *\n> + * Returns when all transactions which are active at the call of the function\n> + * have ended, or if the postmaster dies while waiting. If the postmaster dies\n> + * the abort flag will be set to indicate that the caller of this shouldn't\n> + * proceed.\n> + */\n\nThe caller of this function doesn't check the 'abort' flag AFAICS. I \nthink you could just use use WL_EXIT_ON_PM_DEATH to error out on \npostmaster death.\n\n> + while (true)\n> + {\n> + int processed_databases = 0;\n> +\n> + /*\n> + * Get a list of all databases to process. This may include databases\n> + * that were created during our runtime.\n> + *\n> + * Since a database can be created as a copy of any other database\n> + * (which may not have existed in our last run), we have to repeat\n> + * this loop until no new databases show up in the list. Since we wait\n> + * for all pre-existing transactions finish, this way we can be\n> + * certain that there are no databases left without checksums.\n> + */\n> + DatabaseList = BuildDatabaseList();\n\nI think it's unnecessary to wait out the transactions on the first \niteration of this loop. There must be at least one database, so there \nwill always be at least two iterations.\n\nI think it would be more clear to move the \nWaitForAllTransactionsToFinish() from BuildDatabaseList() to the callers.\n\n> @@ -3567,6 +3571,27 @@ RelationBuildLocalRelation(const char *relname,\n> relkind == RELKIND_MATVIEW)\n> RelationInitTableAccessMethod(rel);\n> \n> + /*\n> + * Set the data checksum state. Since the data checksum state can change at\n> + * any time, the fetched value might be out of date by the time the\n> + * relation is built. DataChecksumsNeedWrite returns true when data\n> + * checksums are: enabled; are in the process of being enabled (state:\n> + * \"inprogress-on\"); are in the process of being disabled (state:\n> + * \"inprogress-off\"). Since relhaschecksums is only used to track progress\n> + * when data checksums are being enabled, and going from disabled to\n> + * enabled will clear relhaschecksums before starting, it is safe to use\n> + * this value for a concurrent state transition to off.\n> + *\n> + * If DataChecksumsNeedWrite returns false, and is concurrently changed to\n> + * true then that implies that checksums are being enabled. Worst case,\n> + * this will lead to the relation being processed for checksums even though\n> + * each page written will have them already. Performing this last shortens\n> + * the window, but doesn't avoid it.\n> + */\n> + HOLD_INTERRUPTS();\n> + rel->rd_rel->relhaschecksums = DataChecksumsNeedWrite();\n> + RESUME_INTERRUPTS();\n> +\n> /*\n> * Okay to insert into the relcache hash table.\n> *\n\nI grepped for relhashcheckums, and concluded that the value in the \nrelcache isn't actually used for anything. Not so! In \nheap_create_with_catalog(), the actual pg_class row is constructed from \nthe relcache entry, so the value set in RelationBuildLocalRelation() \nfinds its way to pg_class. Perhaps it would be more clear to pass \nrelhachecksums directly as an argument to AddNewRelationTuple(). That \nway, the value in the relcache would be truly never used.\n\n- Heikki\n\n\n", "msg_date": "Fri, 22 Jan 2021 13:55:55 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On 22/01/2021 13:55, Heikki Linnakangas wrote:\n> I read through the latest patch,\n> v31-0001-Support-checksum-enable-disable-in-a-running-clu.patch. Some\n> comments below:\n\nOne more thing:\n\nIn SetRelationNumChecks(), you should use SearchSysCacheCopy1() to get a \nmodifiable copy of the tuple. Otherwise you modify the tuple in the \nrelcache as a side effect. Maybe that's harmless in this case, as the \n'relhaschecksums' value in the relcache isn't used for anything, but \nlet's be tidy.\n\n- Heikki\n\n\n", "msg_date": "Fri, 22 Jan 2021 14:21:45 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 22 Jan 2021, at 12:55, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> \n> I read through the latest patch, v31-0001-Support-checksum-enable-disable-in-a-running-clu.patch. Some comments below:\n\nThanks for reviewing! Attached is a v32 which address most of your comments,\nsee below.\n\n> On 19/01/2021 14:32, Daniel Gustafsson wrote:\n>> + /*\n>> + * Hold interrupts for the duration of xlogging to avoid the state of data\n>> + * checksums changing during the processing which would later the premise\n>> + * for xlogging hint bits.\n>> + */\n> \n> Sentence sense does not make.\n\nIndeed it doesn't, the \"later\" is a misspelled \"alter\". Essentially, the idea\nwith the comment is to explain that interrupts should be held during logging so\nthat the decision to log hintbits is valid for the duration of the logging.\nDoes changing to \"alter\" suffice? It's fixed like so in the attached, but\nperhaps there are better wordings for this.\n\n>> @@ -904,6 +916,7 @@ static void SetLatestXTime(TimestampTz xtime);\n>> static void SetCurrentChunkStartTime(TimestampTz xtime);\n>> static void CheckRequiredParameterValues(void);\n>> static void XLogReportParameters(void);\n>> +static void XlogChecksums(ChecksumType new_type);\n>> static void checkTimeLineSwitch(XLogRecPtr lsn, TimeLineID newTLI,\n>> TimeLineID prevTLI);\n>> static void LocalSetXLogInsertAllowed(void);\n> \n> Spelling: make it \"XLogChecksums\" for consistency.\n\nGood point, fixed.\n\n>> /*\n>> * DataChecksumsNeedWrite\n>> *\t\tReturns whether data checksums must be written or not\n>> *\n>> * Returns true iff data checksums are enabled or are in the process of being\n>> * enabled. In case data checksums are currently being enabled we must write\n>> * the checksum even though it's not verified during this stage. Interrupts\n>> * need to be held off by the caller to ensure that the returned state is\n>> * valid for the duration of the intended processing.\n>> */\n>> bool\n>> DataChecksumsNeedWrite(void)\n>> {\n>> \tAssert(InterruptHoldoffCount > 0);\n>> \treturn (LocalDataChecksumVersion == PG_DATA_CHECKSUM_VERSION ||\n>> \t\t\tLocalDataChecksumVersion == PG_DATA_CHECKSUM_INPROGRESS_ON_VERSION ||\n>> \t\t\tLocalDataChecksumVersion == PG_DATA_CHECKSUM_INPROGRESS_OFF_VERSION);\n>> }\n> \n> Can you be more precise on the \"duration of the intended processing\"? It means, until you have actually written out the page, or something like that, right? The similar explanation in DataChecksumsNeedVerify() is easier to understand. The two functions are similar, it would be good to phrase the comments similarly, so that you can quickly see the difference between the two.\n\nI've reworded this to (hopefully) be more clear, and to be more like the\ncomment for DataChecksumsNeedVerify.\n\n>> /*\n>> * SetDataChecksumsOnInProgress\n>> *\t\tSets the data checksum state to \"inprogress-on\" to enable checksums\n>> *\n>> * In order to start the process of enabling data checksums in a running\n>> * cluster the data_checksum_version state must be changed to \"inprogress-on\".\n>> * This state requires data checksums to be written but not verified. The state\n>> * transition is performed in a critical section in order to provide crash\n>> * safety, and checkpoints are held off. When the emitted procsignalbarrier\n>> * has been absorbed by all backends we know that the cluster has started to\n>> * enable data checksums.\n>> */\n> \n> The two \"in order\" are superfluous, it's more concise to say just \"To start the process ...\" (I was made aware of that by Jürgen Purtz's recent patches that removed a couple of \"in order\"s from the docs as unnecessary).\n\nAgreed, that's better.\n\n> It's a bit confusing to talk about the critical section and procsignalbarrier here. Does the caller need to wait for the procsignalbarrier? No, that's just explaining what the function does internally. Maybe move that explanation inside the function, and say here something like \"This function blocks until all processes have acknowledged the state change\" or something like that.\n\nFixed.\n\n>> /*\n>> * SetDataChecksumsOn\n>> *\t\tEnables data checksums cluster-wide\n>> *\n>> * Enabling data checksums is performed using two barriers, the first one\n>> * sets the checksums state to \"inprogress-on\" (which is performed by\n>> * SetDataChecksumsOnInProgress()) and the second one to \"on\" (performed here).\n>> * During \"inprogress-on\", checksums are written but not verified. When all\n>> * existing pages are guaranteed to have checksums, and all new pages will be\n>> * initiated with checksums, the state can be changed to \"on\".\n>> */\n> \n> Perhaps the explanation for how these SetDataChecksumsOn() and SetDataChecksumsOnInProgress() functions work together should be moved to one place. For example, explain both functions here at SetDataChecksumsOn(), and just have a \"see SetDataChecksumsOn()\" in the other function, or no comment at all if they're kept next to each other. As it stands, you have to read both comments and piece together the the big picture in your head. Maybe add a \"see datachecksumsworker.c\" here, since there's a longer explanation of the overall mechanism there.\n\nFixed. I did keep both comments since the function are too long to fit the\ncomment and the code on screen, but refer to one from the other.\n\n>> +/*\n>> + * Disables checksums for the cluster, unless already disabled.\n>> + *\n>> + * Has immediate effect - the checksums are set to off right away.\n>> + */\n>> +Datum\n>> +disable_data_checksums(PG_FUNCTION_ARGS)\n>> +{\n>> + if (!superuser())\n>> + ereport(ERROR,\n>> + (errmsg(\"must be superuser\")));\n>> +\n>> + StartDatachecksumsWorkerLauncher(false, 0, 0);\n>> +\n>> + PG_RETURN_BOOL(true);\n>> +}\n> \n> The documentation says \"Returns <literal>false</literal> in case data checksums are disabled already\", but the function always returns true.\n\nFixed.\n\n> The enable_data_checksum() function also returns a constant 'true'; why not make it void?\n\nThese functions were void until v20 of this patch when Robert correctly pointed\nout that using ereport to communicate status was a poor choice (there were\nNOTICEs IIRC). v23 however rolled back all status checking in response to a\nreview by you, leaving the functions to only call the worker. The returnvalue\nwas however not changed back to void at that point which would've been the\nreasonable choice. Fixed.\n\n> The \"has immediate effect\" comment seems wrong, given that it actually launches a worker process.\n\nFixed.\n\n>> + /*\n>> + * If the launcher is already started, the only operation we can perform\n>> + * is to cancel it iff the user requested for checksums to be disabled.\n>> + * That doesn't however mean that all other cases yield an error, as some\n>> + * might be perfectly benevolent.\n>> + */\n> \n> This comment is a bit hard to understand. Maybe something like\n> \n> \"If the launcher is already started, we cannot launch a new one. But if the user requested for checksums to be disabled, we can cancel it.\"\n\nAgreed, thats better. Fixed.\n\n>> + if (DatachecksumsWorkerShmem->launcher_started)\n>> + {\n>> + if (DatachecksumsWorkerShmem->abort)\n>> + {\n>> + ereport(NOTICE,\n>> + (errmsg(\"data checksum processing is concurrently being aborted, please retry\")));\n>> +\n>> + LWLockRelease(DatachecksumsWorkerLock);\n>> + return;\n>> + }\n> \n> If it's being aborted, and the user requested to disable checksum, can we leave out the NOTICE? I guess not, because the worker process won't check the 'abort' flag, if it's already finished processing all data pages.\n\nCorrect, since we might otherwise silently not disable checksums on a request\nto do so.\n\n>> + /*\n>> + * If the launcher is started data checksums cannot be on or off, but\n>> + * it may be in an inprogress state. Since the state transition may\n>> + * not have happened yet (in case of rapidly initiated checksum enable\n>> + * calls for example) we inspect the target state of the currently\n>> + * running launcher.\n>> + */\n> \n> This comment contradicts itself. If the state transition has not happened yet, then contrary to the first sentence, data checksums *are* currently on or off.\n\nYes, indeed. I've reworded this comment but I'm not sure it's much of an\nimprovement I'm afraid.\n\n>> + if (enable_checksums)\n>> + {\n>> + /*\n>> + * If we are asked to enable checksums when they are already being\n>> + * enabled, there is nothing to do so exit.\n>> + */\n>> + if (DatachecksumsWorkerShmem->enable_checksums)\n>> + {\n>> + LWLockRelease(DatachecksumsWorkerLock);\n>> + return;\n>> + }\n>> +\n>> + /*\n>> + * Disabling checksums is likely to be a very quick operation in\n>> + * many cases so trying to abort it to save the checksums would\n>> + * run the risk of race conditions.\n>> + */\n>> + else\n>> + {\n>> + ereport(NOTICE,\n>> + (errmsg(\"data checksums are concurrently being disabled, please retry\")));\n>> +\n>> + LWLockRelease(DatachecksumsWorkerLock);\n>> + return;\n>> + }\n>> +\n>> + /* This should be unreachable */\n>> + Assert(false);\n>> + }\n>> + else if (!enable_checksums)\n>> + {\n>> + /*\n>> + * Data checksums are already being disabled, exit silently.\n>> + */\n>> + if (DataChecksumsOffInProgress())\n>> + {\n>> + LWLockRelease(DatachecksumsWorkerLock);\n>> + return;\n>> + }\n>> +\n>> + DatachecksumsWorkerShmem->abort = true;\n>> + LWLockRelease(DatachecksumsWorkerLock);\n>> + return;\n>> + }\n> \n> The Assert seems unnecessary. The \"if (!enable_checkums)\" also seems unnecessary, could be just \"else\".\n\nFixed.\n\n>> + /*\n>> + * The launcher is currently not running, so we need to query the system\n>> + * data checksum state to determine how to proceed based on the requested\n>> + * target state.\n>> + */\n> \n> \"query the system\" makes me think \"checking the catalogs\" or similar, but this just looks at a few variables in shared memory.\n\nReworded.\n\n>> +/*\n>> + * ShutdownDatachecksumsWorkerIfRunning\n>> + * Request shutdown of the datachecksumsworker\n>> + *\n> \n> This function is unused.\n\nRemoved.\n\n>> +/*\n>> + * launcher_cancel_handler\n>> + *\n>> + * Internal routine for reacting to SIGINT and flagging the worker to abort.\n>> + * The worker won't be interrupted immediately but will check for abort flag\n>> + * between each block in a relation.\n>> + */\n>> +static void\n>> +launcher_cancel_handler(SIGNAL_ARGS)\n>> +{\n>> + LWLockAcquire(DatachecksumsWorkerLock, LW_EXCLUSIVE);\n>> + DatachecksumsWorkerShmem->abort = true;\n>> + LWLockRelease(DatachecksumsWorkerLock);\n>> +}\n> \n> Acquiring an lwlock in signal handler is not safe.\n> \n> Since this is a signal handler, it might still get called after the process has finished processing, and has already set DatachecksumsWorkerShmem->launcher_started = false. That seems like an unexpected state.\n\nGood point, I've fixed this to use a proper signal handler flag. While doing\nso I realized there was a race window when checksums were disabled while the\nworker was running, but after it had processed the final buffer. Since the\nabort flag was only checked during buffer processing it could be missed leading\nto the worker ending with checksums enabled when they should be disabled. This\nis likely to be much more common in the TAP tests than in real production use,\nwhich is good since it was easy to trigger. The attached fixes this by\nre-checking the abort flag and I am no longer able to trigger the window during\ntests.\n\n>> +/*\n>> + * WaitForAllTransactionsToFinish\n>> + * Blocks awaiting all current transactions to finish\n>> + *\n>> + * Returns when all transactions which are active at the call of the function\n>> + * have ended, or if the postmaster dies while waiting. If the postmaster dies\n>> + * the abort flag will be set to indicate that the caller of this shouldn't\n>> + * proceed.\n>> + */\n> \n> The caller of this function doesn't check the 'abort' flag AFAICS. I think you could just use use WL_EXIT_ON_PM_DEATH to error out on postmaster death.\n\nGood point, that simplifies the code. It's erroring out in the same way as\nother checks for postmaster death.\n\t\n>> + while (true)\n>> + {\n>> + int processed_databases = 0;\n>> +\n>> + /*\n>> + * Get a list of all databases to process. This may include databases\n>> + * that were created during our runtime.\n>> + *\n>> + * Since a database can be created as a copy of any other database\n>> + * (which may not have existed in our last run), we have to repeat\n>> + * this loop until no new databases show up in the list. Since we wait\n>> + * for all pre-existing transactions finish, this way we can be\n>> + * certain that there are no databases left without checksums.\n>> + */\n>> + DatabaseList = BuildDatabaseList();\n> \n> I think it's unnecessary to wait out the transactions on the first iteration of this loop. There must be at least one database, so there will always be at least two iterations.\n> \n> I think it would be more clear to move the WaitForAllTransactionsToFinish() from BuildDatabaseList() to the callers.\n\nI've tried this in the attached. It does increase the window between waiting\nfor transactions to finish and grabbing the list, but that might be negligable?\n\n>> @@ -3567,6 +3571,27 @@ RelationBuildLocalRelation(const char *relname,\n>> relkind == RELKIND_MATVIEW)\n>> RelationInitTableAccessMethod(rel);\n>> + /*\n>> + * Set the data checksum state. Since the data checksum state can change at\n>> + * any time, the fetched value might be out of date by the time the\n>> + * relation is built. DataChecksumsNeedWrite returns true when data\n>> + * checksums are: enabled; are in the process of being enabled (state:\n>> + * \"inprogress-on\"); are in the process of being disabled (state:\n>> + * \"inprogress-off\"). Since relhaschecksums is only used to track progress\n>> + * when data checksums are being enabled, and going from disabled to\n>> + * enabled will clear relhaschecksums before starting, it is safe to use\n>> + * this value for a concurrent state transition to off.\n>> + *\n>> + * If DataChecksumsNeedWrite returns false, and is concurrently changed to\n>> + * true then that implies that checksums are being enabled. Worst case,\n>> + * this will lead to the relation being processed for checksums even though\n>> + * each page written will have them already. Performing this last shortens\n>> + * the window, but doesn't avoid it.\n>> + */\n>> + HOLD_INTERRUPTS();\n>> + rel->rd_rel->relhaschecksums = DataChecksumsNeedWrite();\n>> + RESUME_INTERRUPTS();\n>> +\n>> /*\n>> * Okay to insert into the relcache hash table.\n>> *\n> \n> I grepped for relhashcheckums, and concluded that the value in the relcache isn't actually used for anything. Not so! In heap_create_with_catalog(), the actual pg_class row is constructed from the relcache entry, so the value set in RelationBuildLocalRelation() finds its way to pg_class. Perhaps it would be more clear to pass relhachecksums directly as an argument to AddNewRelationTuple(). That way, the value in the relcache would be truly never used.\n\nI might be thick (or undercaffeinated) but I'm not sure I follow.\nAddNewRelationTuple calls InsertPgClassTuple which in turn avoids the relcache\nentry.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/", "msg_date": "Tue, 26 Jan 2021 22:00:52 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On 22/01/2021 14:21, Heikki Linnakangas wrote:\n> On 22/01/2021 13:55, Heikki Linnakangas wrote:\n>> I read through the latest patch,\n>> v31-0001-Support-checksum-enable-disable-in-a-running-clu.patch. Some\n>> comments below:\n> \n> One more thing:\n> \n> In SetRelationNumChecks(), you should use SearchSysCacheCopy1() to get a\n> modifiable copy of the tuple. Otherwise you modify the tuple in the\n> relcache as a side effect. Maybe that's harmless in this case, as the\n> 'relhaschecksums' value in the relcache isn't used for anything, but\n> let's be tidy.\n\nSorry, I meant SetRelHasChecksums. There is no SetRelationNumChecks \nfunction, I don't know where I got that from.\n\n- Heikki\n\n\n", "msg_date": "Wed, 27 Jan 2021 00:37:22 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 26 Jan 2021, at 23:37, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> \n> On 22/01/2021 14:21, Heikki Linnakangas wrote:\n>> On 22/01/2021 13:55, Heikki Linnakangas wrote:\n>>> I read through the latest patch,\n>>> v31-0001-Support-checksum-enable-disable-in-a-running-clu.patch. Some\n>>> comments below:\n>> One more thing:\n>> In SetRelationNumChecks(), you should use SearchSysCacheCopy1() to get a\n>> modifiable copy of the tuple. Otherwise you modify the tuple in the\n>> relcache as a side effect. Maybe that's harmless in this case, as the\n>> 'relhaschecksums' value in the relcache isn't used for anything, but\n>> let's be tidy.\n> \n> Sorry, I meant SetRelHasChecksums. There is no SetRelationNumChecks function, I don't know where I got that from.\n\nAh, that makes more sense, you had me confused there for a bit =) Fixed in\nattached v33 which also have been through another pgindent and pgperltidy run.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/", "msg_date": "Wed, 27 Jan 2021 12:19:01 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "Revisiting an issue we discussed earlier:\n\nOn 25/11/2020 15:20, Daniel Gustafsson wrote:\n> On 23 Nov 2020, at 18:36, Heikki Linnakangas <hlinnaka(at)iki(dot)fi> wrote:\n>> On 17/11/2020 10:56, Daniel Gustafsson wrote:\n>>> I've reworked this in the attached such that the enable_ and\n>>> disable_ functions merely call into the launcher with the desired\n>>> outcome, and the launcher is responsible for figuring out the\n>>> rest. The datachecksumworker is now the sole place which\n>>> initiates a state transfer.\n>> \n>> Well, you still fill the DatachecksumsWorkerShmem->operations array\n>> in the backend process that launches the datacheckumworker, not in\n>> the worker process. I find that still a bit surprising, but I\n>> believe it works.\n> \n> I'm open to changing it in case there are strong opinions, it just\n> seemed the most natural to me.\n\nThis kept bothering me, so I spent a while hacking this to my liking. \nThe attached patch moves the code to fill in 'operations' from the \nbackend to the launcher, so that the pg_enable/disable_checksums() call \nnow truly just stores the desired state, checksum on or off, in shared \nmemory, and launches the launcher process. The launcher process figures \nout how to get to the desired state. This removes the couple of corner \ncases that previously emitted a NOTICE about the processing being \nconcurrently disabled or aborted. What do you think? I haven't done much \ntesting, so if you adopt this approach, please check if I broke \nsomething in the process.\n\nThis changes the way the abort works. If the \npg_enable/disable_checksums() is called, while the launcher is already \nbusy changing the state, pg_enable/disable_checksums() will just set the \nnew desired state in shared memory anyway. The launcher process will \nnotice that the target state changed some time later, and restart from \nscratch.\n\nA couple of other issues came up while doing that:\n\n- AbortProcessing() has two callers, one in code that runs in the \nlauncher process, and another one in code that runs in the worker \nprocess. Is it really safe to use from the worker process? Calling \nProcessAllDatabases() in the worker seems sketchy. (This is moot in this \nnew patch version, as I removed AbortProcessing() altogether)\n\n- Is it possible that the worker keeps running after the launcher has \nalready exited, e.g. because of an ERROR or SIGTERM? If you then quickly \ncall pg_enable_checksums() again, can you end up with two workers \nrunning at the same time? Is that bad?\n\nOn 26/01/2021 23:00, Daniel Gustafsson wrote:\n>> On 22 Jan 2021, at 12:55, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>>> @@ -3567,6 +3571,27 @@ RelationBuildLocalRelation(const char *relname,\n>>> relkind == RELKIND_MATVIEW)\n>>> RelationInitTableAccessMethod(rel);\n>>> + /*\n>>> + * Set the data checksum state. Since the data checksum state can change at\n>>> + * any time, the fetched value might be out of date by the time the\n>>> + * relation is built. DataChecksumsNeedWrite returns true when data\n>>> + * checksums are: enabled; are in the process of being enabled (state:\n>>> + * \"inprogress-on\"); are in the process of being disabled (state:\n>>> + * \"inprogress-off\"). Since relhaschecksums is only used to track progress\n>>> + * when data checksums are being enabled, and going from disabled to\n>>> + * enabled will clear relhaschecksums before starting, it is safe to use\n>>> + * this value for a concurrent state transition to off.\n>>> + *\n>>> + * If DataChecksumsNeedWrite returns false, and is concurrently changed to\n>>> + * true then that implies that checksums are being enabled. Worst case,\n>>> + * this will lead to the relation being processed for checksums even though\n>>> + * each page written will have them already. Performing this last shortens\n>>> + * the window, but doesn't avoid it.\n>>> + */\n>>> + HOLD_INTERRUPTS();\n>>> + rel->rd_rel->relhaschecksums = DataChecksumsNeedWrite();\n>>> + RESUME_INTERRUPTS();\n>>> +\n>>> /*\n>>> * Okay to insert into the relcache hash table.\n>>> *\n>>\n>> I grepped for relhashcheckums, and concluded that the value in the\n>> relcache isn't actually used for anything. Not so! In\n>> heap_create_with_catalog(), the actual pg_class row is constructed\n>> from the relcache entry, so the value set in\n>> RelationBuildLocalRelation() finds its way to pg_class. Perhaps it\n>> would be more clear to pass relhachecksums directly as an argument\n>> to AddNewRelationTuple(). That way, the value in the relcache would\n>> be truly never used.\n> \n> I might be thick (or undercaffeinated) but I'm not sure I follow. \n> AddNewRelationTuple calls InsertPgClassTuple which in turn avoids the\n> relcache entry.\n\nAh, you're right, I misread AddNewRelationTuple. That means that the \nrelhaschecksums field in the relcache is never used? That's a clear \nrule. The changes to formrdesc() and RelationBuildLocalRelation() seem \nunnecessary then, we can always initialize relhaschecksums to false in \nthe relcache.\n\n- Heikki", "msg_date": "Wed, 27 Jan 2021 17:37:52 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 27 Jan 2021, at 16:37, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> \n> Revisiting an issue we discussed earlier:\n> \n> On 25/11/2020 15:20, Daniel Gustafsson wrote:\n>> On 23 Nov 2020, at 18:36, Heikki Linnakangas <hlinnaka(at)iki(dot)fi> wrote:\n>>> On 17/11/2020 10:56, Daniel Gustafsson wrote:\n>>>> I've reworked this in the attached such that the enable_ and\n>>>> disable_ functions merely call into the launcher with the desired\n>>>> outcome, and the launcher is responsible for figuring out the\n>>>> rest. The datachecksumworker is now the sole place which\n>>>> initiates a state transfer.\n>>> Well, you still fill the DatachecksumsWorkerShmem->operations array\n>>> in the backend process that launches the datacheckumworker, not in\n>>> the worker process. I find that still a bit surprising, but I\n>>> believe it works.\n>> I'm open to changing it in case there are strong opinions, it just\n>> seemed the most natural to me.\n> \n> This kept bothering me, so I spent a while hacking this to my liking. The attached patch moves the code to fill in 'operations' from the backend to the launcher, so that the pg_enable/disable_checksums() call now truly just stores the desired state, checksum on or off, in shared memory, and launches the launcher process. The launcher process figures out how to get to the desired state. This removes the couple of corner cases that previously emitted a NOTICE about the processing being concurrently disabled or aborted. What do you think?\n\nI like it, it does avoid a few edgecases, while some are moved around (more on\nthat below) yielding easier to read code. This wasn't really how I thought you\nwanted it when we talked about this, so I'm very glad to see it in code since I\nnow get what you were saying. Thanks!\n\n> I haven't done much testing, so if you adopt this approach, please check if I broke something in the process.\n\nI think you broke restarts: the enable_checksums variable wasn't populated so\nthe restart seemed to fail to set the right operations. Also, the false return\ncan now mean an actual failure as well as an abort case for a restart. I've\ndone a quick change to look for an updated state, but that doesn't cover the\ncase when processing fails *and* a new state has been set. Maybe the best\nsolution is to change return type for processing to int's such that the three\ncases (failure, abort, success) can be returned?\n\nAlso, this fails on assertion for me when checking the current state since\ninterrupts aren't held off. I have a feeling it should've done that in my\nversion too as I look at it? The attached holds off interrutps to pass that\n(we clearly don't want a new state while we decide on operations anyways).\n\nThe tests in src/test/checksum were reliably failing on these for me but pass\nwith the attached 0002 applied.\n\n> This changes the way the abort works. If the pg_enable/disable_checksums() is called, while the launcher is already busy changing the state, pg_enable/disable_checksums() will just set the new desired state in shared memory anyway. The launcher process will notice that the target state changed some time later, and restart from scratch.\n\nThe \"notice period\" is the same as before though, unless I'm missing something.\n\n> A couple of other issues came up while doing that:\n> \n> - AbortProcessing() has two callers, one in code that runs in the launcher process, and another one in code that runs in the worker process. Is it really safe to use from the worker process? Calling ProcessAllDatabases() in the worker seems sketchy. (This is moot in this new patch version, as I removed AbortProcessing() altogether)\n\nI think it was safe, but I agree that this version is a lot cleaner so it is as\nyou say moot.\n\n> - Is it possible that the worker keeps running after the launcher has already exited, e.g. because of an ERROR or SIGTERM? If you then quickly call pg_enable_checksums() again, can you end up with two workers running at the same time? Is that bad?\n\nTrue, I think there is a window for when that could happen, but worst case\nshould be that a database is checksummed twice?\n\n> On 26/01/2021 23:00, Daniel Gustafsson wrote:\n>>> On 22 Jan 2021, at 12:55, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>>>> @@ -3567,6 +3571,27 @@ RelationBuildLocalRelation(const char *relname,\n>>>> relkind == RELKIND_MATVIEW)\n>>>> RelationInitTableAccessMethod(rel);\n>>>> + /*\n>>>> + * Set the data checksum state. Since the data checksum state can change at\n>>>> + * any time, the fetched value might be out of date by the time the\n>>>> + * relation is built. DataChecksumsNeedWrite returns true when data\n>>>> + * checksums are: enabled; are in the process of being enabled (state:\n>>>> + * \"inprogress-on\"); are in the process of being disabled (state:\n>>>> + * \"inprogress-off\"). Since relhaschecksums is only used to track progress\n>>>> + * when data checksums are being enabled, and going from disabled to\n>>>> + * enabled will clear relhaschecksums before starting, it is safe to use\n>>>> + * this value for a concurrent state transition to off.\n>>>> + *\n>>>> + * If DataChecksumsNeedWrite returns false, and is concurrently changed to\n>>>> + * true then that implies that checksums are being enabled. Worst case,\n>>>> + * this will lead to the relation being processed for checksums even though\n>>>> + * each page written will have them already. Performing this last shortens\n>>>> + * the window, but doesn't avoid it.\n>>>> + */\n>>>> + HOLD_INTERRUPTS();\n>>>> + rel->rd_rel->relhaschecksums = DataChecksumsNeedWrite();\n>>>> + RESUME_INTERRUPTS();\n>>>> +\n>>>> /*\n>>>> * Okay to insert into the relcache hash table.\n>>>> *\n>>> \n>>> I grepped for relhashcheckums, and concluded that the value in the\n>>> relcache isn't actually used for anything. Not so! In\n>>> heap_create_with_catalog(), the actual pg_class row is constructed\n>>> from the relcache entry, so the value set in\n>>> RelationBuildLocalRelation() finds its way to pg_class. Perhaps it\n>>> would be more clear to pass relhachecksums directly as an argument\n>>> to AddNewRelationTuple(). That way, the value in the relcache would\n>>> be truly never used.\n>> I might be thick (or undercaffeinated) but I'm not sure I follow. AddNewRelationTuple calls InsertPgClassTuple which in turn avoids the\n>> relcache entry.\n> \n> Ah, you're right, I misread AddNewRelationTuple. That means that the relhaschecksums field in the relcache is never used? That's a clear rule. The changes to formrdesc() and RelationBuildLocalRelation() seem unnecessary then, we can always initialize relhaschecksums to false in the relcache.\n\nThey probably are, but should they be kept as a just-in-case for future hackery\nwhich may assume the relcache is at all points correct?\n\nI've attached my changes as 0002 here on top of your patch, what do you think\nabout those? There are some commentfixups as well, some stemming from your\npatch and some from much earlier versions that I just hadn't seen until now.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/", "msg_date": "Fri, 29 Jan 2021 00:12:54 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "The previous v35 had a tiny conflict in pg_class.h, the attached v36 (which is\na squash of the 2 commits in v35) fixes that. No other changes are introduced\nin this version.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/", "msg_date": "Wed, 3 Feb 2021 17:15:16 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "(I may have said this before, but) My overall high-level impression of \nthis patch is that it's really cmmplex for a feature that you use maybe \nonce in the lifetime of a cluster. I'm happy to review but I'm not \nplanning to commit this myself. I don't object if some other committer \npicks this up (Magnus?).\n\nNow to the latest patch version:\n\nOn 03/02/2021 18:15, Daniel Gustafsson wrote:\n> The previous v35 had a tiny conflict in pg_class.h, the attached v36 (which is\n> a squash of the 2 commits in v35) fixes that. No other changes are introduced\n> in this version.\n\n\n> \t/*\n> \t * Check to see if my copy of RedoRecPtr is out of date. If so, may have\n> \t * to go back and have the caller recompute everything. This can only\n> \t * happen just after a checkpoint, so it's better to be slow in this case\n> \t * and fast otherwise.\n> \t *\n> \t * Also check to see if fullPageWrites or forcePageWrites was just turned\n> \t * on, or if we are in the process of enabling checksums in the cluster;\n> \t * if we weren't already doing full-page writes then go back and recompute.\n> \t *\n> \t * If we aren't doing full-page writes then RedoRecPtr doesn't actually\n> \t * affect the contents of the XLOG record, so we'll update our local copy\n> \t * but not force a recomputation. (If doPageWrites was just turned off,\n> \t * we could recompute the record without full pages, but we choose not to\n> \t * bother.)\n> \t */\n> \tif (RedoRecPtr != Insert->RedoRecPtr)\n> \t{\n> \t\tAssert(RedoRecPtr < Insert->RedoRecPtr);\n> \t\tRedoRecPtr = Insert->RedoRecPtr;\n> \t}\n> \tdoPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites || DataChecksumsOnInProgress());\n\nWhy does this use DataChecksumsOnInProgress() instead of \nDataChecksumsNeedWrite()? If checksums are enabled, you always need \nfull-page writes, don't you? If not, then why is it needed in the \ninprogress-on state?\n\nWe also set doPageWrites in InitXLOGAccess(). That should match the \ncondition above (although it doesn't matter for correctness).\n\n> /*\n> * DataChecksumsNeedVerify\n> *\t\tReturns whether data checksums must be verified or not\n> *\n> * Data checksums are only verified if they are fully enabled in the cluster.\n> * During the \"inprogress-on\" and \"inprogress-off\" states they are only\n> * updated, not verified (see datachecksumsworker.c for a longer discussion).\n> *\n> * This function is intended for callsites which have read data and are about\n> * to perform checksum validation based on the result of this. To avoid the\n> * the risk of the checksum state changing between reading and performing the\n> * validation (or not), interrupts must be held off. This implies that calling\n> * this function must be performed as close to the validation call as possible\n> * to keep the critical section short. This is in order to protect against\n> * time of check/time of use situations around data checksum validation.\n> */\n> bool\n> DataChecksumsNeedVerify(void)\n> {\n> \tAssert(InterruptHoldoffCount > 0);\n> \treturn (LocalDataChecksumVersion == PG_DATA_CHECKSUM_VERSION);\n> }\n\nWhat exactly is the intended call pattern here? Something like this?\n\nsmgrread() a data page\nHOLD_INTERRUPTS();\nif (DataChecksumsNeedVerify())\n{\n if (pg_checksum_page((char *) page, blkno) != expected)\n elog(ERROR, \"bad checksum\");\n}\nRESUME_INTERRUPTS();\n\nThat seems to be what the code currently does. What good does holding \ninterrupts do here? If checksums were not fully enabled at the \nsmgrread() call, the page might have incorrect checksums, and if the \nstate transitions from inprogress-on to on between the smggread() call \nand the DataChecksumsNeedVerify() call, you'll get an error. I think you \nneed to hold the interrupts *before* the smgrread() call.\n\n> /*\n> * Set checksum for a page in private memory.\n> *\n> * This must only be used when we know that no other process can be modifying\n> * the page buffer.\n> */\n> void\n> PageSetChecksumInplace(Page page, BlockNumber blkno)\n> {\n> \tHOLD_INTERRUPTS();\n> \t/* If we don't need a checksum, just return */\n> \tif (PageIsNew(page) || !DataChecksumsNeedWrite())\n> \t{\n> \t\tRESUME_INTERRUPTS();\n> \t\treturn;\n> \t}\n> \n> \t((PageHeader) page)->pd_checksum = pg_checksum_page((char *) page, blkno);\n> \tRESUME_INTERRUPTS();\n> }\n\nThe checksums state might change just after this call, before the caller \nhas actually performed the smgrwrite() or smgrextend() call. The caller \nneeds to hold interrupts across this function and the \nsmgrwrite/smgrextend() call. It is a bad idea to HOLD_INTERRUPTS() here, \nbecause that just masks bugs where the caller isn't holding the \ninterrupts. Same in PageSetChecksumCopy().\n\n- Heikki\n\n\n", "msg_date": "Tue, 9 Feb 2021 10:54:50 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Tue, Feb 09, 2021 at 10:54:50AM +0200, Heikki Linnakangas wrote:\n> (I may have said this before, but) My overall high-level impression of this\n> patch is that it's really cmmplex for a feature that you use maybe once in\n> the lifetime of a cluster. I'm happy to review but I'm not planning to\n> commit this myself. I don't object if some other committer picks this up\n> (Magnus?).\n\nI was just looking at the latest patch set as a matter of curiosity,\nand I have a shared feeling. I think that this is a lot of\ncomplication in-core for what would be a one-time operation,\nparticularly knowing that there are other ways to do it already with\nthe offline checksum tool, even if that is more costly:\n- Involve logical replication after initializing the new instance with\n--data-checksums, or in an upgrade scenatio with pg_upgrade.\n- Involve physical replication: stop the standby cleanly, enable\nchecksums on it and do a switchover.\n\nAnother thing we could do is to improve pg_checksums with a parallel\nmode. The main design question would be how to distribute the I/O,\nand that would mean balancing at least across tablespaces.\n--\nMichael", "msg_date": "Wed, 10 Feb 2021 15:06:45 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "Hi,\n\nAm Mittwoch, den 10.02.2021, 15:06 +0900 schrieb Michael Paquier:\n> On Tue, Feb 09, 2021 at 10:54:50AM +0200, Heikki Linnakangas wrote:\n> > (I may have said this before, but) My overall high-level impression of this\n> > patch is that it's really cmmplex for a feature that you use maybe once in\n> > the lifetime of a cluster. I'm happy to review but I'm not planning to\n> > commit this myself. I don't object if some other committer picks this up\n> > (Magnus?).\n> \n> I was just looking at the latest patch set as a matter of curiosity,\n> and I have a shared feeling. \n\nI think this still would be a useful feature; not least for the online\ndeactivation - having to shut down the instance is sometimes just not an\noption in production, even for just a few seconds.\n\nHowever, there is also the shoot-the-whole-database-into-WAL (at least,\nthat is what happens, AIUI) issue which has not been discussed that much\neither, the patch allows throttling, but I think the impact on actual\nproduction workloads are not very clear yet.\n\n> I think that this is a lot of complication in-core for what would be a\n> one-time operation, particularly knowing that there are other ways to\n> do it already with the offline checksum tool, even if that is more\n> costly: \n> - Involve logical replication after initializing the new instance with\n> --data-checksums, or in an upgrade scenatio with pg_upgrade.\n\nLogical replication is still somewhat unpractical for such a (possibly)\nroutine task, and I don't understand your pg_upgrade scenario, can\nexpand on that a bit?\n\n> - Involve physical replication: stop the standby cleanly, enable\n> checksums on it and do a switchover.\n\nI would like to focus on this, so I changed the subject in order not to\nderail the online acivation patch thread.\n\nIf this is something we support, then we should document it.\n\nI have to admit that this possiblity escaped me when we first committed\noffline (de)activation, it was brought to my attention via \nhttps://twitter.com/samokhvalov/status/1281312586219188224 and the\nfollowing discussion.\n\nSo if we think this (to recap: shut down the standby, run pg_checksums\non it, start it up again, wait until it is back in sync, then\nswitchover) is a safe way to activate checksums on a streaming\nreplication setup, then we should document it I think. However, I have\nonly seen sorta hand-waiving on this so far and no deeper analysis of\nwhat could possibly go wrong (but doesn't).\n\nAnybody did some further work/tests on this and/or has something written\nup to contribute to the documentation? Or do we think this is not\nappropriate to document? I think once we agree this is safe, it is not\nmore complicated than the rsync-the-standby-after-pg_upgrade recipe we\ndid document.\n\n> Another thing we could do is to improve pg_checksums with a parallel\n> mode. The main design question would be how to distribute the I/O,\n> and that would mean balancing at least across tablespaces.\n\nRight. I thought about this a while ago, but didn't have time to work on\nit so far.\n\n\nMichael\n\n-- \nMichael Banck\nProjektleiter / Senior Berater\nTel.: +49 2166 9901-171\nFax: +49 2166 9901-100\nEmail: michael.banck@credativ.de\n\ncredativ GmbH, HRB Mönchengladbach 12080\nUSt-ID-Nummer: DE204566209\nTrompeterallee 108, 41189 Mönchengladbach\nGeschäftsführung: Dr. Michael Meskes, Jörg Folz, Sascha Heuer\n\nUnser Umgang mit personenbezogenen Daten unterliegt\nfolgenden Bestimmungen: https://www.credativ.de/datenschutz\n\n\n\n", "msg_date": "Wed, 10 Feb 2021 09:06:35 +0100", "msg_from": "Michael Banck <michael.banck@credativ.de>", "msg_from_op": false, "msg_subject": "Offline activation of checksums via standby switchover (was: Online\n checksums patch - once again)" }, { "msg_contents": "On Tue, Feb 9, 2021 at 9:54 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> (I may have said this before, but) My overall high-level impression of\n> this patch is that it's really cmmplex for a feature that you use maybe\n> once in the lifetime of a cluster. I'm happy to review but I'm not\n> planning to commit this myself. I don't object if some other committer\n> picks this up (Magnus?).\n\nA fairly large amount of this complexity comes out of the fact that it\nnow supports restarting and tracks checksums on a per-table basis. We\nskipped this in the original patch for exactly this reason (that's not\nto say there isn't a fair amount of complexity even without it, but it\ndid substantially i increase both the size and the complexity of the\npatch), but in the review of that i was specifically asked for having\nthat added. I personally don't think it's worth that complexity but at\nthe time that seemed to be a pretty strong argument. So I'm not\nentirely sure how to move forward with that...\n\nis your impression that it would still be too complicated, even without that?\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/\n Work: https://www.redpill-linpro.com/\n\n\n", "msg_date": "Wed, 10 Feb 2021 15:25:58 +0100", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": true, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Wed, Feb 10, 2021 at 03:25:58PM +0100, Magnus Hagander wrote:\n> On Tue, Feb 9, 2021 at 9:54 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> >\n> > (I may have said this before, but) My overall high-level impression of\n> > this patch is that it's really cmmplex for a feature that you use maybe\n> > once in the lifetime of a cluster. I'm happy to review but I'm not\n> > planning to commit this myself. I don't object if some other committer\n> > picks this up (Magnus?).\n> \n> A fairly large amount of this complexity comes out of the fact that it\n> now supports restarting and tracks checksums on a per-table basis. We\n> skipped this in the original patch for exactly this reason (that's not\n> to say there isn't a fair amount of complexity even without it, but it\n> did substantially i increase both the size and the complexity of the\n> patch), but in the review of that i was specifically asked for having\n> that added. I personally don't think it's worth that complexity but at\n> the time that seemed to be a pretty strong argument. So I'm not\n> entirely sure how to move forward with that...\n> \n> is your impression that it would still be too complicated, even without that?\n\nI was wondering why this feature has stalled for so long --- now I know.\nThis does highlight the risk of implementing too many additions to a\nfeature. I am working against this dynamic in the cluster file\nencryption feature I am working on.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Wed, 10 Feb 2021 13:26:18 -0500", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On 10/02/2021 16:25, Magnus Hagander wrote:\n> On Tue, Feb 9, 2021 at 9:54 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>>\n>> (I may have said this before, but) My overall high-level impression of\n>> this patch is that it's really cmmplex for a feature that you use maybe\n>> once in the lifetime of a cluster. I'm happy to review but I'm not\n>> planning to commit this myself. I don't object if some other committer\n>> picks this up (Magnus?).\n> \n> A fairly large amount of this complexity comes out of the fact that it\n> now supports restarting and tracks checksums on a per-table basis. We\n> skipped this in the original patch for exactly this reason (that's not\n> to say there isn't a fair amount of complexity even without it, but it\n> did substantially i increase both the size and the complexity of the\n> patch), but in the review of that i was specifically asked for having\n> that added. I personally don't think it's worth that complexity but at\n> the time that seemed to be a pretty strong argument. So I'm not\n> entirely sure how to move forward with that...\n> \n> is your impression that it would still be too complicated, even without that?\n\nI'm not sure. It would certainly be a lot better.\n\nWrt. restartability, I'm also not very happy with the way that works - \nor rather doesn't :-) - in this patch. After shutting down and \nrestarting the cluster, you have to manually call \npg_enable_data_checksums() again to restart the checksumming process.\n\n- Heikki\n\n\n", "msg_date": "Wed, 10 Feb 2021 20:32:42 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Wed, Feb 10, 2021 at 01:26:18PM -0500, Bruce Momjian wrote:\n> On Wed, Feb 10, 2021 at 03:25:58PM +0100, Magnus Hagander wrote:\n> > A fairly large amount of this complexity comes out of the fact that it\n> > now supports restarting and tracks checksums on a per-table basis. We\n> > skipped this in the original patch for exactly this reason (that's not\n> > to say there isn't a fair amount of complexity even without it, but it\n> > did substantially i increase both the size and the complexity of the\n> > patch), but in the review of that i was specifically asked for having\n> > that added. I personally don't think it's worth that complexity but at\n> > the time that seemed to be a pretty strong argument. So I'm not\n> > entirely sure how to move forward with that...\n> > \n> > is your impression that it would still be too complicated, even without that?\n> \n> I was wondering why this feature has stalled for so long --- now I know.\n> This does highlight the risk of implementing too many additions to a\n> feature. I am working against this dynamic in the cluster file\n> encryption feature I am working on.\n\nOh, I think another reason this patchset has had problems is related to\nsomething I mentioned in 2018:\n\n\thttps://www.postgresql.org/message-id/20180801163613.GA2267@momjian.us\n\n\tThis patchset is weird because it is perhaps our first case of trying to\n\tchange the state of the server while it is running. We just don't have\n\tan established protocol for how to orchestrate that, so we are limping\n\talong toward a solution. Forcing a restart is probably part of that\n\tprimitive orchestration. We will probably have similar challenges if we\n\tever allowed Postgres to change its data format on the fly. These\n\tchallenges are one reason pg_upgrade only modifies the new cluster,\n\tnever the old one.\n\nI don't think anyone has done anything wrong --- rather, it is what we\nare _trying_ to do that is complex. Adding restartability to this just\nadded to the challenge.\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Thu, 11 Feb 2021 08:10:10 -0500", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 9 Feb 2021, at 09:54, Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> \n> (I may have said this before, but) My overall high-level impression of this patch is that it's really cmmplex for a feature that you use maybe once in the lifetime of a cluster.\n\nThe frequency of using a feature seems like a suboptimal metric of the value\nand usefulness of it. I don't disagree that this patch is quite invasive and\ncomplicated though, that's a side-effect of performing global state changes in\na distributed system which is hard to get around.\n\nAs was discussed downthread, some of the complexity stems from restartability\nand the catalog state persistence. The attached version does away with this to\nsee how big the difference is. Personally I don't think it's enough to move\nthe needle but mmv.\n\n> I'm happy to review but I'm not planning to commit this myself.\n\nRegardless, thanks for all review and thoughtful comments!\n\n>> \tdoPageWrites = (Insert->fullPageWrites || Insert->forcePageWrites || DataChecksumsOnInProgress());\n> \n> Why does this use DataChecksumsOnInProgress() instead of DataChecksumsNeedWrite()? If checksums are enabled, you always need full-page writes, don't you? If not, then why is it needed in the inprogress-on state?\n\nCorrect, that's a thinko, it should be DataChecksumsNeedWrite.\n\n> We also set doPageWrites in InitXLOGAccess(). That should match the condition above (although it doesn't matter for correctness).\n\nGood point, fixed.\n\n>> I think you need to hold the interrupts *before* the smgrread() call.\n\nFixed.\n\n>> /*\n>> * Set checksum for a page in private memory.\n>> *\n>> * This must only be used when we know that no other process can be modifying\n>> * the page buffer.\n>> */\n>> void\n>> PageSetChecksumInplace(Page page, BlockNumber blkno)\n>> {\n>> \tHOLD_INTERRUPTS();\n>> \t/* If we don't need a checksum, just return */\n>> \tif (PageIsNew(page) || !DataChecksumsNeedWrite())\n>> \t{\n>> \t\tRESUME_INTERRUPTS();\n>> \t\treturn;\n>> \t}\n>> \t((PageHeader) page)->pd_checksum = pg_checksum_page((char *) page, blkno);\n>> \tRESUME_INTERRUPTS();\n>> }\n> \n> The checksums state might change just after this call, before the caller has actually performed the smgrwrite() or smgrextend() call. The caller needs to hold interrupts across this function and the smgrwrite/smgrextend() call. It is a bad idea to HOLD_INTERRUPTS() here, because that just masks bugs where the caller isn't holding the interrupts. Same in PageSetChecksumCopy().\n\nLooking at the cases which could happen here in case of the below state change:\n\nPageSetChecksumInPlace\n B <---- state change\nsmgrwrite\n\nThe possible state transitions which can happen, and the consequences of them\nare:\n\n1) B = (off -> inprogress-on): We will write without a checksum. This relation\nwill then be processed by the DatachecksumsWorker. Readers will not verify\nchecksums.\n\n2) B = (inprogress-on -> on): We will write with a checksum. Both those states\nwrite checksums. Readers will verify the checksum.\n\n3) B = (on -> inprogress-off): We will write with a checksum. Both these\nstates write checksums. Readers will not verify checksums.\n\n4) B = (inprogress-off -> off): We will write with a checksum which is wasteful\nand strictly speaking incorrect. Readers will not verify checksums.\n\nThe above assume there is only a single state transition between the call to\nPageSetChecksumInPlace and smgrwrite/extend, which of course isn't guaranteed\nto be the case (albeit a lot more likely than two).\n\nThe (off -> inprogress-on -> on) and (inprogress-on -> on -> inprogress-off)\ntransitions cannot happen here since the DatachecksumWorker will wait for\nongoing transactions before a transition to on can be initiated.\n\n11) B = (on -> inprogress-off -> off): the checksum will be written when it\nshouldn't be, but readers won't verify it.\n\n22) B = (inprogress-off -> off -> inprogress-on): checksums are written without\nbeing verified in both these states.\n\nSo these cornercases can happen but ending up with an incorrect verification is\nlikely hard, which is probably why they haven't shook out during testing. I've\nupdated to patch to hold interrupts across the smgrwrite/extend call.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/", "msg_date": "Mon, 15 Feb 2021 13:21:17 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 11 Feb 2021, at 14:10, Bruce Momjian <bruce@momjian.us> wrote:\n> \n> On Wed, Feb 10, 2021 at 01:26:18PM -0500, Bruce Momjian wrote:\n>> On Wed, Feb 10, 2021 at 03:25:58PM +0100, Magnus Hagander wrote:\n>>> A fairly large amount of this complexity comes out of the fact that it\n>>> now supports restarting and tracks checksums on a per-table basis. We\n>>> skipped this in the original patch for exactly this reason (that's not\n>>> to say there isn't a fair amount of complexity even without it, but it\n>>> did substantially i increase both the size and the complexity of the\n>>> patch), but in the review of that i was specifically asked for having\n>>> that added. I personally don't think it's worth that complexity but at\n>>> the time that seemed to be a pretty strong argument. So I'm not\n>>> entirely sure how to move forward with that...\n>>> \n>>> is your impression that it would still be too complicated, even without that?\n>> \n>> I was wondering why this feature has stalled for so long --- now I know.\n>> This does highlight the risk of implementing too many additions to a\n>> feature. I am working against this dynamic in the cluster file\n>> encryption feature I am working on.\n> \n> Oh, I think another reason this patchset has had problems is related to\n> something I mentioned in 2018:\n> \n> \thttps://www.postgresql.org/message-id/20180801163613.GA2267@momjian.us\n> \n> \tThis patchset is weird because it is perhaps our first case of trying to\n> \tchange the state of the server while it is running. We just don't have\n> \tan established protocol for how to orchestrate that, so we are limping\n> \talong toward a solution. Forcing a restart is probably part of that\n> \tprimitive orchestration. We will probably have similar challenges if we\n> \tever allowed Postgres to change its data format on the fly. These\n> \tchallenges are one reason pg_upgrade only modifies the new cluster,\n> \tnever the old one.\n> \n> I don't think anyone has done anything wrong --- rather, it is what we\n> are _trying_ to do that is complex.\n\nGlobal state changes in a cluster are complicated, and are unlikely to never\nnot be. By writing patches to attempts such state changes we can see which\npieces of infrastructure we're lacking to reduce complexity. A good example is\nthe ProcSignalBarrier work that Andres and Robert did, inspired in part by this\npatch IIUC. The more we do, the more we learn.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Mon, 15 Feb 2021 14:02:02 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "On Mon, Feb 15, 2021 at 02:02:02PM +0100, Daniel Gustafsson wrote:\n> > On 11 Feb 2021, at 14:10, Bruce Momjian <bruce@momjian.us> wrote:\n> > I don't think anyone has done anything wrong --- rather, it is what we\n> > are _trying_ to do that is complex.\n> \n> Global state changes in a cluster are complicated, and are unlikely to never\n> not be. By writing patches to attempts such state changes we can see which\n> pieces of infrastructure we're lacking to reduce complexity. A good example is\n> the ProcSignalBarrier work that Andres and Robert did, inspired in part by this\n> patch IIUC. The more we do, the more we learn.\n\nDo we support or document the ability to create a standby with checksums\nfrom a primary without it, and is that a better approach?\n\n-- \n Bruce Momjian <bruce@momjian.us> https://momjian.us\n EDB https://enterprisedb.com\n\n The usefulness of a cup is in its emptiness, Bruce Lee\n\n\n\n", "msg_date": "Tue, 9 Mar 2021 13:12:06 -0500", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" }, { "msg_contents": "> On 9 Mar 2021, at 19:12, Bruce Momjian <bruce@momjian.us> wrote:\n\nSince this patch is de-facto rejected I'll mark it withdrawn in the CF app to\nsave on cfbot bandwidth.\n\n> Do we support or document the ability to create a standby with checksums\n> from a primary without it, and is that a better approach?\n\nMichael Banck started a new thread for that forking off of this one on message\nid 8f193f949b39817b9c642623e1fe7ccb94137ce4.camel@credativ.de so it's probably\nbetter to continue the discussion of that over there.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Tue, 9 Mar 2021 20:09:37 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Online checksums patch - once again" } ]
[ { "msg_contents": "The well known rightmost page split optimization (where we apply leaf\npage fill factor) usually does a great job of maximizing space\nutilization with indexes on a single auto-incrementing column or\ntimestamp column, by packing the left half of the rightmost page full.\nSplitting the rightmost page predicts further splits of the new\nrightmost page. If we are inserting ever-increasing values into the\nindex, then we win by packing the left half full -- we get very high\nspace utilization. If we're wrong to assume that another rightmost\npage split is sure to follow soon, then we lose on space utilization,\nthough only by a tiny amount. We may occasionally lose out on space\nutilization because our assumption that the rightmost page is special\nwas wrong. But, since it isn't special, we only inappropriately share\nspace unevenly once in a blue moon, which doesn't matter at all.\n\nThis seems to me to be fundamentally based on the assumption that you\neither have random insertions or sequential insertions, without any\ngray area between the two. Commit f21668f328c more or less generalized\nthis long established optimization to work with cases where it makes\nsense to split at the rightmost page of a *grouping* within the index,\nrather than the *entire* index, but that is almost unrelated to what I\nwant to bring up now. My concern right now is sensor data and IoT\ndata, which seem to call the \"random or sequential\" assumption into\nquestion. Such data often consists of timestamps from a large number\nof low cost devices -- event data that arrives *approximately* in\norder. This is more or less the problem that the TimescaleDB extension\ntargets, so it seems likely that a fair number of users care about\ngetting it right, even if they don't know it.\n\nI happened to notice that the largest TPC-E index has this exact\nproblem (it was the largest back when VMware ran TPC-E on Postgres\n[1], which they specifically complained about at the time). The\n\"trade_history\" table's primary key has tuples inserted\nalmost-but-not-quite in order. Sometimes packing the left half of the\nrightmost page 90% full works out, because the remaining space is\nenough to absorb all future insertions that arrive \"slightly late\"\n(though barely). More often it turns out that that isn't enough space,\nand the almost-rightmost page is split a second time, which is very\ninefficient in lots of ways, even compared to the case where we reduce\nfill factor to 50.\n\nI have found that reducing trade_history_pkey's fill factor to about\n70 increases leaf page space utilization, leaving it at about 85% (it\nwas under 50% with a fill factor of 90). I tend to doubt that this is\na practical tuning strategy in the real world, though, since varying\nTPC-E scale alters which exact setting is effective. Ideally,\nnbtpslitloc.c could intelligently adapt to slightly out of order\ninsertions in order to maximize space utilization -- it could\n*dynamically* tune fill factor in response to ongoing observations\nabout page splits. Importantly, this would allow nbtree to avoid\nunnecessarily splitting the same page twice in a row, having packed it\nalmost full on the first split -- this situation seems truly\npathological to me (think about the WAL overhead).\n\nISTM that adding such an optimization would require maintaining\ndedicated book keeping metadata, which doesn't seem particularly\nappealing. It might have acceptable overhead within a single backend.\nI'm thinking of something like the RelationGetTargetBlock() stuff. Has\nanybody else thought about this? What would a robust algorithm look\nlike?\n\nPerhaps this is a problem that isn't worth solving right now, but it\nis definitely a real problem.\n\n[1] https://www.postgresql.org/message-id/66CE997FB523C04E9749452273184C6C137CB88A86@exch-mbx-113.vmware.com\n--\nPeter Geoghegan\n\n\n", "msg_date": "Mon, 26 Aug 2019 15:48:48 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "IoT/sensor data and B-Tree page splits" }, { "msg_contents": "On 8/26/19 6:48 PM, Peter Geoghegan wrote:\n> Such data often consists of timestamps from a large number\n> of low cost devices -- event data that arrives *approximately* in\n> order. This is more or less the problem that the TimescaleDB extension\n> targets, so it seems likely that a fair number of users care about\n> getting it right, even if they don't know it.\n\nThis problem is not limited to IoT but to RT financial transaction \ningestion as well.\nI found BRIN indices to work exceptionally well for that, while B-tree \ntaking enormous amounts of space with no performance difference or win \ngoing to BRIN.\nThe situation gets even worse when B-tree index is subjected to \nidentical tuples which often happens when you have an avalanche of \ntimestamps that are within less than 1ms of each other (frequent TS \nrounding resolution).\n\n-- \nArcadiy Ivanov\narcadiy@gmail.com | @arcivanov | https://ivanov.biz\nhttps://github.com/arcivanov\n\n\n\n", "msg_date": "Mon, 26 Aug 2019 19:29:32 -0400", "msg_from": "Arcadiy Ivanov <arcadiy@gmail.com>", "msg_from_op": false, "msg_subject": "Re: IoT/sensor data and B-Tree page splits" }, { "msg_contents": "On Mon, Aug 26, 2019 at 4:29 PM Arcadiy Ivanov <arcadiy@gmail.com> wrote:\n> This problem is not limited to IoT but to RT financial transaction\n> ingestion as well.\n\nNot surprising, since the TPC-E benchmark models a financial trading\napplication. Perhaps it exhibits this behavior because it is actually\nrepresentative of a real trading application.\n\nNote that pg_stats.correlation is 1.0 for the leading indexed column\n(in the trade_history PK index), indicating *perfect* correlation.\nIt's not perfectly correlated when you look at it under a microscope,\nthough.\n\n> I found BRIN indices to work exceptionally well for that, while B-tree\n> taking enormous amounts of space with no performance difference or win\n> going to BRIN.\n\nThat won't work with the TPC-E example, though, since it's a primary key index.\n\n> The situation gets even worse when B-tree index is subjected to\n> identical tuples which often happens when you have an avalanche of\n> timestamps that are within less than 1ms of each other (frequent TS\n> rounding resolution).\n\nThe good news there is that that will almost certainly be a lot better\nin Postgres 12. TPC-E also has a number of very low cardinality\nindexes, despite being an OLTP benchmark. Some of these indexes are\nalso listed in the 2012 problem report I linked to. Those same indexes\nwill be a lot smaller on Postgres 12. It should also generate a lot\nless WAL compared to previous versions. (Plus we may get dynamic\nB-Tree deduplication in Postgres 13, which would improve matters\nfurther with low cardinality indexes.)\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 26 Aug 2019 16:49:44 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: IoT/sensor data and B-Tree page splits" }, { "msg_contents": "On 8/26/19 7:49 PM, Peter Geoghegan wrote:\n> Not surprising, since the TPC-E benchmark models a financial trading\n> application.\n\n> The good news there is that that will almost certainly be a lot better\n> in Postgres 12. TPC-E also has a number of very low cardinality\n> indexes, despite being an OLTP benchmark.\n\n\nBut apart from TPC-E and having to perform to it, is there any practical \nreal world usefulness in trying to have a B-tree index on TS-based data \njust to have a PK on it, as opposed to having a BRIN on a TS field and \ncalling it a day?\n\n-- \nArcadiy Ivanov\narcadiy@gmail.com | @arcivanov | https://ivanov.biz\nhttps://github.com/arcivanov\n\n\n\n", "msg_date": "Mon, 26 Aug 2019 19:59:49 -0400", "msg_from": "Arcadiy Ivanov <arcadiy@gmail.com>", "msg_from_op": false, "msg_subject": "Re: IoT/sensor data and B-Tree page splits" }, { "msg_contents": "On Mon, Aug 26, 2019 at 4:59 PM Arcadiy Ivanov <arcadiy@gmail.com> wrote:\n> But apart from TPC-E and having to perform to it, is there any practical\n> real world usefulness in trying to have a B-tree index on TS-based data\n> just to have a PK on it, as opposed to having a BRIN on a TS field and\n> calling it a day?\n\nThe index in question isn't an index on a timestamp. Its leading\ncolumn is an integer that is almost monotonically increasing, but not\nquite.\n\nIf a BRIN index works for you, then that's probably what you should\nuse. I don't think that that's relevant, though. BRIN indexes have\nclear disadvantages, including the fact that you have to know that\nyour data is amenable to BRIN indexing in order to use a BRIN index.\n\n-- \nPeter Geoghegan\n\n\n", "msg_date": "Mon, 26 Aug 2019 17:18:42 -0700", "msg_from": "Peter Geoghegan <pg@bowt.ie>", "msg_from_op": true, "msg_subject": "Re: IoT/sensor data and B-Tree page splits" } ]
[ { "msg_contents": "Hi,\n\nThis is apparently an EDB-owned machine but I have no access to it\ncurrently (I could ask if necessary). For some reason it's been\nfailing for a week, but only on REL_12_STABLE, with this in the log:\n\n2019-08-20 04:31:48.886 MDT [13421:4] LOG: server process (PID 13871)\nwas terminated by signal 11: unrecognized signal\n2019-08-20 04:31:48.886 MDT [13421:5] DETAIL: Failed process was\nrunning: SET default_table_access_method = '';\n\nApparently HPUX's sys_siglist doesn't recognise that most popular of\nsignals, 11, but by googling I see that it has its traditional meaning\nthere. That's clearly in the create_am test:\n\n019-08-20 04:31:22.404 MDT [13871:31] pg_regress/create_am HINT: Use\nDROP ... CASCADE to drop the dependent objects too.\n2019-08-20 04:31:22.404 MDT [13871:32] pg_regress/create_am STATEMENT:\n DROP ACCESS METHOD gist2;\n2019-08-20 04:31:22.405 MDT [13871:33] pg_regress/create_am LOG:\nstatement: DROP ACCESS METHOD gist2 CASCADE;\n2019-08-20 04:31:22.422 MDT [13871:34] pg_regress/create_am LOG:\nstatement: SET default_table_access_method = '';\n\nPerhaps it was really running the next statement.\n\nIt's hard to see how cdc8d371e2, the only non-doc commit listed on the\nfirst failure, could have anything to do with that.\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Tue, 27 Aug 2019 12:51:43 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "gharial segfaulting on REL_12_STABLE only" }, { "msg_contents": "Thomas Munro <thomas.munro@gmail.com> writes:\n> This is apparently an EDB-owned machine but I have no access to it\n> currently (I could ask if necessary). For some reason it's been\n> failing for a week, but only on REL_12_STABLE, with this in the log:\n\nYeah, I've been puzzling over that to little avail.\n\n> It's hard to see how cdc8d371e2, the only non-doc commit listed on the\n> first failure, could have anything to do with that.\n\nExactly :-(. It seems completely reproducible since then, but how\ncould that have triggered a failure over here? And why only in this\nbranch? The identical patch went into HEAD.\n\n> 2019-08-20 04:31:48.886 MDT [13421:4] LOG: server process (PID 13871)\n> was terminated by signal 11: unrecognized signal\n> 2019-08-20 04:31:48.886 MDT [13421:5] DETAIL: Failed process was\n> running: SET default_table_access_method = '';\n\n> Apparently HPUX's sys_siglist doesn't recognise that most popular of\n> signals, 11, but by googling I see that it has its traditional meaning\n> there.\n\nHPUX hasn't *got* sys_siglist, nor strsignal() which is what we're\nactually relying on these days (cf. pgstrsignal.c). I was puzzled\nby that too to start with, though. I wonder if we shouldn't rearrange\npg_strsignal so that the message in the !HAVE_STRSIGNAL case is\nsomething like \"signal names not available on this platform\" rather\nthan something that looks like we should've recognized it and didn't.\n\n> 2019-08-20 04:31:22.422 MDT [13871:34] pg_regress/create_am LOG:\n> statement: SET default_table_access_method = '';\n\n> Perhaps it was really running the next statement.\n\nHard to see how, because this should have reported\n\nERROR: invalid value for parameter \"default_table_access_method\": \"\"\nDETAIL: default_table_access_method cannot be empty.\n\nbut it didn't get that far. It seems like it must have died either\nin the (utterly trivial) check that leads to the above-quoted\ncomplaint, or somewhere in the ereport mechanism. Neither theory\nseems very credible.\n\nThe seeming action-at-a-distance nature of the failure has me\nspeculating about compiler or linker bugs, but I dislike\njumping to that type of conclusion without hard evidence.\n\nA stack trace would likely be really useful right about now.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 26 Aug 2019 21:48:01 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: gharial segfaulting on REL_12_STABLE only" }, { "msg_contents": "On Tue, Aug 27, 2019 at 1:48 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> A stack trace would likely be really useful right about now.\n\nYeah. Looking into how to get that.\n\n\n--\nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Tue, 27 Aug 2019 14:09:17 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: gharial segfaulting on REL_12_STABLE only" }, { "msg_contents": "On Tue, Aug 27, 2019 at 2:09 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> On Tue, Aug 27, 2019 at 1:48 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > A stack trace would likely be really useful right about now.\n>\n> Yeah. Looking into how to get that.\n\nErm. I heard the system was in a very unhappy state and couldn't be\nlogged into. After it was rebooted, the problem appears to have gone\naway. That is quite unsatisfying.\n\n\"anole\" runs on the same host, and occasionally fails to launch any\nparallel workers, and it seems to be pretty unhappy too -- very long\nruntimes (minutes where my smaller machines take seconds). So the\nmachine may be massively overloaded and swapping or something like\nthat, something to be looked into, but that doesn't explain how we get\nto a segfault without an underlying hard to reach bug in our code...\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Thu, 29 Aug 2019 13:06:32 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: gharial segfaulting on REL_12_STABLE only" } ]
[ { "msg_contents": "Hi\n\nIn my business, one of the things blocking the migration from Oracle to PostgreSQL is not having the equivalent of Oracle Real Application Testing .\nThis product captures a charge in production and replay it in a test environment.\nthis allows to know the impacts of a migration to a newer version, the creation of an index..\nis there an equivalent in the PostgreSQL community?\nif not, do you think it's technically possible to do it ?\nwho would be interested in this project ?\n\nThanks in advance\nBest Regards\n\nDidier ROS\nEDF\nCe message et toutes les pièces jointes (ci-après le 'Message') sont établis à l'intention exclusive des destinataires et les informations qui y figurent sont strictement confidentielles. Toute utilisation de ce Message non conforme à sa destination, toute diffusion ou toute publication totale ou partielle, est interdite sauf autorisation expresse.\n\nSi vous n'êtes pas le destinataire de ce Message, il vous est interdit de le copier, de le faire suivre, de le divulguer ou d'en utiliser tout ou partie. Si vous avez reçu ce Message par erreur, merci de le supprimer de votre système, ainsi que toutes ses copies, et de n'en garder aucune trace sur quelque support que ce soit. Nous vous remercions également d'en avertir immédiatement l'expéditeur par retour du message.\n\nIl est impossible de garantir que les communications par messagerie électronique arrivent en temps utile, sont sécurisées ou dénuées de toute erreur ou virus.\n____________________________________________________\n\nThis message and any attachments (the 'Message') are intended solely for the addressees. The information contained in this Message is confidential. Any use of information contained in this Message not in accord with its purpose, any dissemination or disclosure, either whole or partial, is prohibited except formal approval.\n\nIf you are not the addressee, you may not copy, forward, disclose or use any part of it. If you have received this message in error, please delete it and all copies from your system and notify the sender immediately by return message.\n\nE-mail communication cannot be guaranteed to be timely secure, error or virus-free.", "msg_date": "Tue, 27 Aug 2019 10:47:24 +0000", "msg_from": "ROS Didier <didier.ros@edf.fr>", "msg_from_op": true, "msg_subject": "PostgreSQL and Real Application Testing (RAT)" }, { "msg_contents": "ROS Didier schrieb am 27.08.2019 um 12:47:\n> In my business, one of the things blocking the migration from Oracle\n> to PostgreSQL is not having the equivalent of Oracle Real Application\n> Testing .\n>\n> This product captures a charge in production and replay it in a test\n> environment.\n>\n> this allows to know the impacts of a migration to a newer version,\n> the creation of an index..\n>\n> is there an equivalent in the PostgreSQL community?\n>\n> if not, do you think it's technically possible to do it?\n>\n> who would be interested in this project?\nNot sure how up-to-date that is, but you might want to have a look here:\n\nhttps://wiki.postgresql.org/wiki/Statement_Playback\n\n\n\n", "msg_date": "Tue, 27 Aug 2019 15:49:37 +0200", "msg_from": "Thomas Kellerer <shammat@gmx.net>", "msg_from_op": false, "msg_subject": "Re: PostgreSQL and Real Application Testing (RAT)" }, { "msg_contents": "On Tue, 27 Aug 2019 at 05:47, ROS Didier <didier.ros@edf.fr> wrote:\n\n> Hi\n>\n>\n>\n> In my business, one of the things blocking the migration from Oracle to\n> PostgreSQL is not having the equivalent of Oracle Real Application Testing .\n>\n> This product captures a charge in production and replay it in a test\n> environment.\n>\n> this allows to know the impacts of a migration to a newer version, the\n> creation of an index..\n>\n> is there an equivalent in the PostgreSQL community?\n>\n\nI used https://github.com/laurenz/pgreplay recently to re-execute the\nqueries sent to a pg9.1 in a pg11. It was very useful to find queries that\nare affected but changes in default values of GUCs.\n\nNormally, a query that works in an old version will work in a new one; but\nthis is useful to catch the few that don't if any\n\n-- \nJaime Casanova www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\nOn Tue, 27 Aug 2019 at 05:47, ROS Didier <didier.ros@edf.fr> wrote:\n\n\nHi \n \nIn my business, one of the things blocking the migration from Oracle to PostgreSQL is not having the equivalent of Oracle Real Application Testing .\nThis product captures a charge in production and replay it in a test environment.\nthis allows to know the impacts of a migration to a newer version, the creation of an index..\nis there an equivalent in the PostgreSQL community?I used https://github.com/laurenz/pgreplay recently to re-execute the queries sent to a pg9.1 in a pg11. It was very useful to find queries that are affected but changes in default values of GUCs.Normally, a query that works in an old version will work in a new one; but this is useful to catch the few that don't if any-- Jaime Casanova                      www.2ndQuadrant.comPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Tue, 27 Aug 2019 13:42:27 -0500", "msg_from": "Jaime Casanova <jaime.casanova@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: PostgreSQL and Real Application Testing (RAT)" }, { "msg_contents": "On Tue, Aug 27, 2019 at 3:47 AM ROS Didier <didier.ros@edf.fr> wrote:\n\n> Hi\n>\n>\n>\n> In my business, one of the things blocking the migration from Oracle to\n> PostgreSQL is not having the equivalent of Oracle Real Application Testing .\n>\n> This product captures a charge in production and replay it in a test\n> environment.\n>\n> this allows to know the impacts of a migration to a newer version, the\n> creation of an index..\n>\n> is there an equivalent in the PostgreSQL community?\n>\n> if not, do you think it's technically possible to do it ?\n>\n> who would be interested in this project ?\n>\n\nReplaying workload might or might not apply well to your case.\n\nThere are several major difficulties if you want to replay workload:\n\n1) How to \"record\" workload. You need to write all your queries to the\nPostgres log. Three problems here:\n 1a) pgreplay expects log_statements = 'all' while you might prefer\ndealing with log_min_duration_statement instead. This is a minor issue\nthough, quite easy to solve with preprocessing.\n 1b) under heavy load, log_min_duration_statement = 0 (or log_statements =\n'all') will lead to performance degradation or even downtime. Possible\nsolutions are: write to memory, or don't write at all but send over the\nnetwork.\n 1c) ideally, recoding just queries is not enough. To replay workload \"as\nis\", we need to replay queries with known plans. There is no easy solution\nto this problem in the Postgres ecosystem yet.\n\nA couple of additional points regarding item 1b and 1c. In Postgres 12,\nthere is a cool new capability: sampling for query logging,\nimplemented by Adrien\nNayrat https://commitfest.postgresql.org/20/1691/ WIth this, it will be\npossible to fully log, say, 5% of all transactions and use it for\nreplaying. Moreover, with auto_explain, it will be possible to have plans!\nOpen questions are: (a) how to determine, if N% is enough, and (b) how to\nreplay with specified plans. [If anyone is interested in working in this\ndirection – please reach out to me.]\n\n2) Issues with replaying itself. I can highlight at least two problems here:\n 2a) pgreplay might be not enough for your workload, it doesn't scale\nwell. If interested, look at its analog written in Go,\nhttps://github.com/gocardless/pgreplay-go, but this is quite a young\nproject.\n 2b) Postgres logs have millisecond precision (if you switched from %t to\n%m in log_line_prefix), this might be not enough. There is a patch to\nmicrosecond precision from David Fetter\nhttps://www.postgresql.org/message-id/flat/20181023185050.GE6049%40fetter.org,\nbut that conversation hasn't yet led to commit.\n\nAnother approach you might be interested in -- workload simulation. This is\nwhat we (Postgres.ai) now used in most times when building \"lab\"\nenvironments for our clients. The idea is as follows:\n- carefully analyze workload using pg_stat_statements (here, our\nopen-source tool called \"postgres-checkup\"\nhttps://gitlab.com/postgres-ai/postgres-checkup might be helpful, see\nreports in section K),\n- take the most resource-consuming query groups (Top-N ordered by\ntotal_time),\n- create a set of files with statements with randomly filled parameters\n(won't work for most cases, I discuss restrictions below),\n- use pgbench, feed workload files to it, using multiple -f options, with\nbalancing (-f filename@XX, where XX is to be taked from\npg_statements_analysis, but this time, \"calls\" and their ratio in the whole\nworkload will be needed -- again, postgres-checkup can help here).\n- run, analyze, compare behavior.\n\nRestrictions of this approach are obvious:\n- doesn't work well if most of your transactions have multiple statements,\n- in many cases, randomization is hard (not obvious how to organize;\nsynthetic approach is far from real data distribution in storage and\nworkload; etc),\n- the approach requires a significant amount of manual efforts.\n\nHowever, the \"workload simulation\" approach is an extremely helpful\napproach in many cases, helping with change management. It doesn't require\nanything that might negatively affect your production workload, it utilizes\npgbench (or any other tool) which is reliable, has great features and\nscales well.\n\nYou might be interested in looking at our tool that we built to conduct a\nhuge amount of DB experiments, Nancy CLI\nhttps://gitlab.com/postgres-ai/nancy. It supports both \"workload replay\"\nmethod (with pgreplay) and \"workload simulation\" (with pgbench). PM me if\nyou're interested in discussing details.\n\nThanks,\nNik\n\nOn Tue, Aug 27, 2019 at 3:47 AM ROS Didier <didier.ros@edf.fr> wrote:\n\n\nHi \n \nIn my business, one of the things blocking the migration from Oracle to PostgreSQL is not having the equivalent of Oracle Real Application Testing .\nThis product captures a charge in production and replay it in a test environment.\nthis allows to know the impacts of a migration to a newer version, the creation of an index..\nis there an equivalent in the PostgreSQL community?\nif not, do you think it's technically possible to do it ?\nwho would be interested in this project ?Replaying workload might or might not apply well to your case.There are several major difficulties if you want to replay workload:1) How to \"record\" workload. You need to write all your queries to the Postgres log. Three problems here:  1a) pgreplay expects log_statements = 'all' while you might prefer dealing with log_min_duration_statement instead. This is a minor issue though, quite easy to solve with preprocessing.  1b) under heavy load, log_min_duration_statement = 0 (or log_statements = 'all') will lead to performance degradation or even downtime. Possible solutions are: write to memory, or don't write at all but send over the network.  1c) ideally, recoding just queries is not enough. To replay workload \"as is\", we need to replay queries with known plans. There is no easy solution to this problem in the Postgres ecosystem yet.A couple of additional points regarding item 1b and 1c. In Postgres 12, there is a cool new capability: sampling for query logging, implemented by Adrien Nayrat https://commitfest.postgresql.org/20/1691/  WIth this, it will be possible to fully log, say, 5% of all transactions and use it for replaying. Moreover, with auto_explain, it will be possible to have plans! Open questions are: (a) how to determine, if N% is enough, and (b) how to replay with specified plans. [If anyone is interested in working in this direction – please reach out to me.]2) Issues with replaying itself. I can highlight at least two problems here:  2a) pgreplay might be not enough for your workload, it doesn't scale well. If interested, look at its analog written in Go, https://github.com/gocardless/pgreplay-go, but this is quite a young project.  2b) Postgres logs have millisecond precision (if you switched from %t to %m in log_line_prefix), this might be not enough. There is a patch to microsecond precision from David Fetter https://www.postgresql.org/message-id/flat/20181023185050.GE6049%40fetter.org, but that conversation hasn't yet led to commit.Another approach you might be interested in -- workload simulation. This is what we (Postgres.ai) now used in most times when building \"lab\" environments for our clients. The idea is as follows:- carefully analyze workload using pg_stat_statements (here, our open-source tool called \"postgres-checkup\" https://gitlab.com/postgres-ai/postgres-checkup might be helpful, see reports in section K),- take the most resource-consuming query groups (Top-N ordered by total_time),- create a set of files with statements with randomly filled parameters (won't work for most cases, I discuss restrictions below),- use pgbench, feed workload files to it, using multiple -f options, with balancing (-f filename@XX, where XX is to be taked from pg_statements_analysis, but this time, \"calls\" and their ratio in the whole workload will be needed -- again, postgres-checkup can help here).- run, analyze, compare behavior.Restrictions of this approach are obvious:- doesn't work well if most of your transactions have multiple statements,- in many cases, randomization is hard (not obvious how to organize; synthetic approach is far from real data distribution in storage and workload; etc),- the approach requires a significant amount of manual efforts.However, the \"workload simulation\" approach is an extremely helpful approach in many cases, helping with change management. It doesn't require anything that might negatively affect your production workload, it utilizes pgbench (or any other tool) which is reliable, has great features and scales well.You might be interested in looking at our tool that we built to conduct a huge amount of DB experiments, Nancy CLI https://gitlab.com/postgres-ai/nancy. It supports both \"workload replay\" method (with pgreplay) and \"workload simulation\" (with pgbench). PM me if you're interested in discussing details.Thanks,Nik", "msg_date": "Tue, 27 Aug 2019 17:32:44 -0700", "msg_from": "Nikolay Samokhvalov <samokhvalov@gmail.com>", "msg_from_op": false, "msg_subject": "Re: PostgreSQL and Real Application Testing (RAT)" }, { "msg_contents": "On Tue, 27 Aug 2019 at 19:33, Nikolay Samokhvalov <samokhvalov@gmail.com>\nwrote:\n\n> On Tue, Aug 27, 2019 at 3:47 AM ROS Didier <didier.ros@edf.fr> wrote:\n>\n>> Hi\n>>\n>>\n>>\n>> In my business, one of the things blocking the migration from Oracle to\n>> PostgreSQL is not having the equivalent of Oracle Real Application Testing .\n>>\n>> This product captures a charge in production and replay it in a test\n>> environment.\n>>\n>> this allows to know the impacts of a migration to a newer version, the\n>> creation of an index..\n>>\n>> is there an equivalent in the PostgreSQL community?\n>>\n>> if not, do you think it's technically possible to do it ?\n>>\n>> who would be interested in this project ?\n>>\n>\n> Replaying workload might or might not apply well to your case.\n>\n> There are several major difficulties if you want to replay workload:\n>\n> 1) How to \"record\" workload. You need to write all your queries to the\n> Postgres log. Three problems here:\n> 1a) pgreplay expects log_statements = 'all' while you might prefer\n> dealing with log_min_duration_statement instead. This is a minor issue\n> though, quite easy to solve with preprocessing.\n> 1b) under heavy load, log_min_duration_statement = 0 (or log_statements\n> = 'all') will lead to performance degradation or even downtime. Possible\n> solutions are: write to memory, or don't write at all but send over the\n> network.\n> 1c) ideally, recoding just queries is not enough. To replay workload \"as\n> is\", we need to replay queries with known plans. There is no easy solution\n> to this problem in the Postgres ecosystem yet.\n>\n>\nwhy? i prefer queries to take advantage of new plans for example if i'm\nmigrating from 9.5 to 9.6+ i would prefer that, when replaying, the queries\nuse parallel plans so i quickly get if that would somehow be a problem (for\nexample by using more cpu than before)\n\n-- \nJaime Casanova www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\nOn Tue, 27 Aug 2019 at 19:33, Nikolay Samokhvalov <samokhvalov@gmail.com> wrote:On Tue, Aug 27, 2019 at 3:47 AM ROS Didier <didier.ros@edf.fr> wrote:\n\n\nHi \n \nIn my business, one of the things blocking the migration from Oracle to PostgreSQL is not having the equivalent of Oracle Real Application Testing .\nThis product captures a charge in production and replay it in a test environment.\nthis allows to know the impacts of a migration to a newer version, the creation of an index..\nis there an equivalent in the PostgreSQL community?\nif not, do you think it's technically possible to do it ?\nwho would be interested in this project ?Replaying workload might or might not apply well to your case.There are several major difficulties if you want to replay workload:1) How to \"record\" workload. You need to write all your queries to the Postgres log. Three problems here:  1a) pgreplay expects log_statements = 'all' while you might prefer dealing with log_min_duration_statement instead. This is a minor issue though, quite easy to solve with preprocessing.  1b) under heavy load, log_min_duration_statement = 0 (or log_statements = 'all') will lead to performance degradation or even downtime. Possible solutions are: write to memory, or don't write at all but send over the network.  1c) ideally, recoding just queries is not enough. To replay workload \"as is\", we need to replay queries with known plans. There is no easy solution to this problem in the Postgres ecosystem yet.why? i prefer queries to take advantage of new plans for example if i'm migrating from 9.5 to 9.6+ i would prefer that, when replaying, the queries use parallel plans so i quickly get if that would somehow be a problem (for example by using more cpu than before)-- Jaime Casanova                      www.2ndQuadrant.comPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Tue, 27 Aug 2019 19:56:27 -0500", "msg_from": "Jaime Casanova <jaime.casanova@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: PostgreSQL and Real Application Testing (RAT)" } ]
[ { "msg_contents": "Hello,\n\nI was looking at resolve_generic_type to add anymultirange support,\nand the range logic doesn't seem correct to me. This function takes 3\ntype Oids:\n\n- declared_type is the declared type of a function parameter whose\nactual type it would like to deduce.\n- context_{declared,actual}_type are the {declared,actual} types of\nanother parameter, as a hint.\n\nHere is the logic in pseudocode:\n\n if (declared_type == ANYARRAYOID)\n {\n if (context_declared_type == ANYARRAYOID)\n return the array type\n else if (context_declared_type == ANYELEMENTOID ||\n context_declared_type == ANYNONARRAYOID ||\n context_declared_type == ANYENUMOID ||\n context_declared_type == ANYRANGEOID)\n context_declared_type == ANYMULTIRANGEOID)\n return an array of those things\n }\n else if (declared_type == ANYELEMENTOID ||\n declared_type == ANYNONARRAYOID ||\n declared_type == ANYENUMOID ||\n declared_type == ANYRANGEOID)\n {\n if (context_declared_type == ANYARRAYOID)\n return the element type\n else if (context_declared_type == ANYRANGEOID)\n return the element type\n else if (context_declared_type == ANYELEMENTOID ||\n context_declared_type == ANYNONARRAYOID ||\n context_declared_type == ANYENUMOID)\n return the actual type\n }\n else {\n return declared_type // since it's not polymorphic....\n }\n\nIt seems to me that these inputs would give invalid results:\n\nresolve_generic_type(ANYARRAYOID, x, ANYRANGEOID) - this will return\nan array of the *range type*, but that contracts the normal\nrelationship between anyelement and anyrange. It should return an\narray of the range's element type.\n\nresolve_generic_type(ANYRANGEOID, x, ANYRANGEOID) - this will return\nthe known range's *element* type, but it should return the known\nrange.\n\nFortunately we never call the function in either of those ways. The\nonly call site I could find is utils/fmgr/funcapi.c, and it only calls\nit like this:\n\n resolve_generic_type(ANYELEMENTOID, anyarray_type, ANYARRAYOID)\n resolve_generic_type(ANYELEMENTOID, anyrange_type, ANYRANGEOID)\n resolve_generic_type(ANYARRAYOID, anyelement_type, ANYELEMENTOID)\n\nSo I'm curious what I should do about all that, if anything. I'm happy\nto fix it (although I'm not sure how I'd test my changes), but it\nseems worth asking first. The first case in particular we *could* use\nto guess an anyarray's type if we wanted to, so I could add that to\nfuncapi.c and then probably invent some scenario to test it. For the\nsecond case, I'm guessing if a function has the *same* polymorphic\nparameter we probably make an inference without using\nresolve_generic_type, since they should obviously match. But does\nanyone here have a suggestion?\n\nThanks!\nPaul\n\n\n", "msg_date": "Tue, 27 Aug 2019 07:20:06 -0700", "msg_from": "Paul A Jungwirth <pj@illuminatedcomputing.com>", "msg_from_op": true, "msg_subject": "range bug in resolve_generic_type?" }, { "msg_contents": "Paul A Jungwirth <pj@illuminatedcomputing.com> writes:\n> I was looking at resolve_generic_type to add anymultirange support,\n> and the range logic doesn't seem correct to me.\n\nHmmm...\n\n> resolve_generic_type(ANYARRAYOID, x, ANYRANGEOID) - this will return\n> an array of the *range type*, but that contracts the normal\n> relationship between anyelement and anyrange. It should return an\n> array of the range's element type.\n\nI seem to recall that we discussed this exact point during development\nof the range feature, and concluded that this was the behavior we\nwanted, ie, treat anyrange like a scalar for this purpose. Otherwise\nthere isn't any way to use a polymorphic function to build an array\nof ranges, and that seemed more useful than being able to build\nan array of the range elements. Jeff might remember more here.\n\n> resolve_generic_type(ANYRANGEOID, x, ANYRANGEOID) - this will return\n> the known range's *element* type, but it should return the known\n> range.\n\nYeah, that seems like a flat-out bug.\n\n> Fortunately we never call the function in either of those ways.\n\nWouldn't it depend on the signature+result type of the user-defined\nfunction we're dealing with? (That is, calls with constant argument\ntypes are probably not the interesting ones.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 27 Aug 2019 11:23:32 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: range bug in resolve_generic_type?" }, { "msg_contents": "On Tue, Aug 27, 2019 at 8:23 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > resolve_generic_type(ANYARRAYOID, x, ANYRANGEOID) - this will return\n> > an array of the *range type*, but that contracts the normal\n> > relationship between anyelement and anyrange. It should return an\n> > array of the range's element type.\n>\n> I seem to recall that we discussed this exact point during development\n> of the range feature, and concluded that this was the behavior we\n> wanted, ie, treat anyrange like a scalar for this purpose. Otherwise\n> there isn't any way to use a polymorphic function to build an array\n> of ranges\n\nWell, I don't think that works anyway. At least I couldn't get it to\nwork here: https://www.postgresql.org/message-id/CA%2BrenyVOjb4xQZGjdCnA54-1nzVSY%2B47-h4nkM-EP5J%3D1z%3Db9w%40mail.gmail.com\n\nBut also check_generic_type_consistency works the way I'm saying:\n\n- if anyrange = r then anyelement = elemOf(r)\n- if anyarray = a then anyelement = elemOf(a)\n- elemOf(r) = elemOf(a)\n\nSo resolve_generic_type should agree with that, right?\n\nAlso, I'm interested in adding not just anymultirange but also\nanyrangearray, which *would* let you have polymorphic\narrays-of-ranges. (I thought I would need anyrangearray for a\nmultirange constructor, but actually now I think I might not need\nit---maybe. But still it seems like a helpful thing.)\n\n> > Fortunately we never call the function in either of those ways.\n>\n> Wouldn't it depend on the signature+result type of the user-defined\n> function we're dealing with? (That is, calls with constant argument\n> types are probably not the interesting ones.)\n\nI suppose an extension could call it (although it seems unlikely). But\nI couldn't find anywhere in the Postgres code that doesn't call it\nwith hardcoded arguments. (I certainly could have missed something\nthough.)\n\nThanks!\nPaul\n\n\n", "msg_date": "Tue, 27 Aug 2019 08:52:33 -0700", "msg_from": "Paul A Jungwirth <pj@illuminatedcomputing.com>", "msg_from_op": true, "msg_subject": "Re: range bug in resolve_generic_type?" }, { "msg_contents": "On Tue, Aug 27, 2019 at 8:52 AM Paul A Jungwirth\n<pj@illuminatedcomputing.com> wrote:\n>\n> On Tue, Aug 27, 2019 at 8:23 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > I seem to recall that we discussed this exact point during development\n> > of the range feature, and concluded that this was the behavior we\n> > wanted, ie, treat anyrange like a scalar for this purpose. Otherwise\n> > there isn't any way to use a polymorphic function to build an array\n> > of ranges\n\nOne more thing about this: The docs only say that elemOf(anyrange) =\nanyelement and elemOf(anyarray) = anyelement. I already added\nanymultirange to that page, so here is what I have (from my\nforthcoming patch). It also includes anyrangearray. I thought it might\nbe useful here to clarify how we could support polymorphic\narrays-of-ranges going forward, while avoiding any contradictions:\n\n <para>\n Seven pseudo-types of special interest are <type>anyelement</type>,\n <type>anyarray</type>, <type>anynonarray</type>, <type>anyenum</type>,\n <type>anyrange</type>, <type>anymultirange</type>, and\n <type>anyrangearray</type>.\n which are collectively called <firstterm>polymorphic types</firstterm>.\n Any function declared using these types is said to be\n a <firstterm>polymorphic function</firstterm>. A polymorphic function can\n operate on many different data types, with the specific data type(s)\n being determined by the data types actually passed to it in a particular\n call.\n </para>\n\n <para>\n Polymorphic arguments and results are tied to each other and are resolved\n to a specific data type when a query calling a polymorphic function is\n parsed. Each position (either argument or return value) declared as\n <type>anyelement</type> is allowed to have any specific actual\n data type, but in any given call they must all be the\n <emphasis>same</emphasis> actual type. Each\n position declared as <type>anyarray</type> can have any array data type,\n but similarly they must all be the same type. And similarly,\n positions declared as <type>anyrange</type> must all be the same range\n type. Likewise for <type>anymultirange</type> and\n<type>anyrangearray</type>.\n </para>\n\n <para>\n Furthermore, if there are\n positions declared <type>anyarray</type> and others declared\n <type>anyelement</type>, the actual array type in the\n <type>anyarray</type> positions must be an array whose elements are\n the same type appearing in the <type>anyelement</type> positions.\n <type>anynonarray</type> is treated exactly the same as\n<type>anyelement</type>,\n but adds the additional constraint that the actual type must not be\n an array type.\n <type>anyenum</type> is treated exactly the same as\n<type>anyelement</type>,\n but adds the additional constraint that the actual type must\n be an enum type.\n </para>\n\n <para>\n Similarly, if there are positions declared <type>anyrange</type>\n and others declared <type>anyelement</type>, the actual range type in\n the <type>anyrange</type> positions must be a range whose subtype is\n the same type appearing in the <type>anyelement</type> positions.\n The types <type>anymultirange</type> and <type>anyrangearray</type> accept\n a multirange or array of any range type, respectively.\n If they appear along with an <type>anyrange</type> then they must be a\n multirange/array of that range type.\n If a function has both <type>anymultirange</type> and\n <type>anyrangearray</type>, they must contain ranges of the same type,\n even if there is no <type>anyrange</type> parameter.\n </para>\n\n <para>\n Thus, when more than one argument position is declared with a polymorphic\n type, the net effect is that only certain combinations of actual argument\n types are allowed. For example, a function declared as\n <literal>equal(anyelement, anyelement)</literal> will take any\ntwo input values,\n so long as they are of the same data type.\n </para>\n\nI hope that helps!\n\nYours,\nPaul\n\n\n", "msg_date": "Sat, 31 Aug 2019 06:35:48 -0700", "msg_from": "Paul A Jungwirth <pj@illuminatedcomputing.com>", "msg_from_op": true, "msg_subject": "Re: range bug in resolve_generic_type?" } ]
[ { "msg_contents": "While reviewing a proposed patch to basebackup.c this morning, I found\nmyself a bit underwhelmed by the quality of the code and comments in\nbasebackup.c's sendFile(). I believe it's already been pointed out\nthat the the retry logic here is not particularly correct, and the\ncomments demonstrate a pretty clear lack of understanding of how the\nactual race conditions that are possible here might operate.\n\nHowever, I then noticed another problem which I think is significantly\nmore serious: this code totally ignores the possibility of a failure\nin fread(). It just assumes that if fread() fails to return a\npositive value, it's reached the end of the file, and if that happens,\nit just pads out the rest of the file with zeroes. So it looks to me\nlike if fread() encountered, say, an I/O error while trying to read a\ndata file, and if that error were on the first data block, then the\nentire contents of that file would be replaced with zero bytes in the\nbackup, and no error or warning of any kind would be given to the\nuser. If it hit the error later, everything from the point of the\nerror onward would just get replaced with zero bytes. To be clear, I\nthink it is fine for basebackup.c to fill out the rest of the expected\nlength with zeroes if in fact the file has been truncated during the\nbackup; recovery should fix it. But recovery is not going to fix data\nthat got eaten because EIO was encountered while copying a file.\n\nThe logic that rereads a block appears to have the opposite problem.\nHere, it will detect an error, but it will also fail in the face of a\nconcurrent truncation, which it shouldn't.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 27 Aug 2019 12:42:03 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": true, "msg_subject": "basebackup.c's sendFile() ignores read errors" }, { "msg_contents": "On Tue, Aug 27, 2019 at 10:33 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> While reviewing a proposed patch to basebackup.c this morning, I found\n> myself a bit underwhelmed by the quality of the code and comments in\n> basebackup.c's sendFile(). I believe it's already been pointed out\n> that the the retry logic here is not particularly correct, and the\n> comments demonstrate a pretty clear lack of understanding of how the\n> actual race conditions that are possible here might operate.\n>\n> However, I then noticed another problem which I think is significantly\n> more serious: this code totally ignores the possibility of a failure\n> in fread(). It just assumes that if fread() fails to return a\n> positive value, it's reached the end of the file, and if that happens,\n> it just pads out the rest of the file with zeroes. So it looks to me\n> like if fread() encountered, say, an I/O error while trying to read a\n> data file, and if that error were on the first data block, then the\n> entire contents of that file would be replaced with zero bytes in the\n> backup, and no error or warning of any kind would be given to the\n> user. If it hit the error later, everything from the point of the\n> error onward would just get replaced with zero bytes. To be clear, I\n> think it is fine for basebackup.c to fill out the rest of the expected\n> length with zeroes if in fact the file has been truncated during the\n> backup; recovery should fix it. But recovery is not going to fix data\n> that got eaten because EIO was encountered while copying a file.\n>\n\nPer fread(3) manpage, we cannot distinguish between an error or EOF. So to\ncheck for any error we must use ferror() after fread(). Attached patch which\ntests ferror() and throws an error if it returns true. However, I think\nfread()/ferror() both do not set errno (per some web reference) and thus\nthrowing a generic error here. I have manually tested it.\n\n\n> The logic that rereads a block appears to have the opposite problem.\n> Here, it will detect an error, but it will also fail in the face of a\n> concurrent truncation, which it shouldn't.\n>\n\nFor this, I have checked for feof() assuming that when the file gets\ntruncated\nwe reach EOF. And if yes, getting out of the loop instead of throwing an\nerror.\nI may be wrong as I couldn't reproduce this issue.\n\nPlease have a look over the patch and let me know your views.\n\n\n>\n> --\n> Robert Haas\n> EnterpriseDB: http://www.enterprisedb.com\n> The Enterprise PostgreSQL Company\n>\n>\n>\n\n-- \nJeevan Chalke\nTechnical Architect, Product Development\nEnterpriseDB Corporation\nThe Enterprise PostgreSQL Company", "msg_date": "Wed, 28 Aug 2019 16:01:06 +0530", "msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: basebackup.c's sendFile() ignores read errors" }, { "msg_contents": "Hi Jeevan,\n\nOn Wed, Aug 28, 2019 at 10:26 PM Jeevan Chalke <\njeevan.chalke@enterprisedb.com> wrote:\n\n>\n>\n> On Tue, Aug 27, 2019 at 10:33 PM Robert Haas <robertmhaas@gmail.com>\n> wrote:\n>\n>> While reviewing a proposed patch to basebackup.c this morning, I found\n>> myself a bit underwhelmed by the quality of the code and comments in\n>> basebackup.c's sendFile(). I believe it's already been pointed out\n>> that the the retry logic here is not particularly correct, and the\n>> comments demonstrate a pretty clear lack of understanding of how the\n>> actual race conditions that are possible here might operate.\n>>\n>> However, I then noticed another problem which I think is significantly\n>> more serious: this code totally ignores the possibility of a failure\n>> in fread(). It just assumes that if fread() fails to return a\n>> positive value, it's reached the end of the file, and if that happens,\n>> it just pads out the rest of the file with zeroes. So it looks to me\n>> like if fread() encountered, say, an I/O error while trying to read a\n>> data file, and if that error were on the first data block, then the\n>> entire contents of that file would be replaced with zero bytes in the\n>> backup, and no error or warning of any kind would be given to the\n>> user. If it hit the error later, everything from the point of the\n>> error onward would just get replaced with zero bytes. To be clear, I\n>> think it is fine for basebackup.c to fill out the rest of the expected\n>> length with zeroes if in fact the file has been truncated during the\n>> backup; recovery should fix it. But recovery is not going to fix data\n>> that got eaten because EIO was encountered while copying a file.\n>>\n>\n> Per fread(3) manpage, we cannot distinguish between an error or EOF. So to\n> check for any error we must use ferror() after fread(). Attached patch\n> which\n> tests ferror() and throws an error if it returns true.\n>\n\nYou are right. This seems the right approach to me. I can see at least\ncouple\nof places already using ferror() to guard errors of fread()\nlike CopyGetData(),\nread_backup_label() etc.\n\n\n> However, I think\n> fread()/ferror() both do not set errno (per some web reference) and thus\n> throwing a generic error here. I have manually tested it.\n>\n\nIf we are interested in getting the errno, then instead of fread(), we can\nuse read(). But, here, in particular, we are not decision making anything\ndepending on errno so I think we should be fine with your current patch.\n\n\n>\n>> The logic that rereads a block appears to have the opposite problem.\n>> Here, it will detect an error, but it will also fail in the face of a\n>> concurrent truncation, which it shouldn't.\n>>\n>\n> For this, I have checked for feof() assuming that when the file gets\n> truncated\n> we reach EOF. And if yes, getting out of the loop instead of throwing an\n> error.\n> I may be wrong as I couldn't reproduce this issue.\n>\n\nI had a look at the patch and this seems correct to me.\n\nFew minor comments:\n\n+ /* Check fread() error. */\n+ CHECK_FREAD_ERROR(fp, pathbuf);\n+\n\nThe comments above the macro call at both the places are not necessary as\nyour macro name itself is self-explanatory.\n\n----------\n+ /*\n+ * If file is truncated, then we will hit\n+ * end-of-file error in which case we don't\n+ * want to error out, instead just pad it with\n+ * zeros.\n+ */\n+ if (feof(fp))\n\nThe if block does not do the truncation right away, so I think the comment\nabove can be reworded to explain why we reset cnt?\n\nRegards,\nJeevan Ladhe\n\nHi Jeevan,On Wed, Aug 28, 2019 at 10:26 PM Jeevan Chalke <jeevan.chalke@enterprisedb.com> wrote:On Tue, Aug 27, 2019 at 10:33 PM Robert Haas <robertmhaas@gmail.com> wrote:While reviewing a proposed patch to basebackup.c this morning, I foundmyself a bit underwhelmed by the quality of the code and comments inbasebackup.c's sendFile(). I believe it's already been pointed outthat the the retry logic here is not particularly correct, and thecomments demonstrate a pretty clear lack of understanding of how theactual race conditions that are possible here might operate.\nHowever, I then noticed another problem which I think is significantlymore serious: this code totally ignores the possibility of a failurein fread().  It just assumes that if fread() fails to return apositive value, it's reached the end of the file, and if that happens,it just pads out the rest of the file with zeroes.  So it looks to melike if fread() encountered, say, an I/O error while trying to read adata file, and if that error were on the first data block, then theentire contents of that file would be replaced with zero bytes in thebackup, and no error or warning of any kind would be given to theuser.  If it hit the error later, everything from the point of theerror onward would just get replaced with zero bytes.  To be clear, Ithink it is fine for basebackup.c to fill out the rest of the expectedlength with zeroes if in fact the file has been truncated during thebackup; recovery should fix it.  But recovery is not going to fix datathat got eaten because EIO was encountered while copying a file.Per fread(3) manpage, we cannot distinguish between an error or EOF. So tocheck for any error we must use ferror() after fread(). Attached patch whichtests ferror() and throws an error if it returns true. You are right. This seems the right approach to me. I can see at least coupleof places already using ferror() to guard errors of fread() like CopyGetData(),read_backup_label() etc. However, I thinkfread()/ferror() both do not set errno (per some web reference) and thusthrowing a generic error here. I have manually tested it.If we are interested in getting the errno, then instead of fread(), we canuse read(). But, here, in particular, we are not decision making anythingdepending on errno so I think we should be fine with your current patch. \nThe logic that rereads a block appears to have the opposite problem.Here, it will detect an error, but it will also fail in the face of aconcurrent truncation, which it shouldn't.For this, I have checked for feof() assuming that when the file gets truncatedwe reach EOF. And if yes, getting out of the loop instead of throwing an error.I may be wrong as I couldn't reproduce this issue.I had a look at the patch and this seems correct to me.Few minor comments:+ /* Check fread() error. */+ CHECK_FREAD_ERROR(fp, pathbuf);+The comments above the macro call at both the places are not necessary asyour macro name itself is self-explanatory.----------+ /*+ * If file is truncated, then we will hit+ * end-of-file error in which case we don't+ * want to error out, instead just pad it with+ * zeros.+ */+ if (feof(fp))The if block does not do the truncation right away, so I think the commentabove can be reworded to explain why we reset cnt?Regards,Jeevan Ladhe", "msg_date": "Thu, 29 Aug 2019 15:17:31 +0530", "msg_from": "Jeevan Ladhe <jeevan.ladhe@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: basebackup.c's sendFile() ignores read errors" }, { "msg_contents": "On Thu, Aug 29, 2019 at 3:17 PM Jeevan Ladhe <jeevan.ladhe@enterprisedb.com>\nwrote:\n\n> Hi Jeevan\n>\n> I had a look at the patch and this seems correct to me.\n>\n\nThanks, Jeevan Ladhe.\n\n\n>\n> Few minor comments:\n>\n> + /* Check fread() error. */\n> + CHECK_FREAD_ERROR(fp, pathbuf);\n> +\n>\n> The comments above the macro call at both the places are not necessary as\n> your macro name itself is self-explanatory.\n>\n> ----------\n> + /*\n> + * If file is truncated, then we will hit\n> + * end-of-file error in which case we don't\n> + * want to error out, instead just pad it with\n> + * zeros.\n> + */\n> + if (feof(fp))\n>\n> The if block does not do the truncation right away, so I think the comment\n> above can be reworded to explain why we reset cnt?\n>\n\nFixed both comments in the attached patch.\n\n-- \nJeevan Chalke\nTechnical Architect, Product Development\nEnterpriseDB Corporation\nThe Enterprise PostgreSQL Company", "msg_date": "Fri, 30 Aug 2019 16:04:43 +0530", "msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: basebackup.c's sendFile() ignores read errors" }, { "msg_contents": ">\n> Fixed both comments in the attached patch.\n>\n\nThanks, the patch looks good to me.\n\nRegards,\nJeevan Ladhe\n\nFixed both comments in the attached patch.Thanks, the patch looks good to me.Regards,Jeevan Ladhe", "msg_date": "Fri, 30 Aug 2019 16:34:53 +0530", "msg_from": "Jeevan Ladhe <jeevan.ladhe@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: basebackup.c's sendFile() ignores read errors" }, { "msg_contents": "On Fri, Aug 30, 2019 at 7:05 AM Jeevan Ladhe\n<jeevan.ladhe@enterprisedb.com> wrote:\n>> Fixed both comments in the attached patch.\n>\n> Thanks, the patch looks good to me.\n\nHere's a version of the patch with a further change to the wording of\nthe comment. I hope this is clearer.\n\nI think this needs to be back-patched all the way back to 9.4, and it\ndoesn't seem to apply cleanly before v11. Any chance you could\nprepare a version for the older branches?\n\nThanks,\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company", "msg_date": "Thu, 5 Sep 2019 14:10:37 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": true, "msg_subject": "Re: basebackup.c's sendFile() ignores read errors" }, { "msg_contents": "On Thu, Sep 5, 2019 at 11:40 PM Robert Haas <robertmhaas@gmail.com> wrote:\n\n> On Fri, Aug 30, 2019 at 7:05 AM Jeevan Ladhe\n> <jeevan.ladhe@enterprisedb.com> wrote:\n> >> Fixed both comments in the attached patch.\n> >\n> > Thanks, the patch looks good to me.\n>\n> Here's a version of the patch with a further change to the wording of\n> the comment. I hope this is clearer.\n>\n\nYep.\n\n\n>\n> I think this needs to be back-patched all the way back to 9.4, and it\n> doesn't seem to apply cleanly before v11. Any chance you could\n> prepare a version for the older branches?\n>\n\nAttached patch for v10 and pre. The same v10 patch applies cleanly.\n\nChanges related to the page checksum verification is not present on v10 and\npre, and thus those changes are not applicable, so removed those. Also,\nwal_segment_size is XLogSegSize over there, adjusted that.\n\n\n>\n> Thanks,\n>\n> --\n> Robert Haas\n> EnterpriseDB: http://www.enterprisedb.com\n> The Enterprise PostgreSQL Company\n>\n\nThanks\n-- \nJeevan Chalke\nTechnical Architect, Product Development\nEnterpriseDB Corporation\nThe Enterprise PostgreSQL Company", "msg_date": "Fri, 6 Sep 2019 11:38:12 +0530", "msg_from": "Jeevan Chalke <jeevan.chalke@enterprisedb.com>", "msg_from_op": false, "msg_subject": "Re: basebackup.c's sendFile() ignores read errors" }, { "msg_contents": "On Fri, Sep 6, 2019 at 2:08 AM Jeevan Chalke\n<jeevan.chalke@enterprisedb.com> wrote:\n> Attached patch for v10 and pre. The same v10 patch applies cleanly.\n>\n> Changes related to the page checksum verification is not present on v10 and\n> pre, and thus those changes are not applicable, so removed those. Also,\n> wal_segment_size is XLogSegSize over there, adjusted that.\n\nThanks. Committed the v3 patch to v11+ and this version to the older branches.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Fri, 6 Sep 2019 09:18:03 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": true, "msg_subject": "Re: basebackup.c's sendFile() ignores read errors" } ]
[ { "msg_contents": "In 959f6d6a1821 it seems that I fat-fingered and missed a newline in the usage\noutput, which makes --check become appended to -B rather than on its own line.\nThe attached diff fixes that.\n\ncheers ./daniel", "msg_date": "Tue, 27 Aug 2019 21:06:15 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": true, "msg_subject": "Missing newline in pg_upgrade usage()" }, { "msg_contents": "Daniel Gustafsson <daniel@yesql.se> writes:\n> In 959f6d6a1821 it seems that I fat-fingered and missed a newline in the usage\n> output, which makes --check become appended to -B rather than on its own line.\n> The attached diff fixes that.\n\nRoger, pushed.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 27 Aug 2019 15:15:24 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Missing newline in pg_upgrade usage()" } ]
[ { "msg_contents": "Dear Hackers.\n\nCurrently, the XLogWrite function is written in 8k(or 16kb) units\nregardless of the size of the new record.\nFor example, even if a new record is only 300 bytes, pg_pwrite is\ncalled to write data in 8k units (if it cannot be writing on one page\nis 16kb written).\nLet's look at the worst case.\n1) LogwrtResult.Flush is 8100 pos.\n2) And the new record size is only 100 bytes.\nIn this case, pg_pwrite is called which writes 16 kb to update only 100 bytes.\nIt is a rare case, but I think there is overhead for pg_pwrite for some systems.\n# For systems that often update one record in one transaction.\n\nSo what about modifying the XLogWrite function only to write the size\nthat should record?\nCan this idea benefit from WAL writing performance?\nIf it's OK to improve, I want to do modification.\nHow do you think of it?\n\nBest Regards.\nMoon.\n\n\n", "msg_date": "Wed, 28 Aug 2019 15:43:02 +0900", "msg_from": "\"Moon, Insung\" <tsukiwamoon.pgsql@gmail.com>", "msg_from_op": true, "msg_subject": "Performance improvement of WAL writing?" }, { "msg_contents": "Hi, Moon-san.\n\nAt Wed, 28 Aug 2019 15:43:02 +0900, \"Moon, Insung\" <tsukiwamoon.pgsql@gmail.com> wrote in <CAEMmqBvQ56-CvUy2kyJp0JJnFE9EAm4t0aGnSfiH+z4=Hw_6DQ@mail.gmail.com>\n> Dear Hackers.\n> \n> Currently, the XLogWrite function is written in 8k(or 16kb) units\n> regardless of the size of the new record.\n> For example, even if a new record is only 300 bytes, pg_pwrite is\n> called to write data in 8k units (if it cannot be writing on one page\n> is 16kb written).\n> Let's look at the worst case.\n> 1) LogwrtResult.Flush is 8100 pos.\n> 2) And the new record size is only 100 bytes.\n> In this case, pg_pwrite is called which writes 16 kb to update only 100 bytes.\n> It is a rare case, but I think there is overhead for pg_pwrite for some systems.\n> # For systems that often update one record in one transaction.\n\nIf a commit is lonely in the system, the 100 bytes ought to be\nflushed out immediately. If there are many concurrent commits,\nXLogFlush() waits for all in-flight insertions up to the LSN the\nbackends is writing then actually flushes. Of course sometimes it\nflushes just 100 bytes but sometimes it flushes far many bytes\ninvolving records from other backends. If another backend has\nflushed further than the backend's upto LSN, the backend skips\nflush.\n\nIf you want to involve more commits in a flush, commit_delay lets\nthe backend wait for that duration so that more commits can come\nin within the window. Or synchronous_commit = off works somewhat\nmore aggressively.\n\n> So what about modifying the XLogWrite function only to write the size\n> that should record?\n\nIf I understand your porposal correctly, you're proposing to\nseparate fsync from XLogWrite. Actually, as you proposed, roughly\nspeaking no flush happen execpt at segment switch or commit. If\nyou are proposing not flushing immediately even at commit,\ncommit_delay (or synchronous_commit) works that way.\n\n> Can this idea benefit from WAL writing performance?\n> If it's OK to improve, I want to do modification.\n> How do you think of it?\n\nSo the proposal seems to be already achieved. If not, could you\nelaborate the proposal, or explain about actual problem?\n\n> Best Regards.\n> Moon.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Wed, 28 Aug 2019 17:17:40 +0900 (Tokyo Standard Time)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Performance improvement of WAL writing?" }, { "msg_contents": "On Wed, Aug 28, 2019 at 2:43 AM Moon, Insung <tsukiwamoon.pgsql@gmail.com>\nwrote:\n\n> So what about modifying the XLogWrite function only to write the size\n> that should record?\n> Can this idea benefit from WAL writing performance?\n> If it's OK to improve, I want to do modification.\n> How do you think of it?\n>\n\nI have performed tests in this direction several years ago.\n\nThe way it works now guarantees that the data of recycled WAL segments is\nnever read from disk, as long as the WAL block size is a multiple of the\nfilesystem's page/fragment size. The OS sees that the write() is on a\nfragment boundary and full fragment(s) in size. If the write() would be\nsmaller in size, the OS would be forced to combine the new data with the\nrest of the fragment's old data on disk. To do so the system now has to\nwait until the old fragment is actually in the OS buffer. Which means that\nonce you have enough WAL segments to cycle through so that the checkpoint\nreason is never XLOG and the blocks of the WAL segment that is cycled in\nhave been evicted since it was last used, this causes real reads. On\nspinning media, which are still an excellent choice for WAL, this turns\ninto a total disaster because it adds a rotational delay for every single\nWAL block that is only partially overwritten.\n\nI believe that this could only work if we stopped recycling WAL segments\nand instead delete old segments, then create new files as needed. This\nhowever adds the overhead of constant metadata change to WAL writing and I\nhave no idea what performance or reliability impact that may have. There\nwere reasons we chose to implement WAL segment recycling many years ago.\nThese reasons may no longer be valid on modern filesystems, but it\ndefinitely is not a performance question alone.\n\nRegards, Jan\n\n-- \nJan Wieck\nSenior Postgres Architect\nhttp://pgblog.wi3ck.info\n\nOn Wed, Aug 28, 2019 at 2:43 AM Moon, Insung <tsukiwamoon.pgsql@gmail.com> wrote:So what about modifying the XLogWrite function only to write the size\nthat should record?\nCan this idea benefit from WAL writing performance?\nIf it's OK to improve, I want to do modification.\nHow do you think of it?I have performed tests in this direction several years ago.The way it works now guarantees that the data of recycled WAL segments is never read from disk, as long as the WAL block size is a multiple of the filesystem's page/fragment size. The OS sees that the write() is on a fragment boundary and full fragment(s) in size. If the write() would be smaller in size, the OS would be forced to combine the new data with the rest of the fragment's old data on disk. To do so the system now has to wait until the old fragment is actually in the OS buffer. Which means that once you have enough WAL segments to cycle through so that the checkpoint reason is never XLOG and the blocks of the WAL segment that is cycled in have been evicted since it was last used, this causes real reads. On spinning media, which are still an excellent choice for WAL, this turns into a total disaster because it adds a rotational delay for every single WAL block that is only partially overwritten.I believe that this could only work if we stopped recycling WAL segments and instead delete old segments, then create new files as needed. This however adds the overhead of constant metadata change to WAL writing and I have no idea what performance or reliability impact that may have. There were reasons we chose to implement WAL segment recycling many years ago. These reasons may no longer be valid on modern filesystems, but it definitely is not a performance question alone.Regards, Jan -- Jan WieckSenior Postgres Architecthttp://pgblog.wi3ck.info", "msg_date": "Wed, 28 Aug 2019 07:12:01 -0400", "msg_from": "Jan Wieck <jan@wi3ck.info>", "msg_from_op": false, "msg_subject": "Re: Performance improvement of WAL writing?" } ]
[ { "msg_contents": "Hi all,\n\nThis is a follow-up of the discussion which happened here after Tom\nhas committed fb57f40:\nhttps://www.postgresql.org/message-id/20190828012439.GA1965@paquier.xyz\n\nI have reviewed the TAP tests, and we have much more spots where it\nis better to use PostgresNode::safe_psql instead PostgresNode::psql so\nas the test dies immediately if there is a failure on a query which\nshould never fail.\n\nAttached are the spots I have found. Any thoughts or opinions?\nThanks,\n--\nMichael", "msg_date": "Wed, 28 Aug 2019 15:49:46 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Improve error detections in TAP tests by spreading safe_psql" }, { "msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n> This is a follow-up of the discussion which happened here after Tom\n> has committed fb57f40:\n> https://www.postgresql.org/message-id/20190828012439.GA1965@paquier.xyz\n> I have reviewed the TAP tests, and we have much more spots where it\n> is better to use PostgresNode::safe_psql instead PostgresNode::psql so\n> as the test dies immediately if there is a failure on a query which\n> should never fail.\n\nAfter a brief review of node->psql calls in the TAP tests, I'm\nof the opinion that what we should do is revert fb57f40 and instead\nchange PostgresNode::psql so that on_error_die defaults to 1, then\nfix the *very* small number of callers that need it to be zero.\nOtherwise we're just going to be fighting this same fire forevermore.\nMoreover, that's going to lead to a much smaller patch.\n\n> Attached are the spots I have found. Any thoughts or opinions?\n\nWell, for instance, you missed SSLServer.pm, in which every single\none of the psql calls is wrong.\n\nIf we go this route we'd have to back-patch the change, else it'd\nbe a serious hazard for test case back-patching. But the buildfarm\nwould, more or less by definition, find any oversights --- so that\ndoesn't scare me much.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 28 Aug 2019 10:43:28 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Improve error detections in TAP tests by spreading safe_psql" }, { "msg_contents": "I wrote:\n> After a brief review of node->psql calls in the TAP tests, I'm\n> of the opinion that what we should do is revert fb57f40 and instead\n> change PostgresNode::psql so that on_error_die defaults to 1, then\n> fix the *very* small number of callers that need it to be zero.\n> Otherwise we're just going to be fighting this same fire forevermore.\n> Moreover, that's going to lead to a much smaller patch.\n\nHmm .. I experimented with doing it this way, as attached, and I guess\nI have to take back the assertion that it'd be a much smaller patch.\nI found 47 calls that'd need to be changed to set on_error_die to 0,\nwhereas your patch is touching 44 calls (though I think it missed some).\nI still think this is a safer, less bug-prone way to proceed though.\n\nThe attached patch just follows a mechanical rule of \"set on_error_die\nto 0 in exactly those calls where the surrounding code verifies the\nexit code is what it expects\". That leads to a lot of code that\nlooks like, say,\n\n # Insert should work on standby\n is( $node_standby->psql(\n \t\t'postgres',\n-\t\tqq{insert into testtab select generate_series(1,1000), 'foo';}),\n+\t\tqq{insert into testtab select generate_series(1,1000), 'foo';},\n+\t\ton_error_die => 0),\n \t0,\n \t'INSERT succeeds with truncated relation FSM');\n\nI have to wonder if it isn't better to just drop the is() test\nand let PostgresNode::psql issue the failure. The only thing\nthe is() is really buying us is the ability to label the test\nwith an ID string, which is helpful, but um ... couldn't that\njust be a comment? Or we could think about adding another\noptional parameter:\n\n$node_standby->psql(\n\t'postgres',\n\tqq{insert into testtab select generate_series(1,1000), 'foo';},\n \ttest_name => 'INSERT succeeds with truncated relation FSM');\n\n\t\t\tregards, tom lane", "msg_date": "Wed, 28 Aug 2019 12:19:08 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Improve error detections in TAP tests by spreading safe_psql" }, { "msg_contents": "On Wed, Aug 28, 2019 at 12:19:08PM -0400, Tom Lane wrote:\n> The attached patch just follows a mechanical rule of \"set on_error_die\n> to 0 in exactly those calls where the surrounding code verifies the\n> exit code is what it expects\". That leads to a lot of code that\n> looks like, say,\n> \n> # Insert should work on standby\n> is( $node_standby->psql(\n> \t\t'postgres',\n> -\t\tqq{insert into testtab select generate_series(1,1000), 'foo';}),\n> +\t\tqq{insert into testtab select generate_series(1,1000), 'foo';},\n> +\t\ton_error_die => 0),\n> \t0,\n> \t'INSERT succeeds with truncated relation FSM');\n\nI am fine with that approach. There is an argument for dropping\nsafe_psql then?\n\n> I have to wonder if it isn't better to just drop the is() test\n> and let PostgresNode::psql issue the failure. The only thing\n> the is() is really buying us is the ability to label the test\n> with an ID string, which is helpful, but um ... couldn't that\n> just be a comment?\n\nI got the same thought as you on this point about why the is() is\nactually necessary if we know that it would fail. An advantage of the\ncurrent code is that we are able to catch all errors in a given run at\nonce. If the test dies immediately, you cannot catch that and this\nneeds repetitive retries if there is no dependency between each step\nof the test. An argument against back-patching the stuff changing the\ndefault flag are tests which rely on the current behavior. This could\nbe annoying for some people doing advanced testing.\n--\nMichael", "msg_date": "Thu, 29 Aug 2019 09:46:39 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Improve error detections in TAP tests by spreading safe_psql" }, { "msg_contents": "Michael Paquier <michael@paquier.xyz> writes:\n> On Wed, Aug 28, 2019 at 12:19:08PM -0400, Tom Lane wrote:\n>> The attached patch just follows a mechanical rule of \"set on_error_die\n>> to 0 in exactly those calls where the surrounding code verifies the\n>> exit code is what it expects\".\n\n> I am fine with that approach. There is an argument for dropping\n> safe_psql then?\n\nWell, it's useful if you just want the stdout back. But its name\nis a bit misleading if the default behavior of psql is just as\nsafe. Not sure whether renaming it is worthwhile.\n\n>> I have to wonder if it isn't better to just drop the is() test\n>> and let PostgresNode::psql issue the failure.\n\n> I got the same thought as you on this point about why the is() is\n> actually necessary if we know that it would fail. An advantage of the\n> current code is that we are able to catch all errors in a given run at\n> once.\n\nYeah, but only if the test cases are independent, which I think is\nmostly not true in our TAP scripts. Otherwise you're just looking\nat cascading errors.\n\n> An argument against back-patching the stuff changing the\n> default flag are tests which rely on the current behavior. This could\n> be annoying for some people doing advanced testing.\n\nYup, the tradeoff is people possibly having test scripts outside\nour tree that would break, versus the possibility that we'll back-patch\ntest changes that don't behave as expected in back branches. I don't\nknow if the former is true, but I'm afraid the latter is a certainty\nif we don't back-patch.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 28 Aug 2019 21:44:58 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Improve error detections in TAP tests by spreading safe_psql" }, { "msg_contents": "On Wed, Aug 28, 2019 at 09:44:58PM -0400, Tom Lane wrote:\n> Well, it's useful if you just want the stdout back. But its name\n> is a bit misleading if the default behavior of psql is just as\n> safe. Not sure whether renaming it is worthwhile.\n\nIt is not that complicated enough to capture stdout with\nPostgresNode::psql either, so if we are making the default of one\n(PostgresNode::psql) look like the other (PostgresNode::safe_psql),\nthen we lose no actual feature by dropping safe_psql.\n\n> Yeah, but only if the test cases are independent, which I think is\n> mostly not true in our TAP scripts. Otherwise you're just looking\n> at cascading errors.\n\nYep. We have a couple of cases though where things are quite\nindependent, like the 2PC suite divided into sequences of different\ntransactions, but mostly there are dependencies between one step and\nthe follow-up ones.\n\n> Yup, the tradeoff is people possibly having test scripts outside\n> our tree that would break, versus the possibility that we'll back-patch\n> test changes that don't behave as expected in back branches. I don't\n> know if the former is true, but I'm afraid the latter is a certainty\n> if we don't back-patch.\n\nExactly, that's why I am wondering how wide breakages in those\nout-of-the-tree tests would go as we have PostgresNode since 9.6.\nFacing this choice makes me uneasy, which is why I would tend to only\ndo incompatible things on HEAD. Another, safer, possibility would be\nto introduce in back-branches an extra psql-like routine enforcing\nerrors which we use in our tests, to keep the former ones for\ncompatibility, and to drop the old ones on HEAD. It is never fun to\nface sudden errors on a system when doing a minor upgrade.\n--\nMichael", "msg_date": "Fri, 30 Aug 2019 13:29:48 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Improve error detections in TAP tests by spreading safe_psql" } ]
[ { "msg_contents": "I bumped into a little bug in BRIN, while hacking on something \nunrelated. This causes a segfault, or an assertion failure if assertions \nare enabled:\n\nCREATE TABLE brintest (n numrange);\nCREATE INDEX brinidx ON brintest USING brin (n);\n\nINSERT INTO brintest VALUES ('empty');\nINSERT INTO brintest VALUES (numrange(0, 2^1000::numeric));\nINSERT INTO brintest VALUES ('(-1, 0)');\n\nSELECT brin_desummarize_range('brinidx',0);\nSELECT brin_summarize_range('brinidx',0) ;\n\ngdb backtrace:\n\nProgram terminated with signal SIGSEGV, Segmentation fault.\n#0 0x0000560fef71f4b2 in GetMemoryChunkContext (pointer=0x7fed65a8fc30) \nat ../../../../src/include/utils/memutils.h:129\n129\t\tAssertArg(MemoryContextIsValid(context));\n(gdb) bt\n#0 0x0000560fef71f4b2 in GetMemoryChunkContext (pointer=0x7fed65a8fc30) \nat ../../../../src/include/utils/memutils.h:129\n#1 0x0000560fef721290 in pfree (pointer=0x7fed65a8fc30) at mcxt.c:1033\n#2 0x0000560fef0bd13f in brin_inclusion_add_value \n(fcinfo=0x7ffc4cd36220) at brin_inclusion.c:239\n#3 0x0000560fef6ee543 in FunctionCall4Coll (flinfo=0x560ff05d0cf0, \ncollation=0, arg1=94626457109880, arg2=94626457868896, \narg3=140657589550088, arg4=0) at fmgr.c:1214\n#4 0x0000560fef0b39b7 in brinbuildCallback (index=0x7fed64f37460, \nhtup=0x560ff0685d68, values=0x7ffc4cd365d0, isnull=0x7ffc4cd365b0, \ntupleIsAlive=true, brstate=0x560ff06859e0)\n at brin.c:650\n#5 0x0000560fef12e418 in heapam_index_build_range_scan \n(heapRelation=0x7fed64f37248, indexRelation=0x7fed64f37460, \nindexInfo=0x560ff0685b48, allow_sync=false, anyvisible=true,\n progress=false, start_blockno=0, numblocks=1, \ncallback=0x560fef0b37c9 <brinbuildCallback>, \ncallback_state=0x560ff06859e0, scan=0x560ff0685d18) at heapam_handler.c:1663\n#6 0x0000560fef0b2858 in table_index_build_range_scan \n(table_rel=0x7fed64f37248, index_rel=0x7fed64f37460, \nindex_info=0x560ff0685b48, allow_sync=false, anyvisible=true, \nprogress=false,\n start_blockno=0, numblocks=1, callback=0x560fef0b37c9 \n<brinbuildCallback>, callback_state=0x560ff06859e0, scan=0x0) at \n../../../../src/include/access/tableam.h:1544\n#7 0x0000560fef0b4dac in summarize_range (indexInfo=0x560ff0685b48, \nstate=0x560ff06859e0, heapRel=0x7fed64f37248, heapBlk=0, heapNumBlks=1) \nat brin.c:1240\n#8 0x0000560fef0b50d9 in brinsummarize (index=0x7fed64f37460, \nheapRel=0x7fed64f37248, pageRange=0, include_partial=true, \nnumSummarized=0x7ffc4cd36928, numExisting=0x0) at brin.c:1375\n#9 0x0000560fef0b43bf in brin_summarize_range (fcinfo=0x560ff06840d0) \nat brin.c:933\n#10 0x0000560fef339acc in ExecInterpExpr (state=0x560ff0683fe8, \necontext=0x560ff0683ce8, isnull=0x7ffc4cd36c17) at execExprInterp.c:650\n\nAnalysis:\n\nThis is a memory management issue in the brin_inclusion_add_value() \nfunction:\n\n\t/* Finally, merge the new value to the existing union. */\n\tfinfo = inclusion_get_procinfo(bdesc, attno, PROCNUM_MERGE);\n\tAssert(finfo != NULL);\n\tresult = FunctionCall2Coll(finfo, colloid,\n\t\t\t\t\t\t\t column->bv_values[INCLUSION_UNION], newval);\n\tif (!attr->attbyval)\n\t\tpfree(DatumGetPointer(column->bv_values[INCLUSION_UNION]));\n\tcolumn->bv_values[INCLUSION_UNION] = result;\n\nThis assumes that the merge function returns a newly-palloc'd value. \nThat's a shaky assumption; if one of the arguments is an empty range, \nrange_merge() returns the other argument, rather than a newly \nconstructed value. And surely we can't assume assume that for \nuser-defined opclasses.\n\nWhen that happens, we store the 'newval' directly in \ncolumn->bv_values[INCLUSION_UNION], but it is allocated in a \nshortly-lived memory context (or points directly to a buffer in the \nbuffer cache). On the next call, we try to pfree() the old value, but \nthe memory context that contained it was already reset.\n\nIt took a while to work out the script to reproduce it. The first value \npassed to brin_inclusion_add_value() must be an empty range, so that \ncolumn->bv_values[INCLUSION_UNION] is set to an empty range. On the \nsecond call, the new value must be non-empty, so that range_merge() \nreturns 'newval' unchanged. And it must be a very large value, because \nif it uses a short varlen header, the PG_GETARG_RANGE_P() call in \nrange_merge() will make a copy of it.\n\nbrin_inclusion_union() has a similar issue, but I didn't write a script \nto reproduce that. Fix attached.\n\n- Heikki", "msg_date": "Wed, 28 Aug 2019 12:22:17 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": true, "msg_subject": "Crash in BRIN summarization" }, { "msg_contents": "Thank you for your fix.\n\n> This assumes that the merge function returns a newly-palloc'd value.\n> That's a shaky assumption; if one of the arguments is an empty range,\n> range_merge() returns the other argument, rather than a newly\n> constructed value. And surely we can't assume assume that for\n> user-defined opclasses.\n\nYour analysis looks right to me.\n\n> brin_inclusion_union() has a similar issue, but I didn't write a script\n> to reproduce that. Fix attached.\n\nI am not sure about this part. If it's okay to use col_a->bv_values\nwithout copying, it should also be okay to use col_b->bv_values, no?\n\n\n", "msg_date": "Wed, 28 Aug 2019 12:03:59 +0100", "msg_from": "Emre Hasegeli <emre@hasegeli.com>", "msg_from_op": false, "msg_subject": "Re: Crash in BRIN summarization" }, { "msg_contents": "Heikki Linnakangas <hlinnaka@iki.fi> writes:\n> I bumped into a little bug in BRIN, while hacking on something \n> unrelated. This causes a segfault, or an assertion failure if assertions \n> are enabled:\n\nGood catch.\n\n> Fix attached.\n\nHm, I don't particularly care for directly comparing Datum values\nlike that. We don't do that elsewhere (I think) and it feels like\na type violation to me. Since you've already tested for !attbyval,\nI think it'd be legitimate to extract the pointer values and compare\nthose, eg\n\n\tif (!attr->attbyval &&\n\t DatumGetPointer(result) != DatumGetPointer(column->bv_values[INCLUSION_UNION]))\n\nI realize that this makes no difference in terms of the machine\ncode (at least for most machines?) but it avoids breaking the\nDatum abstraction.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 28 Aug 2019 10:00:59 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Crash in BRIN summarization" }, { "msg_contents": "On 2019-Aug-28, Heikki Linnakangas wrote:\n\n> I bumped into a little bug in BRIN, while hacking on something unrelated.\n> This causes a segfault, or an assertion failure if assertions are enabled:\n\nHeikki, I just noticed that you haven't pushed this bugfix. Would you\nlike me to? (If I don't hear from you, I'll probably get to it next\nweek.)\n\nThanks\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 17 Jan 2020 18:35:46 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Crash in BRIN summarization" }, { "msg_contents": "On 17/01/2020 23:35, Alvaro Herrera wrote:\n> On 2019-Aug-28, Heikki Linnakangas wrote:\n> \n>> I bumped into a little bug in BRIN, while hacking on something unrelated.\n>> This causes a segfault, or an assertion failure if assertions are enabled:\n> \n> Heikki, I just noticed that you haven't pushed this bugfix. Would you\n> like me to? (If I don't hear from you, I'll probably get to it next\n> week.)\n\nSorry, forgot all about it. Pushed now.\n\nOn 28/08/2019 14:03, Emre Hasegeli wrote:\n >> brin_inclusion_union() has a similar issue, but I didn't write a script\n >> to reproduce that. Fix attached.\n >\n > I am not sure about this part. If it's okay to use col_a->bv_values\n > without copying, it should also be okay to use col_b->bv_values, no?\n\nNo, the 'a' and 'b' arguments are not symmetric. 'a' is in a long-lived \nmemory context, and the function modifies it in place, whereas 'b' is \nshort-lived and isn't touched by the function.\n\n- Heikki\n\n\n", "msg_date": "Mon, 20 Jan 2020 10:44:28 +0200", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": true, "msg_subject": "Re: Crash in BRIN summarization" }, { "msg_contents": "On 2020-Jan-20, Heikki Linnakangas wrote:\n\n> Sorry, forgot all about it. Pushed now.\n\nThank you!\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 20 Jan 2020 09:14:58 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Crash in BRIN summarization" } ]
[ { "msg_contents": "Hi, \n\n      \n\n          I have a  join query with is not distinct from criteria (select * from table1 join table2 on a is not  distinct from b). on examining,  it was the  nested loop join that makes the query slow.  For join with ' is not distinct from ' qual can't the planner choose  hash-join over nested loop  or will there be any problem by doing so. Kindly enlighten me about the same.\n\n\nThanks\nPradeep\nHi,                 I have a  join query with is not distinct from criteria (select * from table1 join table2 on a is not  distinct from b). on examining,  it was the  nested loop join that makes the query slow.  For join with ' is not distinct from ' qual can't the planner choose  hash-join over nested loop  or will there be any problem by doing so. Kindly enlighten me about the same.ThanksPradeep", "msg_date": "Wed, 28 Aug 2019 16:19:08 +0530", "msg_from": "Narendra Pradeep U U <narendra.pradeep@zohocorp.com>", "msg_from_op": true, "msg_subject": "Converting Nested loop to hashjoin for not is distinct from case" } ]
[ { "msg_contents": "Hello,\n\nI hear that not recommended to set pg_resetwal with --wal-segsize for wal\nincreasing. Are any more detailed information exists about it? What an\neffects could be? Does it possible change it due full offline?\n\nRegards, Paul\n\n Hello,I hear that not recommended to set pg_resetwal with --wal-segsize for wal increasing. Are any more detailed information exists about it? What an effects could be? Does it possible change it due full offline?Regards,\nPaul", "msg_date": "Wed, 28 Aug 2019 14:45:31 +0300", "msg_from": "Pavel Demidov <zeller56@gmail.com>", "msg_from_op": true, "msg_subject": "" }, { "msg_contents": "On 2019-Aug-28, Pavel Demidov wrote:\n\n> I hear that not recommended to set pg_resetwal with --wal-segsize for wal\n> increasing. Are any more detailed information exists about it? What an\n> effects could be? Does it possible change it due full offline?\n\nThe manual contains a warning about it:\n\n While pg_resetwal will set the WAL starting address\n beyond the latest existing WAL segment file, some segment size changes\n can cause previous WAL file names to be reused. It is recommended to\n use -l together with this option to manually set the\n WAL starting address if WAL file name overlap will cause problems with\n your archiving strategy.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 5 Sep 2019 10:18:52 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "changing wal segsize with pg_resetwal" } ]
[ { "msg_contents": "I'm pretty new to this, and I find it hard trying to make some sense from\nsrc code.\n\nI'm trying to understand, logical decoding.\n\nIn `HEAP2` RMGR,\nwhat does HEAP2_NEW_CID operation do?\n\ncan somebody give an example, when this type of record is written to wal\nfiles.\n\nWhen logical decoding decodes this record, what it means to it.\n\nIs it a transaction with sub-transactions, which does some ddl changes?\n\n\n-- \nThank you\n\nI'm pretty new to this, and I find it hard trying to make some sense from src code.I'm trying to understand, logical decoding.In `HEAP2` RMGR,what does HEAP2_NEW_CID operation do?can somebody give an example, when this type of record is written to wal files.When logical decoding decodes this record, what it means to it.Is it a transaction with sub-transactions, which does some ddl changes?-- Thank you", "msg_date": "Wed, 28 Aug 2019 17:46:03 +0530", "msg_from": "nilsocket <nilsocket@gmail.com>", "msg_from_op": true, "msg_subject": "Doubt regarding logical decoding" } ]
[ { "msg_contents": "Hello\nWe already have function pg_get_userbyid(oid) with lookup in pg_authid catalog. My collegue ask me can we add similar function pg_get_databasebyid(oid) with lookup in pg_databases.\nIt is simple function to get a database name by oid and fallback to 'unknown (OID=n)' if missing.\n\nThe proposed patch is attached. Currently I missed the tests - I doubt which file in src/test/regress/sql/ is the most suitable. pg_get_userbyid is called from privileges.sql only.\n\nregards, Sergei", "msg_date": "Wed, 28 Aug 2019 15:38:42 +0300", "msg_from": "Sergei Kornilov <sk@zsrv.org>", "msg_from_op": true, "msg_subject": "pg_get_databasebyid(oid)" }, { "msg_contents": "On Wed, Aug 28, 2019 at 5:38 PM Sergei Kornilov <sk@zsrv.org> wrote:\n\n> Hello\n> We already have function pg_get_userbyid(oid) with lookup in pg_authid\n> catalog. My collegue ask me can we add similar function\n> pg_get_databasebyid(oid) with lookup in pg_databases.\n> It is simple function to get a database name by oid and fallback to\n> 'unknown (OID=n)' if missing.\n>\n> The proposed patch is attached. Currently I missed the tests - I doubt\n> which file in src/test/regress/sql/ is the most suitable. pg_get_userbyid\n> is called from privileges.sql only.\n>\n> regards, Sergei\n\n\nPlease add that to commitfest.\n\n\n-- \nIbrar Ahmed\n\nOn Wed, Aug 28, 2019 at 5:38 PM Sergei Kornilov <sk@zsrv.org> wrote:Hello\nWe already have function pg_get_userbyid(oid) with lookup in pg_authid catalog. My collegue ask me can we add similar function pg_get_databasebyid(oid) with lookup in pg_databases.\nIt is simple function to get a database name by oid and fallback to 'unknown (OID=n)' if missing.\n\nThe proposed patch is attached. Currently I missed the tests - I doubt which file in src/test/regress/sql/ is the most suitable. pg_get_userbyid is called from privileges.sql only.\n\nregards, SergeiPlease add that to commitfest. -- Ibrar Ahmed", "msg_date": "Wed, 28 Aug 2019 17:49:40 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg_get_databasebyid(oid)" }, { "msg_contents": "> Please add that to commitfest.\n\nDone: https://commitfest.postgresql.org/24/2261/\n\nregards, Sergei\n\n\n", "msg_date": "Wed, 28 Aug 2019 16:05:07 +0300", "msg_from": "Sergei Kornilov <sk@zsrv.org>", "msg_from_op": true, "msg_subject": "Re: pg_get_databasebyid(oid)" }, { "msg_contents": "On Wed, Aug 28, 2019 at 6:05 PM Sergei Kornilov <sk@zsrv.org> wrote:\n\n> > Please add that to commitfest.\n>\n> Done: https://commitfest.postgresql.org/24/2261/\n>\n> regards, Sergei\n>\nHi,\n\nI have checked the code, the function \"pg_get_userbyid\" is used in many\nplaces in code. I am just curious why we need that \"pg_get_databasebyid\"\nfunction. Is there a need for this function for the user?\n\n\n-- \nIbrar Ahmed\n\nOn Wed, Aug 28, 2019 at 6:05 PM Sergei Kornilov <sk@zsrv.org> wrote:> Please add that to commitfest.\n\nDone: https://commitfest.postgresql.org/24/2261/\n\nregards, Sergei\nHi,I have checked the code, the function \"pg_get_userbyid\" is used in many places in code. I am just curious why we need that  \"pg_get_databasebyid\" function. Is there a need for this function for the user?-- Ibrar Ahmed", "msg_date": "Thu, 29 Aug 2019 13:59:24 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg_get_databasebyid(oid)" }, { "msg_contents": "Hello\n\n> Is there a need for this function for the user?\n\nThis was feature request from user. I got such comment:\n\nThis function is useful when working with pg_stat_statements. For obtaining a databаse name for particular query you need to join pg_database relation, but for obtaining an username you just need pg_get_userbyid(). So it will be useful not to join extra relation and get a database name using the similar function - pg_get_databasebyid().\n\nregards, Sergei\n\n\n", "msg_date": "Thu, 29 Aug 2019 13:16:25 +0300", "msg_from": "Sergei Kornilov <sk@zsrv.org>", "msg_from_op": true, "msg_subject": "Re: pg_get_databasebyid(oid)" }, { "msg_contents": "On Thu, Aug 29, 2019 at 3:16 PM Sergei Kornilov <sk@zsrv.org> wrote:\n\n> Hello\n>\n> > Is there a need for this function for the user?\n>\n> This was feature request from user. I got such comment:\n>\n> This function is useful when working with pg_stat_statements. For\n> obtaining a databаse name for particular query you need to join pg_database\n> relation, but for obtaining an username you just need pg_get_userbyid(). So\n> it will be useful not to join extra relation and get a database name using\n> the similar function - pg_get_databasebyid().\n>\n> regards, Sergei\n>\n\nHi,\nI think its a user request and don't require to be in the core of\nPostgreSQL.\nA simple SQL function can fulfill the requirement of the user.\n\nCREATE OR REPLACE FUNCTION pg_get_databasebyid(dboid integer) RETURNS name\nAS $$\n\n SELECT datname from pg_database WHERE oid = dboid;\n$$ LANGUAGE SQL;\n\n-- \nIbrar Ahmed\n\nOn Thu, Aug 29, 2019 at 3:16 PM Sergei Kornilov <sk@zsrv.org> wrote:Hello\n\n> Is there a need for this function for the user?\n\nThis was feature request from user. I got such comment:\n\nThis function is useful when working with pg_stat_statements. For obtaining a databаse name for particular query you need to join pg_database relation, but for obtaining an username you just need pg_get_userbyid(). So it will be useful not to join extra relation and get a database name using the similar function - pg_get_databasebyid().\n\nregards, SergeiHi,I think its a user request and don't require to be in the core of PostgreSQL.  A simple SQL function can fulfill the requirement of the user.\nCREATE OR REPLACE FUNCTION pg_get_databasebyid(dboid integer) RETURNS name AS $$\n    SELECT datname from pg_database WHERE oid = dboid;\n$$ LANGUAGE SQL;-- Ibrar Ahmed", "msg_date": "Thu, 29 Aug 2019 15:47:40 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: pg_get_databasebyid(oid)" }, { "msg_contents": "On Thu, Aug 29, 2019 at 03:47:40PM +0500, Ibrar Ahmed wrote:\n> I think its a user request and don't require to be in the core of\n> PostgreSQL.\n> A simple SQL function can fulfill the requirement of the user.\n> \n> CREATE OR REPLACE FUNCTION pg_get_databasebyid(dboid integer) RETURNS name\n> AS $$\n> \n> SELECT datname from pg_database WHERE oid = dboid;\n> $$ LANGUAGE SQL;\n\nIndeed, I think that we can drop the patch. FWIW, I find the\nsemantics of pg_get_userbyid() horrible when it comes to return a\nresult for a non-existing user with its own way of defining how this\ninformation should show up. Returning NULL would be more natural, so\nI don't think that we should make more functions behave the same way.\n--\nMichael", "msg_date": "Wed, 4 Sep 2019 12:54:55 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pg_get_databasebyid(oid)" }, { "msg_contents": "Hello\n\nThank you for attention! I marked CF entry as returned with feedback.\n\nregards, Sergei\n\n\n", "msg_date": "Wed, 04 Sep 2019 12:29:13 +0300", "msg_from": "Sergei Kornilov <sk@zsrv.org>", "msg_from_op": true, "msg_subject": "Re: pg_get_databasebyid(oid)" } ]
[ { "msg_contents": "Hello devs,\n\nThe attached patch improves psql code coverage by adding a specific TAP \ntest. The 1709 tests take 4 seconds CPU (6.3 elapsed time) on my laptop.\n\nThe infrastructure is updated to require perl module \"Expect\", allowing to \ntest interactive features such as tab completion and prompt changes.\n\nCoverage in \"src/bin/psql\" jumps from 40.0% of lines and 41.9% of \nfunctions to 78.4% of lines and 98.1% of functions with \"check-world\".\n\n-- \nFabien.", "msg_date": "Wed, 28 Aug 2019 16:31:00 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": true, "msg_subject": "psql - improve test coverage from 41% to 88%" }, { "msg_contents": "Attached is a rebase after TestLib.pm got a documentation in 6fcc40b1.\n\n> The attached patch improves psql code coverage by adding a specific TAP test. \n> The 1709 tests take 4 seconds CPU (6.3 elapsed time) on my laptop.\n>\n> The infrastructure is updated to require perl module \"Expect\", allowing to \n> test interactive features such as tab completion and prompt changes.\n>\n> Coverage in \"src/bin/psql\" jumps from 40.0% of lines and 41.9% of functions \n> to 78.4% of lines and 98.1% of functions with \"check-world\".\n\n-- \nFabien.", "msg_date": "Tue, 3 Sep 2019 08:06:43 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": true, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "On Tue, Sep 03, 2019 at 08:06:43AM +0200, Fabien COELHO wrote:\n> Attached is a rebase after TestLib.pm got a documentation in\n> 6fcc40b1.\n\nI am not completely sure what to think about this patch, but here are\nsome high-level comments.\n\n+=item $node->icommand_checks(cmd, ...)\n+\n+=cut\n+\n+sub icommand_checks\n\nSurely this can have a better description, like say\nPostgresNode::command_checks_all.\n\nIs Expect compatible down to perl 5.8.0 which is the minimum required\nfor the TAP tests (see src/test/perl/README)?\n\nThere are cases where we don't support tab completion, aka no\nUSE_READLINE. So tests would need to be skipped.\n\n- \\a \\C arg1 \\c arg1 arg2 arg3 arg4 \\cd arg1 \\conninfo\n+ \\a\n+ \\C arg1\nWhy are you changing that? Your patch does not touch the logic of\npsql. Could it make sense as a separate patch to shape better the\ntests?\n\n--- a/src/bin/psql/describe.c\n+++ b/src/bin/psql/describe.c\n@@ -307,6 +307,7 @@ describeTablespaces(const char *pattern, bool\nverbose)\n * a for aggregates\n * n for normal\n+ * p for procedure\nThis is a separate issue, fixed.\n--\nMichael", "msg_date": "Wed, 11 Sep 2019 15:25:59 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "Bonjour Michaᅵl,\n\n> +=item $node->icommand_checks(cmd, ...)\n> +\n> +=cut\n> +\n> +sub icommand_checks\n>\n> Surely this can have a better description, like say\n> PostgresNode::command_checks_all.\n\nOk.\n\n> Is Expect compatible down to perl 5.8.0 which is the minimum required\n> for the TAP tests (see src/test/perl/README)?\n\nI think so. It looks like this has existed for a very long time (22 \nyears?), but I cannot test it simply against a perl 5.8.\n\n> There are cases where we don't support tab completion, aka no\n> USE_READLINE. So tests would need to be skipped.\n\nGood catch. I added a skip if it detects that history/readline is \ndisabled.\n\n> - \\a \\C arg1 \\c arg1 arg2 arg3 arg4 \\cd arg1 \\conninfo\n> + \\a\n> + \\C arg1\n> Why are you changing that?\n\nAFAICR this is because the coverage was not the same:-) Some backslash \ncommands just skip silently to the end of the line, so that intermediate \n\\commands on the same line are not recognized/processed the same, so I \nmoved everything on one line to avoid this.\n\n> Your patch does not touch the logic of psql. Could it make sense as a \n> separate patch to shape better the tests?\n\nNope, this is not just reshaping, it is really about improving coverage.\n\n> --- a/src/bin/psql/describe.c\n> +++ b/src/bin/psql/describe.c\n> @@ -307,6 +307,7 @@ describeTablespaces(const char *pattern, bool\n> verbose)\n> * a for aggregates\n> * n for normal\n> + * p for procedure\n> This is a separate issue, fixed.\n\nOk.\n\nAttached v3 which fixes the outlined issues.\n\n-- \nFabien.", "msg_date": "Wed, 11 Sep 2019 22:52:01 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": true, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "On Wed, Sep 11, 2019 at 10:52:01PM +0200, Fabien COELHO wrote:\n> AFAICR this is because the coverage was not the same:-) Some backslash\n> commands just skip silently to the end of the line, so that intermediate\n> \\commands on the same line are not recognized/processed the same, so I moved\n> everything on one line to avoid this.\n\nI see. So basically this tests for more code paths to ignore\nbackslash commands and it improves the coverage of \\elif. Applied\nafter fixing two nits:\n- Indentation was incorrect.\n- Moved the \\elif test closer to the existing one for the false\nbranch (you can grep #2 to find it).\n--\nMichael", "msg_date": "Thu, 12 Sep 2019 10:37:24 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "> On Wed, Sep 11, 2019 at 10:52:01PM +0200, Fabien COELHO wrote:\n>> AFAICR this is because the coverage was not the same:-) Some backslash\n>> commands just skip silently to the end of the line, so that intermediate\n>> \\commands on the same line are not recognized/processed the same, so I moved\n>> everything on one line to avoid this.\n>\n> I see. So basically this tests for more code paths to ignore\n> backslash commands and it improves the coverage of \\elif. Applied\n> after fixing two nits:\n> - Indentation was incorrect.\n> - Moved the \\elif test closer to the existing one for the false\n> branch (you can grep #2 to find it).\n\nOk. Rebased version added, with some minor changes to improve readability \n(comments, variables).\n\n-- \nFabien.", "msg_date": "Thu, 12 Sep 2019 08:25:50 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": true, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "On Thu, Sep 12, 2019 at 11:56 AM Fabien COELHO <coelho@cri.ensmp.fr> wrote:\n>\n> > On Wed, Sep 11, 2019 at 10:52:01PM +0200, Fabien COELHO wrote:\n> >> AFAICR this is because the coverage was not the same:-) Some backslash\n> >> commands just skip silently to the end of the line, so that intermediate\n> >> \\commands on the same line are not recognized/processed the same, so I moved\n> >> everything on one line to avoid this.\n> >\n> > I see. So basically this tests for more code paths to ignore\n> > backslash commands and it improves the coverage of \\elif. Applied\n> > after fixing two nits:\n> > - Indentation was incorrect.\n> > - Moved the \\elif test closer to the existing one for the false\n> > branch (you can grep #2 to find it).\n>\n> Ok. Rebased version added, with some minor changes to improve readability\n> (comments, variables).\n>\n>\nFew comments:\n+sub create_test_file\n+{\n+ my ($fname, $contents) = @_;\n+ my $fn = $node->basedir . '/' . $fname;\n+ #ok(not -e $fn, \"$fn must not already exists\");\n+ append_to_file($fn, $contents);\n+ return $fn;\n+}\n\nCommented line can be removed\n\n+# nope, interacts on tty\n+#psql('-W', 0, \"foo\\n\", [ qr{^$} ], [ qr{^$} ], 'psql -W');\n+psql('-x', 0, \"SELECT 1 AS one, 2 AS two;\\n\", [ qr{one \\| 1.*two \\|\n2}s ], $EMPTY, 'psql -x');\n+# some issue, \\0 is not welcome somewhere\n+#psql('-A -z', \"SELECT 1 AS one, 2 AS two;\\n\", [ qr{one.two}s,\nqr{1.2}s ], $EMPTY, 'psql -z');\n+#psql('-A -0', \"SELECT 1 AS one, 2 AS two;\\n\", [ qr{two.1}s ],\n$EMPTY, 'psql -0');\n+psql('-1', 0, \"SELECT 54;\\nSELECT 32;\\n\", [ qr{54}, qr{32} ], $EMPTY,\n'psql -1');\n\nCommented lines can be removed\n\n+ [ \"\\\\lo_list\\n\", [ qr{Large objects} ] ],\n+ [ \"\\\\if true\\\\q\\\\endif\\n\", $EMPTY ],\n+ # ???\n+ #[ \"SELECT md5('hello world');\\n\\\\s\\n\", [ qr{5eb63bbbe0}, qr{SELECT md5} ] ],\n+ [ \"\\\\set\\n\", [ qr{ENCODING = }, qr{VERSION_NUM = } ] ],\n+ [ \"\\\\set COMP_KEYWORD_CASE preserve-lower\\n\\\\set COMP_KEYWORD_CASE lower\\n\" .\n\n#[ \"Select\"] commented line can be removed\n??? can be changed to some suitable heading\n\n+psql('', 0, \"\\\\s /dev/null\\n\", $EMPTY, $EMPTY, 'psql \\s null');\n+\n+# tab-complation\n+ipsql('-P pager', 0, 5,\n+ [ # commands\n\ntab-complation to be changed to tab-completion\n\n+ # but the coverage works as expected.\n+ #[ \"CREATE \\t\", qr/i(MATERIALIZED VIEW.*postgres=\\# )?/s ],\n+ #[ \"\\\\r\\n\", qr/Query buffer reset.*postgres=\\# /s ],\n+ [ \"CREATE \\t\\\\r\\n\", qr/Query buffer reset.*postgres=\\# /s ],\n+ #[ \"DROP \\t\", qr/(UNLOGGED.*postgres=\\# )?/s ],\n+ #[ \"\\\\r\\n\", qr/Query buffer reset.*postgres=\\# /s ],\n+ [ \"DROP \\t\\\\r\\n\", qr/Query buffer reset.*postgres=\\# /s ],\n+ #[ \"ALTER \\t\", qr/(TABLESPACE.*postgres=\\# )/s ],\n+ #[ \"\\\\r\\n\", qr/Query buffer reset.*postgres=\\# /s ],\n\nCommented lines can be removed, some more are present below these lines also.\n\nRegards,\nVignesh\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 12 Sep 2019 13:37:37 +0530", "msg_from": "vignesh C <vignesh21@gmail.com>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": ">> Ok. Rebased version added, with some minor changes to improve readability\n>> (comments, variables).\n>\n> Few comments: [...]\n>\n> Commented line can be removed\n> Commented lines can be removed\n> ??? can be changed to some suitable heading\n> tab-complation to be changed to tab-completion\n> Commented lines can be removed, some more are present below these lines also.\n\nThanks for this review.\n\nThe lines were really tests I did that had some issues because of the way \nthe Expect module works, and are not useful for inclusion in the code \nbase.\n\nHere is a v5.\n\n-- \nFabien Coelho - CRI, MINES ParisTech", "msg_date": "Thu, 12 Sep 2019 10:45:06 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": true, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "On Thu, Sep 12, 2019 at 2:15 PM Fabien COELHO <coelho@cri.ensmp.fr> wrote:\n>\n>\n> >> Ok. Rebased version added, with some minor changes to improve readability\n> >> (comments, variables).\n> >\n> > Few comments: [...]\n> >\n> > Commented line can be removed\n> > Commented lines can be removed\n> > ??? can be changed to some suitable heading\n> > tab-complation to be changed to tab-completion\n> > Commented lines can be removed, some more are present below these lines also.\n>\n> Thanks for this review.\n>\n> The lines were really tests I did that had some issues because of the way\n> the Expect module works, and are not useful for inclusion in the code\n> base.\n>\n> Here is a v5.\nFew more in icommand_checks subroutine:\n\n+\n+ #$ps->slave->stty(qw(raw -echo));\n+ $ps->slave->stty(qw(raw));\n+ my $n = 0;\n+ for my $test (@$inout)\n+ {\n+ #warn \"test: @$test\";\n+ my ($in, @out) = @$test;\n+ $n++;\n+ #warn \"in: $in\";\n+ #warn \"out: @out\";\n+ $ps->send($in);\n\nFew unwanted code can be removed.\n\nRegards,\nVignesh\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 12 Sep 2019 16:18:36 +0530", "msg_from": "vignesh C <vignesh21@gmail.com>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": ">> Here is a v5.\n\n> Few more in icommand_checks subroutine:\n> Few unwanted code can be removed.\n\nIndeed, more debug and test code.\n\nAttached v6 fixes these, and I checked for remaining scrubs without \nfinding any.\n\n-- \nFabien.", "msg_date": "Thu, 12 Sep 2019 13:19:28 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": true, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "I think the TestLib.pm changes should be done separately, not together\nwith the rest of the hacking in this patch.\n\nMostly, because I think they're going to cause trouble. Adding a\nparameter in the middle of the list may cause trouble for third-party\nusers of TestLib. I propose that we make the routines a bit smarter to\ncope with the API change: use named parameters instead. And in order to\ndo that without having to change existing users of command_check, make\nit so that the routine checks whether the parameter is a hashref, and\nbehave differently. So when called as in the existing callsites (five\nscalar paramters) it behaves as currently.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 12 Sep 2019 12:14:16 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "On Thu, Sep 12, 2019 at 12:14:16PM -0300, Alvaro Herrera wrote:\n> Mostly, because I think they're going to cause trouble. Adding a\n> parameter in the middle of the list may cause trouble for third-party\n> users of TestLib. I propose that we make the routines a bit smarter to\n> cope with the API change: use named parameters instead. And in order to\n> do that without having to change existing users of command_check, make\n> it so that the routine checks whether the parameter is a hashref, and\n> behave differently. So when called as in the existing callsites (five\n> scalar parameters) it behaves as currently.\n\n+1.\n--\nMichael", "msg_date": "Fri, 13 Sep 2019 12:17:46 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "On Thu, Sep 12, 2019 at 4:49 PM Fabien COELHO <coelho@cri.ensmp.fr> wrote:\n>\n>\n> >> Here is a v5.\n>\n> > Few more in icommand_checks subroutine:\n> > Few unwanted code can be removed.\n>\n> Indeed, more debug and test code.\n>\n> Attached v6 fixes these, and I checked for remaining scrubs without\n> finding any.\n>\nFew comments:\n+ [ 'START TRANSACTION', [ qr{ISOLATION LEVEL}, qr{(?!BEGIN)} ] ],\n+ [ 'TABLE', [ qr{ONLY} ] ], # hmmm...\n+ [ 'TRUNCATE', [ qr{CONTINUE IDENTITY} ] ],\n+ [ 'UNLISTEN', [ ] ],\n\nWe can remove # hmmm... if not required\n\n+ [ 'UPDATE', [ qr{RETURNING} ] ],\n+ [ 'VACUUM', [ qr{FREEZE} ] ],\n+ [ 'VALUES', [ qr{ORDER BY} ] ],\n+ [ 'WITH', [ qr{RECURSIVE} ] ], # SELECT duplicate?\n+);\n\nWe can remove # SELECT duplicate? if not required\n\n+\n+psql('--log-file=/dev/null', 0, \"SELECT 5432 AS pg\\n\",\n+ [ qr/\\b5432\\b/ ], $EMPTY, 'psql -L null');\n+\n+psql('', 0, \"\\\\copy public.regress_psql_tap_1_t1(data) FROM PROGRAM\n'echo moe'\\n\",\n+ [ qr/COPY 1\\b/ ], $EMPTY, 'psql copy echo');\n+psql('', 0, \"\\\\copy public.regress_psql_tap_1_t1(data) TO PROGRAM 'cat'\\n\",\n+ [ qr/COPY 1\\b/ ], $EMPTY, 'psql copy cat'); # :-)\n+\n+END_UNIX_ZONE:\n\nWe can remove # :-) if not required\n\n\nRegards,\nVignesh\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 17 Sep 2019 16:48:06 +0530", "msg_from": "vignesh C <vignesh21@gmail.com>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "Hi Fabien,\n\nOn Tue, Sep 17, 2019 at 04:48:06PM +0530, vignesh C wrote:\n> Few comments:\n> + [ 'START TRANSACTION', [ qr{ISOLATION LEVEL}, qr{(?!BEGIN)} ] ],\n> + [ 'TABLE', [ qr{ONLY} ] ], # hmmm...\n> + [ 'TRUNCATE', [ qr{CONTINUE IDENTITY} ] ],\n> + [ 'UNLISTEN', [ ] ],\n> \n> We can remove # hmmm... if not required\n> \n> + [ 'UPDATE', [ qr{RETURNING} ] ],\n> + [ 'VACUUM', [ qr{FREEZE} ] ],\n> + [ 'VALUES', [ qr{ORDER BY} ] ],\n> + [ 'WITH', [ qr{RECURSIVE} ] ], # SELECT duplicate?\n> +);\n> \n> We can remove # SELECT duplicate? if not required\n> \n> +\n> +psql('--log-file=/dev/null', 0, \"SELECT 5432 AS pg\\n\",\n> + [ qr/\\b5432\\b/ ], $EMPTY, 'psql -L null');\n> +\n> +psql('', 0, \"\\\\copy public.regress_psql_tap_1_t1(data) FROM PROGRAM\n> 'echo moe'\\n\",\n> + [ qr/COPY 1\\b/ ], $EMPTY, 'psql copy echo');\n> +psql('', 0, \"\\\\copy public.regress_psql_tap_1_t1(data) TO PROGRAM 'cat'\\n\",\n> + [ qr/COPY 1\\b/ ], $EMPTY, 'psql copy cat'); # :-)\n> +\n> +END_UNIX_ZONE:\n> \n> We can remove # :-) if not required\n\nPlease note that you have received comments on this patch a couple of\nweeks ago. The patch was still marked as \"needs review\", which was\nincorrect, and it does not apply. Perhaps you did not notice it, so I\nam moving it to next CF, waiting on author for a rebase and for\nreplies on those comments.\n--\nMichael", "msg_date": "Wed, 27 Nov 2019 14:03:21 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "Bonjour Michaᅵl,\n\n> Please note that you have received comments on this patch a couple of\n> weeks ago. The patch was still marked as \"needs review\", which was\n> incorrect, and it does not apply. Perhaps you did not notice it, so I\n> am moving it to next CF, waiting on author for a rebase and for\n> replies on those comments.\n\nIndeed, I did not notice.\n\nAttached a rebase, which also removes the 3 comments pointed out by \nVignesh.\n\n-- \nFabien.", "msg_date": "Wed, 27 Nov 2019 10:14:16 +0100 (CET)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": true, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "On Wed, Nov 27, 2019 at 10:14:16AM +0100, Fabien COELHO wrote:\n> Indeed, I did not notice.\n\nThanks, Fabien!\n--\nMichael", "msg_date": "Thu, 28 Nov 2019 13:01:10 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "Hi Fabien,\n\nOn 11/27/19 11:01 PM, Michael Paquier wrote:\n> On Wed, Nov 27, 2019 at 10:14:16AM +0100, Fabien COELHO wrote:\n>> Indeed, I did not notice.\n\n\nThis patch no longer applies: http://cfbot.cputube.org/patch_27_2262.log\n\nCF entry has been updated to Waiting on Author.\n\nRegards,\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Tue, 24 Mar 2020 10:47:00 -0400", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "> On 24 Mar 2020, at 15:47, David Steele <david@pgmasters.net> wrote:\n\n> This patch no longer applies: http://cfbot.cputube.org/patch_27_2262.log\n> \n> CF entry has been updated to Waiting on Author.\n\nThis patch hasn't been updated and still doesn't apply, do you intend to rebase\nit during this commitfest or should we move it to returned with feedback? It\ncan always be re-opened at a later date.\n\ncheers ./daniel\n\n", "msg_date": "Sun, 5 Jul 2020 13:38:33 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "> On 5 Jul 2020, at 13:38, Daniel Gustafsson <daniel@yesql.se> wrote:\n> \n>> On 24 Mar 2020, at 15:47, David Steele <david@pgmasters.net> wrote:\n> \n>> This patch no longer applies: http://cfbot.cputube.org/patch_27_2262.log\n>> \n>> CF entry has been updated to Waiting on Author.\n> \n> This patch hasn't been updated and still doesn't apply, do you intend to rebase\n> it during this commitfest or should we move it to returned with feedback? It\n> can always be re-opened at a later date.\n\nAs the thread has stalled, I've marked this Returned with Feedback.\n\ncheers ./daniel\n\n", "msg_date": "Thu, 30 Jul 2020 23:47:23 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "\nHello,\n\n>>> This patch no longer applies: http://cfbot.cputube.org/patch_27_2262.log\n>>>\n>>> CF entry has been updated to Waiting on Author.\n>>\n>> This patch hasn't been updated and still doesn't apply, do you intend to rebase\n>> it during this commitfest or should we move it to returned with feedback? It\n>> can always be re-opened at a later date.\n>\n> As the thread has stalled, I've marked this Returned with Feedback.\n\nHmmm.\n\nAFAICR the feedback is that the Expect perl module is not welcome, which \nseems to suggest that it would have to be re-implemented somehow. This is \nnot my dev philosophy, I won't do that, so I'm sorry to say that psql \ncoverage will remain pretty abysmal.\n\nSigh.\n\n-- \nFabien.\n\n\n", "msg_date": "Sat, 1 Aug 2020 09:06:39 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": true, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "> On 1 Aug 2020, at 09:06, Fabien COELHO <coelho@cri.ensmp.fr> wrote:\n> \n> Hello,\n> \n>>>> This patch no longer applies: http://cfbot.cputube.org/patch_27_2262.log\n>>>> \n>>>> CF entry has been updated to Waiting on Author.\n>>> \n>>> This patch hasn't been updated and still doesn't apply, do you intend to rebase\n>>> it during this commitfest or should we move it to returned with feedback? It\n>>> can always be re-opened at a later date.\n>> \n>> As the thread has stalled, I've marked this Returned with Feedback.\n> \n> Hmmm.\n> \n> AFAICR the feedback is that the Expect perl module is not welcome, which seems to suggest that it would have to be re-implemented somehow. This is not my dev philosophy, I won't do that, so I'm sorry to say that psql coverage will remain pretty abysmal.\n\nRe-reading this thread, I see no complaints about introducing a dependency on\nExpect. The feedback returned in this case is that the patch hasn't applied\nsince March, and that the patch is more than welcome to be re-entered in the\nnext CF once it does.\n\ncheers ./daniel\n\n", "msg_date": "Sat, 1 Aug 2020 22:42:32 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "Daniel Gustafsson <daniel@yesql.se> writes:\n> On 1 Aug 2020, at 09:06, Fabien COELHO <coelho@cri.ensmp.fr> wrote:\n>> AFAICR the feedback is that the Expect perl module is not welcome, which seems to suggest that it would have to be re-implemented somehow. This is not my dev philosophy, I won't do that, so I'm sorry to say that psql coverage will remain pretty abysmal.\n\n> Re-reading this thread, I see no complaints about introducing a dependency on\n> Expect. The feedback returned in this case is that the patch hasn't applied\n> since March, and that the patch is more than welcome to be re-entered in the\n> next CF once it does.\n\nPersonally, I'd object to introducing a hard dependency on Expect, as\nthere are no doubt a lot of developers and buildfarm members who don't\nhave that installed. But I see no reason we couldn't skip some tests\nif it's lacking, as we're already doing with IO::Pty in\n010_tab_completion.pl.\n\nThat does raise the question of whether Expect makes things enough\neasier than raw IO::Pty that it's worth adding that dependency (and\nhence foregoing the tests on some machines). But I'm prepared to be\nconvinced on that point.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 01 Aug 2020 17:27:53 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "\nOn 8/1/20 5:27 PM, Tom Lane wrote:\n> Daniel Gustafsson <daniel@yesql.se> writes:\n>> On 1 Aug 2020, at 09:06, Fabien COELHO <coelho@cri.ensmp.fr> wrote:\n>>> AFAICR the feedback is that the Expect perl module is not welcome, which seems to suggest that it would have to be re-implemented somehow. This is not my dev philosophy, I won't do that, so I'm sorry to say that psql coverage will remain pretty abysmal.\n>> Re-reading this thread, I see no complaints about introducing a dependency on\n>> Expect. The feedback returned in this case is that the patch hasn't applied\n>> since March, and that the patch is more than welcome to be re-entered in the\n>> next CF once it does.\n> Personally, I'd object to introducing a hard dependency on Expect, as\n> there are no doubt a lot of developers and buildfarm members who don't\n> have that installed. But I see no reason we couldn't skip some tests\n> if it's lacking, as we're already doing with IO::Pty in\n> 010_tab_completion.pl.\n>\n> That does raise the question of whether Expect makes things enough\n> easier than raw IO::Pty that it's worth adding that dependency (and\n> hence foregoing the tests on some machines). But I'm prepared to be\n> convinced on that point.\n>\n> \t\t\t\n\n\n+1. Also note that the Windows animals don't and probably will never\nsupport Expect, since Windows doesn't have PTYs. Expect.pm is in fact a\npure perl module that sits on top of IO::Pty, which in turn sits on top\nof IO::Tty. So if you have those Expect.pm probably isn't a huge\nstretch. But let's not add a dependency if we can avoid it. And if we do\nadd one it will need to be a soft one like the case you mentioned.\n\n\ncheers\n\n\nandrew\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Sun, 2 Aug 2020 11:10:23 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "On Sun, Aug 02, 2020 at 11:10:23AM -0400, Andrew Dunstan wrote:\n> +1. Also note that the Windows animals don't and probably will never\n> support Expect, since Windows doesn't have PTYs. Expect.pm is in fact a\n> pure perl module that sits on top of IO::Pty, which in turn sits on top\n> of IO::Tty. So if you have those Expect.pm probably isn't a huge\n> stretch. But let's not add a dependency if we can avoid it. And if we do\n> add one it will need to be a soft one like the case you mentioned.\n\nEven with that, do we really care about some code coverage specific to\nWindows for tab-complete.c? Also, how complicated does the proposed\npatch become if we remove the dependency to Expect.pm and just rely on\nIO::Pty?\n--\nMichael", "msg_date": "Mon, 3 Aug 2020 11:06:19 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "\n> Re-reading this thread, I see no complaints about introducing a \n> dependency on Expect.\n\nIndeed, Tom's complaint was on another thread, possibly when interactive \ntests \"src/bin/psql/t/010_tab_completion.pl\" were added.\n\nISTM that one of the issue was that some farm animal would be broken.\n\nI'm quite lost about Expect portability discussion wrt windows, it is \nunclear to me whether it is expected to work there or not.\n\nAs I stated, I do not like re-inventing the wheel, probably quite badly, \nwhen someone else already did a good job.\n\n-- \nFabien.\n\n\n", "msg_date": "Mon, 3 Aug 2020 21:34:47 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": true, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" }, { "msg_contents": "\nOn 8/3/20 3:34 PM, Fabien COELHO wrote:\n>\n>\n> I'm quite lost about Expect portability discussion wrt windows, it is\n> unclear to me whether it is expected to work there or not.\n\n\n\nSorry if I was unclear. Expect will not work on Windows. Nor will use of\nIO::Pty  or IO::Tty, which are what Expect uses under the hood. So use\nof any of that needs to be done just as it is done on\n010_tab_completion.pl, i.e.\n\n\n eval { require IO::Pty; };\n if ($@)\n {\n     plan skip_all => 'IO::Pty is needed to run this test';\n }\n\n\ncheers\n\n\nandrew\n\n\n-- \nAndrew Dunstan https://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n\n", "msg_date": "Mon, 3 Aug 2020 18:44:03 -0400", "msg_from": "Andrew Dunstan <andrew.dunstan@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: psql - improve test coverage from 41% to 88%" } ]
[ { "msg_contents": "It was apparently entirely undocumented that the tablespace size\nestimates sent by the base backup protocol are in kilobytes. Here is a\npatch to document that. Also, a related clarification in the\npg_basebackup.c source code: It was not clear without analyzing the\nwhole stack that \"totalsize\" is in kilobytes and \"totaldone\" is in bytes.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services", "msg_date": "Wed, 28 Aug 2019 16:58:43 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Improve base backup protocol documentation" }, { "msg_contents": "On Wed, Aug 28, 2019 at 4:58 PM Peter Eisentraut <\npeter.eisentraut@2ndquadrant.com> wrote:\n\n> It was apparently entirely undocumented that the tablespace size\n> estimates sent by the base backup protocol are in kilobytes. Here is a\n> patch to document that. Also, a related clarification in the\n> pg_basebackup.c source code: It was not clear without analyzing the\n> whole stack that \"totalsize\" is in kilobytes and \"totaldone\" is in bytes.\n>\n>\n+1, these both look like reasonable changes to me.\n\n//Magnus\n\nOn Wed, Aug 28, 2019 at 4:58 PM Peter Eisentraut <peter.eisentraut@2ndquadrant.com> wrote:It was apparently entirely undocumented that the tablespace size\nestimates sent by the base backup protocol are in kilobytes.  Here is a\npatch to document that.  Also, a related clarification in the\npg_basebackup.c source code: It was not clear without analyzing the\nwhole stack that \"totalsize\" is in kilobytes and \"totaldone\" is in bytes.+1, these both look like reasonable changes to me.//Magnus", "msg_date": "Tue, 3 Sep 2019 09:50:44 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: Improve base backup protocol documentation" }, { "msg_contents": "On 2019-09-03 09:50, Magnus Hagander wrote:\n> On Wed, Aug 28, 2019 at 4:58 PM Peter Eisentraut\n> <peter.eisentraut@2ndquadrant.com\n> <mailto:peter.eisentraut@2ndquadrant.com>> wrote:\n> \n> It was apparently entirely undocumented that the tablespace size\n> estimates sent by the base backup protocol are in kilobytes.  Here is a\n> patch to document that.  Also, a related clarification in the\n> pg_basebackup.c source code: It was not clear without analyzing the\n> whole stack that \"totalsize\" is in kilobytes and \"totaldone\" is in\n> bytes.\n> \n> \n> +1, these both look like reasonable changes to me.\n\ncommitted\n\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 3 Sep 2019 12:03:25 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: Improve base backup protocol documentation" } ]
[ { "msg_contents": "SECCOMP (\"SECure COMPuting with filters\") is a Linux kernel syscall\nfiltering mechanism which allows reduction of the kernel attack surface\nby preventing (or at least audit logging) normally unused syscalls.\n\nQuoting from this link:\nhttps://www.kernel.org/doc/Documentation/prctl/seccomp_filter.txt\n\n \"A large number of system calls are exposed to every userland process\n with many of them going unused for the entire lifetime of the\n process. As system calls change and mature, bugs are found and\n eradicated. A certain subset of userland applications benefit by\n having a reduced set of available system calls. The resulting set\n reduces the total kernel surface exposed to the application. System\n call filtering is meant for use with those applications.\"\n\nRecent security best-practices recommend, and certain highly\nsecurity-conscious organizations are beginning to require, that SECCOMP\nbe used to the extent possible. The major web browsers, container\nruntime engines, and systemd are all examples of software that already\nsupport seccomp.\n\n---------\nA seccomp (bpf) filter is comprised of a default action, and a set of\nrules with actions pertaining to specific syscalls (possibly with even\nmore specific sets of arguments). Once loaded into the kernel, a filter\nis inherited by all child processes and cannot be removed. It can,\nhowever, be overlaid with another filter. For any given syscall match,\nthe most restrictive (a.k.a. highest precedence) action will be taken by\nthe kernel. PostgreSQL has already been run \"in the wild\" under seccomp\ncontrol in containers, and possibly systemd. Adding seccomp support into\nPostgreSQL itself mitigates issues with these approaches, and has\nseveral advantages:\n\n* Container seccomp filters tend to be extremely broad/permissive,\n typically allowing about 6 out 7 of all syscalls. They must do this\n because the use cases for containers vary widely.\n* systemd does not implement seccomp filters by default. Packagers may\n decide to do so, but there is no guarantee. Adding them post install\n potentially requires cooperation by groups outside control of\n the database admins.\n* In the container and systemd case there is no particularly good way to\n inspect what filters are active. It is possible to observe actions\n taken, but again, control is possibly outside the database admin\n group. For example, the best way to understand what happened is to\n review the auditd log, which is likely not readable by the DBA.\n* With built-in support, it is possible to lock down backend processes\n more tightly than the postmaster.\n* With built-in support, it is possible to lock down different backend\n processes differently than each other, for example by using ALTER ROLE\n ... SET or ALTER DATABASE ... SET.\n* With built-in support, it is possible to calculate and return (in the\n form of an SRF) the effective filters being applied to the postmaster\n and the current backend.\n* With built-in support, it could be possible (this part not yet\n implemented) to have separate filters for different backend types,\n e.g. autovac workers, background writer, etc.\n\n---------\nAttached is a patch for discussion, adding support for seccomp-bpf\n(nowadays generally just called seccomp) syscall filtering at\nconfigure-time using libseccomp. I would like to get this in shape to be\ncommitted by the end of the November CF if possible.\n\nThe code itself has been through several rounds of revision based on\ndiscussions I have had with the author of libseccomp as well as a few\nother folks. However as of the moment:\n\n* Documentation - general discussion missing entirely\n* No regression tests\n\n---------\nFor convenience, here are a couple of additional links to relevant\ninformation regarding seccomp:\nhttps://en.wikipedia.org/wiki/Seccomp\nhttps://github.com/seccomp/libseccomp\n\n---------\nSpecific feedback requested:\n1. Placement of pg_get_seccomp_filter() in\n src/backend/utils/adt/genfile.c\n originally made sense but after several rewrites no longer does.\n Ideas where it *should* go?\n2. Where should a general discussion section go in the docs, if at all?\n3. Currently this supports a global filter at the postmaster level,\n which is inherited by all child processes, and a secondary filter\n at the client backend session level. It likely makes sense to\n support secondary filters for other types of child processes,\n e.g. autovacuum workers, etc. Add that now (pg13), later release,\n or never?\n4. What is the best way to approach testing of this feature? Tap\n testing perhaps?\n5. Default GUC values - should we provide \"starter\" lists, or only a\n procedure for generating a list (as below).\n\n---------\nNotes on usage:\n===============\nIn order to determine your minimally required allow lists, do something\nlike the following on a non-production server with the same architecture\nas production:\n\n0. Setup:\n * install libseccomp, libseccomp-dev, and seccomp\n * install auditd if not already installed\n * configure postgres --with-seccomp and maybe --enable-tap-tests to\n improve feature coverage (see below)\n\n1. Modify postgresql.conf and/or create <pg_source_dir>/postgresql_tmp.conf\n8<--------------------\nseccomp = on\nglobal_syscall_default = allow\nglobal_syscall_allow = ''\nglobal_syscall_log = ''\nglobal_syscall_error = ''\nglobal_syscall_kill = ''\nsession_syscall_default = log\nsession_syscall_allow = '*'\nsession_syscall_log = '*'\nsession_syscall_error = '*'\nsession_syscall_kill = '*'\n8<--------------------\n\n2. Modify /etc/audit/auditd.conf\n * disp_qos = 'lossless'\n * change max_log_file_action = 'ignore'\n\n3. Stop auditd, clear out all audit.logs, start auditd:\n * systemctl stop auditd.service\t\t\t# if running\n * echo -n \"\" > /var/log/audit/audit.log\n * systemctl start auditd.service\n\n4. Start/restart postgres.\n\n5. Exercise postgres as much as possible (one or more of the following):\n * make installcheck-world\n * make check world \\\n EXTRA_REGRESS_OPTS=--temp-config=<pg_source_dir>/postgresql_tmp.conf\n * run your application through its paces\n * other random testing of relevant postgres features\n\n Note: at this point audit.log will start growing quickly. During `make\n check world` mine grew to just under 1 GB.\n\n6. Process results:\n a) systemctl stop auditd.service\n b) Run the provided \"get_syscalls.sh\" script\n c) Cut and paste the result as the value of session_syscall_allow.\n\n7. Optional:\n a) global_syscall_default = 'log'\n b) Repeat steps 3-5\n c) Repeat step 6a and 6b\n d) Cut and paste the result as the value of global_syscall_allow\n\n8. Iterate steps 3-6b.\n * Output should be empty.\n * If there are any new syscalls, add to global_syscall_allow and\n session_syscall_allow.\n * Iterate until output of \"get_syscalls.sh\" script is empty.\n\n9. Optional:\n * Change global and session defaults to \"error\" or \"kill\"\n * Reduce the allow lists if desired\n * This can be done for specific database users, by doing\n ALTER ROLE... SET session_syscall_allow to '<some reduced allow list>'\n\n10. Adjust settings to taste, restart postgres, and monitor audit.log\n going forward.\n\nBelow are some values from my system. Note that I have made no attempt\nthus far to do static code analysis -- this list was build using `make\ncheck world` several times.\n8<-------------------------\nseccomp = on\n\nglobal_syscall_default = log\nglobal_syscall_allow =\n'accept,access,bind,brk,chmod,clone,close,connect,dup,epoll_create1,epoll_ctl,epoll_wait,exit_group,fadvise64,fallocate,fcntl,fdatasync,fstat,fsync,ftruncate,futex,getdents,getegid,geteuid,getgid,getpeername,getpid,getppid,getrandom,getrusage,getsockname,getsockopt,getuid,ioctl,kill,link,listen,lseek,lstat,mkdir,mmap,mprotect,mremap,munmap,openat,pipe,poll,prctl,pread64,prlimit64,pwrite64,read,readlink,recvfrom,recvmsg,rename,rmdir,rt_sigaction,rt_sigprocmask,rt_sigreturn,seccomp,select,sendto,setitimer,set_robust_list,setsid,setsockopt,shmat,shmctl,shmdt,shmget,shutdown,socket,stat,statfs,symlink,sync_file_range,sysinfo,umask,uname,unlink,utime,wait4,write'\nglobal_syscall_log = ''\nglobal_syscall_error = ''\nglobal_syscall_kill = ''\n\nsession_syscall_default = log\nsession_syscall_allow =\n'access,brk,chmod,close,connect,epoll_create1,epoll_ctl,epoll_wait,exit_group,fadvise64,fallocate,fcntl,fdatasync,fstat,fsync,ftruncate,futex,getdents,getegid,geteuid,getgid,getpeername,getpid,getrandom,getrusage,getsockname,getsockopt,getuid,ioctl,kill,link,lseek,lstat,mkdir,mmap,mprotect,mremap,munmap,openat,poll,pread64,pwrite64,read,readlink,recvfrom,recvmsg,rename,rmdir,rt_sigaction,rt_sigprocmask,rt_sigreturn,select,sendto,setitimer,setsockopt,shutdown,socket,stat,symlink,sync_file_range,sysinfo,umask,uname,unlink,utime,write'\nsession_syscall_log = '*'\nsession_syscall_error = '*'\nsession_syscall_kill = '*'\n8<-------------------------\n\nThat results in the following effective filters at the (\"context\"\nequals) global and session levels:\n\n8<-------------------------\nselect * from pg_get_seccomp_filter() order by 4,1;\n syscall | syscallnum | filter_action | context\n-----------------+------------+----------------+---------\n accept | 43 | global->allow | global\n access | 21 | global->allow | global\n bind | 49 | global->allow | global\n brk | 12 | global->allow | global\n chmod | 90 | global->allow | global\n clone | 56 | global->allow | global\n close | 3 | global->allow | global\n connect | 42 | global->allow | global\n <default> | -1 | global->log | global\n dup | 32 | global->allow | global\n epoll_create1 | 291 | global->allow | global\n epoll_ctl | 233 | global->allow | global\n epoll_wait | 232 | global->allow | global\n exit_group | 231 | global->allow | global\n fadvise64 | 221 | global->allow | global\n fallocate | 285 | global->allow | global\n fcntl | 72 | global->allow | global\n fdatasync | 75 | global->allow | global\n fstat | 5 | global->allow | global\n fsync | 74 | global->allow | global\n ftruncate | 77 | global->allow | global\n futex | 202 | global->allow | global\n getdents | 78 | global->allow | global\n getegid | 108 | global->allow | global\n geteuid | 107 | global->allow | global\n getgid | 104 | global->allow | global\n getpeername | 52 | global->allow | global\n getpid | 39 | global->allow | global\n getppid | 110 | global->allow | global\n getrandom | 318 | global->allow | global\n getrusage | 98 | global->allow | global\n getsockname | 51 | global->allow | global\n getsockopt | 55 | global->allow | global\n getuid | 102 | global->allow | global\n ioctl | 16 | global->allow | global\n kill | 62 | global->allow | global\n link | 86 | global->allow | global\n listen | 50 | global->allow | global\n lseek | 8 | global->allow | global\n lstat | 6 | global->allow | global\n mkdir | 83 | global->allow | global\n mmap | 9 | global->allow | global\n mprotect | 10 | global->allow | global\n mremap | 25 | global->allow | global\n munmap | 11 | global->allow | global\n openat | 257 | global->allow | global\n pipe | 22 | global->allow | global\n poll | 7 | global->allow | global\n prctl | 157 | global->allow | global\n pread64 | 17 | global->allow | global\n prlimit64 | 302 | global->allow | global\n pwrite64 | 18 | global->allow | global\n read | 0 | global->allow | global\n readlink | 89 | global->allow | global\n recvfrom | 45 | global->allow | global\n recvmsg | 47 | global->allow | global\n rename | 82 | global->allow | global\n rmdir | 84 | global->allow | global\n rt_sigaction | 13 | global->allow | global\n rt_sigprocmask | 14 | global->allow | global\n rt_sigreturn | 15 | global->allow | global\n seccomp | 317 | global->allow | global\n select | 23 | global->allow | global\n sendto | 44 | global->allow | global\n setitimer | 38 | global->allow | global\n set_robust_list | 273 | global->allow | global\n setsid | 112 | global->allow | global\n setsockopt | 54 | global->allow | global\n shmat | 30 | global->allow | global\n shmctl | 31 | global->allow | global\n shmdt | 67 | global->allow | global\n shmget | 29 | global->allow | global\n shutdown | 48 | global->allow | global\n socket | 41 | global->allow | global\n stat | 4 | global->allow | global\n statfs | 137 | global->allow | global\n symlink | 88 | global->allow | global\n sync_file_range | 277 | global->allow | global\n sysinfo | 99 | global->allow | global\n umask | 95 | global->allow | global\n uname | 63 | global->allow | global\n unlink | 87 | global->allow | global\n utime | 132 | global->allow | global\n wait4 | 61 | global->allow | global\n write | 1 | global->allow | global\n accept | 43 | session->log | session\n access | 21 | session->allow | session\n bind | 49 | session->log | session\n brk | 12 | session->allow | session\n chmod | 90 | session->allow | session\n clone | 56 | session->log | session\n close | 3 | session->allow | session\n connect | 42 | session->allow | session\n <default> | -1 | session->log | session\n dup | 32 | session->log | session\n epoll_create1 | 291 | session->allow | session\n epoll_ctl | 233 | session->allow | session\n epoll_wait | 232 | session->allow | session\n exit_group | 231 | session->allow | session\n fadvise64 | 221 | session->allow | session\n fallocate | 285 | session->allow | session\n fcntl | 72 | session->allow | session\n fdatasync | 75 | session->allow | session\n fstat | 5 | session->allow | session\n fsync | 74 | session->allow | session\n ftruncate | 77 | session->allow | session\n futex | 202 | session->allow | session\n getdents | 78 | session->allow | session\n getegid | 108 | session->allow | session\n geteuid | 107 | session->allow | session\n getgid | 104 | session->allow | session\n getpeername | 52 | session->allow | session\n getpid | 39 | session->allow | session\n getppid | 110 | session->log | session\n getrandom | 318 | session->allow | session\n getrusage | 98 | session->allow | session\n getsockname | 51 | session->allow | session\n getsockopt | 55 | session->allow | session\n getuid | 102 | session->allow | session\n ioctl | 16 | session->allow | session\n kill | 62 | session->allow | session\n link | 86 | session->allow | session\n listen | 50 | session->log | session\n lseek | 8 | session->allow | session\n lstat | 6 | session->allow | session\n mkdir | 83 | session->allow | session\n mmap | 9 | session->allow | session\n mprotect | 10 | session->allow | session\n mremap | 25 | session->allow | session\n munmap | 11 | session->allow | session\n openat | 257 | session->allow | session\n pipe | 22 | session->log | session\n poll | 7 | session->allow | session\n prctl | 157 | session->log | session\n pread64 | 17 | session->allow | session\n prlimit64 | 302 | session->log | session\n pwrite64 | 18 | session->allow | session\n read | 0 | session->allow | session\n readlink | 89 | session->allow | session\n recvfrom | 45 | session->allow | session\n recvmsg | 47 | session->allow | session\n rename | 82 | session->allow | session\n rmdir | 84 | session->allow | session\n rt_sigaction | 13 | session->allow | session\n rt_sigprocmask | 14 | session->allow | session\n rt_sigreturn | 15 | session->allow | session\n seccomp | 317 | session->log | session\n select | 23 | session->allow | session\n sendto | 44 | session->allow | session\n setitimer | 38 | session->allow | session\n set_robust_list | 273 | session->log | session\n setsid | 112 | session->log | session\n setsockopt | 54 | session->allow | session\n shmat | 30 | session->log | session\n shmctl | 31 | session->log | session\n shmdt | 67 | session->log | session\n shmget | 29 | session->log | session\n shutdown | 48 | session->allow | session\n socket | 41 | session->allow | session\n stat | 4 | session->allow | session\n statfs | 137 | session->log | session\n symlink | 88 | session->allow | session\n sync_file_range | 277 | session->allow | session\n sysinfo | 99 | session->allow | session\n umask | 95 | session->allow | session\n uname | 63 | session->allow | session\n unlink | 87 | session->allow | session\n utime | 132 | session->allow | session\n wait4 | 61 | session->log | session\n write | 1 | session->allow | session\n(170 rows)\n8<-------------------------\n\nIf you made it all the way to here, thank you for your attention :-)\n\nJoe\n\n-- \nCrunchy Data - http://crunchydata.com\nPostgreSQL Support for Secure Enterprises\nConsulting, Training, & Open Source Development", "msg_date": "Wed, 28 Aug 2019 11:13:27 -0400", "msg_from": "Joe Conway <mail@joeconway.com>", "msg_from_op": true, "msg_subject": "RFC: seccomp-bpf support" }, { "msg_contents": "On Wed, Aug 28, 2019 at 11:13:27AM -0400, Joe Conway wrote:\n> SECCOMP (\"SECure COMPuting with filters\") is a Linux kernel syscall\n> filtering mechanism which allows reduction of the kernel attack surface\n> by preventing (or at least audit logging) normally unused syscalls.\n> \n> Quoting from this link:\n> https://www.kernel.org/doc/Documentation/prctl/seccomp_filter.txt\n> \n> \"A large number of system calls are exposed to every userland process\n> with many of them going unused for the entire lifetime of the\n> process. As system calls change and mature, bugs are found and\n> eradicated. A certain subset of userland applications benefit by\n> having a reduced set of available system calls. The resulting set\n> reduces the total kernel surface exposed to the application. System\n> call filtering is meant for use with those applications.\"\n> \n> Recent security best-practices recommend, and certain highly\n> security-conscious organizations are beginning to require, that SECCOMP\n> be used to the extent possible. The major web browsers, container\n> runtime engines, and systemd are all examples of software that already\n> support seccomp.\n\nNeat!\n\nAre the seccomp interfaces for other kernels arranged in a manner\nsimilar enough to have a unified interface in PostgreSQL, or is this\nmore of a Linux-only feature?\n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate\n\n\n", "msg_date": "Wed, 28 Aug 2019 18:47:50 +0200", "msg_from": "David Fetter <david@fetter.org>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On 2019-08-28 17:13, Joe Conway wrote:\n> * systemd does not implement seccomp filters by default. Packagers may\n> decide to do so, but there is no guarantee. Adding them post install\n> potentially requires cooperation by groups outside control of\n> the database admins.\n\nWell, if we are interested in this, why don't we just ask packagers to\ndo so? That seems like a much easier solution.\n\n> * In the container and systemd case there is no particularly good way to\n> inspect what filters are active. It is possible to observe actions\n> taken, but again, control is possibly outside the database admin\n> group. For example, the best way to understand what happened is to\n> review the auditd log, which is likely not readable by the DBA.\n\nWhy does one need to know what filters are active (other than,\nobviously, checking that the filters one has set were actually\nactivated)? What decisions would a DBA or database user be able to make\nbased on whether a filter is set or not?\n\n> * With built-in support, it is possible to lock down backend processes\n> more tightly than the postmaster.\n\nAlso the other way around?\n\n> * With built-in support, it is possible to lock down different backend\n> processes differently than each other, for example by using ALTER ROLE\n> ... SET or ALTER DATABASE ... SET.\n\nWhat are use cases for this?\n\n> Attached is a patch for discussion, adding support for seccomp-bpf\n> (nowadays generally just called seccomp) syscall filtering at\n> configure-time using libseccomp. I would like to get this in shape to be\n> committed by the end of the November CF if possible.\n\nTo compute the initial set of allowed system calls, you need to have\nfantastic test coverage. What you don't want is some rarely used error\nrecovery path to cause a system crash. I wouldn't trust our current\ncoverage for this.\n\nAlso, the list of system calls in use changes all the time. The same\nfunction call from PostgreSQL could be a system call or a glibc\nimplementation, depending on the specific installed packages or run-time\nsettings.\n\nExtensions would need to maintain their own permissions list, and they\nwould need to be merged manually into the respective existing settings.\n\nWithout good answers to these, I suspect that this feature would go\nstraight to the top of the list of \"if in doubt, turn off\".\n\nOverall, I think this sounds like a maintenance headache, and the\npossible benefits are unclear.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 28 Aug 2019 19:03:07 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On 8/28/19 1:03 PM, Peter Eisentraut wrote:\n> On 2019-08-28 17:13, Joe Conway wrote:\n>> * systemd does not implement seccomp filters by default. Packagers may\n>> decide to do so, but there is no guarantee. Adding them post install\n>> potentially requires cooperation by groups outside control of\n>> the database admins.\n> \n> Well, if we are interested in this, why don't we just ask packagers to\n> do so? That seems like a much easier solution.\n\n\nFor the reason listed below\n\n>> * In the container and systemd case there is no particularly good way to\n>> inspect what filters are active. It is possible to observe actions\n>> taken, but again, control is possibly outside the database admin\n>> group. For example, the best way to understand what happened is to\n>> review the auditd log, which is likely not readable by the DBA.\n> \n> Why does one need to know what filters are active (other than,\n> obviously, checking that the filters one has set were actually\n> activated)? What decisions would a DBA or database user be able to make\n> based on whether a filter is set or not?\n\nSo that when an enforement action happens, you can understand why it\nhappened. Perhaps it was a bug (omission) in your allow list, or perhaps\nit was an intentional rule to prevent abuse (say blocking certain\nsyscalls from plperlu), or it was because someone is trying to\ncompromise you system (e.g. some obscure and clearly not needed syscall).\n\n>> * With built-in support, it is possible to lock down backend processes\n>> more tightly than the postmaster.\n> \n> Also the other way around?\n\nAs I stated in the original email, the filters can add restrictions but\nnever remove them.\n\n>> * With built-in support, it is possible to lock down different backend\n>> processes differently than each other, for example by using ALTER ROLE\n>> ... SET or ALTER DATABASE ... SET.\n> \n> What are use cases for this?\n\nFor example to allow a specific user to use plperlu to exec shell code\nwhile others cannot.\n\n>> Attached is a patch for discussion, adding support for seccomp-bpf\n>> (nowadays generally just called seccomp) syscall filtering at\n>> configure-time using libseccomp. I would like to get this in shape to be\n>> committed by the end of the November CF if possible.\n> \n> To compute the initial set of allowed system calls, you need to have\n> fantastic test coverage. What you don't want is some rarely used error\n> recovery path to cause a system crash. I wouldn't trust our current\n> coverage for this.\n\n\nSo if you are worried about that make your default action 'log' and\nwatch audit.log. There will be no errors or crashes of postgres caused\nby that because there will be no change in postgres visible behavior.\n\nAnd if returning an error from a syscall causes a crash that would be a\nserious bug and we should fix it.\n\n\n> Also, the list of system calls in use changes all the time. The same\n> function call from PostgreSQL could be a system call or a glibc\n> implementation, depending on the specific installed packages or run-time\n> settings.\n\nTrue. That is why I did not provide an initial list and believe folks\nwho want to use this should develop their own.\n\n> Extensions would need to maintain their own permissions list, and they\n> would need to be merged manually into the respective existing settings.\n\nPeople would have to generate their own list for extensions -- I don't\nbelieve it is the extension writers' problem.\n\n> Without good answers to these, I suspect that this feature would go\n> straight to the top of the list of \"if in doubt, turn off\".\n\nThat is fine. Perhaps most people never use this, but when needed (and\nincreasingly will be required) it is available.\n\n> Overall, I think this sounds like a maintenance headache, and the\n> possible benefits are unclear.\n\nThe only people who will incur the maintenance headache are those who\nneed to use it. The benefits are compliance with requirements.\n\nJoe\n\n-- \nCrunchy Data - http://crunchydata.com\nPostgreSQL Support for Secure Enterprises\nConsulting, Training, & Open Source Development", "msg_date": "Wed, 28 Aug 2019 13:28:06 -0400", "msg_from": "Joe Conway <mail@joeconway.com>", "msg_from_op": true, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On 8/28/19 12:47 PM, David Fetter wrote:\n> On Wed, Aug 28, 2019 at 11:13:27AM -0400, Joe Conway wrote:\n>> SECCOMP (\"SECure COMPuting with filters\") is a Linux kernel syscall\n>> filtering mechanism which allows reduction of the kernel attack surface\n>> by preventing (or at least audit logging) normally unused syscalls.\n>> \n>> Quoting from this link:\n>> https://www.kernel.org/doc/Documentation/prctl/seccomp_filter.txt\n>> \n>> \"A large number of system calls are exposed to every userland process\n>> with many of them going unused for the entire lifetime of the\n>> process. As system calls change and mature, bugs are found and\n>> eradicated. A certain subset of userland applications benefit by\n>> having a reduced set of available system calls. The resulting set\n>> reduces the total kernel surface exposed to the application. System\n>> call filtering is meant for use with those applications.\"\n>> \n>> Recent security best-practices recommend, and certain highly\n>> security-conscious organizations are beginning to require, that SECCOMP\n>> be used to the extent possible. The major web browsers, container\n>> runtime engines, and systemd are all examples of software that already\n>> support seccomp.\n> \n> Neat!\n> \n> Are the seccomp interfaces for other kernels arranged in a manner\n> similar enough to have a unified interface in PostgreSQL, or is this\n> more of a Linux-only feature?\n\n\nAs far as I know libseccomp is Linux specific, at least at the moment.\n\nJoe\n-- \nCrunchy Data - http://crunchydata.com\nPostgreSQL Support for Secure Enterprises\nConsulting, Training, & Open Source Development", "msg_date": "Wed, 28 Aug 2019 13:33:55 -0400", "msg_from": "Joe Conway <mail@joeconway.com>", "msg_from_op": true, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> On 2019-08-28 17:13, Joe Conway wrote:\n>> Attached is a patch for discussion, adding support for seccomp-bpf\n>> (nowadays generally just called seccomp) syscall filtering at\n>> configure-time using libseccomp. I would like to get this in shape to be\n>> committed by the end of the November CF if possible.\n\n> To compute the initial set of allowed system calls, you need to have\n> fantastic test coverage. What you don't want is some rarely used error\n> recovery path to cause a system crash. I wouldn't trust our current\n> coverage for this.\n\nYeah, that seems like quite a serious problem. I think you'd want\nto have some sort of static-code-analysis-based way of identifying\nthe syscalls in use, rather than trying to test your way to it.\n\n> Overall, I think this sounds like a maintenance headache, and the\n> possible benefits are unclear.\n\nAfter thinking about this for awhile, I really don't follow what\nthreat model it's trying to protect against. Given that we'll allow\nany syscall that an unmodified PG executable might use, it seems\nlike the only scenarios being protected against involve someone\nhaving already compromised the server enough to have arbitrary code\nexecution. OK, fine, but then why wouldn't the attacker just\nbypass libseccomp? Or tell it to let through the syscall he wants\nto use? Having the list of allowed syscalls be determined inside\nthe process seems like fundamentally the wrong implementation.\nI'd have expected a feature like this to be implemented by SELinux,\nor some similar technology where the filtering is done by logic\nthat's outside the executable you wish to not trust.\n\n(After googling for libseccomp, I see that it's supposed to not\nallow syscalls to be turned back on once turned off, but that isn't\nany protection against this problem. An attacker who's found an ACE\nhole in Postgres can just issue ALTER SYSTEM SET to disable the\nfeature, then force a postmaster restart, then profit.)\n\nI follow the idea of limiting the attack surface for kernel bugs,\nbut this doesn't seem like a useful implementation of that, even\nignoring the ease-of-use problems Peter mentions.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 28 Aug 2019 13:42:33 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "Hi,\n\nOn 2019-08-28 11:13:27 -0400, Joe Conway wrote:\n> Recent security best-practices recommend, and certain highly\n> security-conscious organizations are beginning to require, that SECCOMP\n> be used to the extent possible. The major web browsers, container\n> runtime engines, and systemd are all examples of software that already\n> support seccomp.\n\nMaybe I'm missing something, but it's not clear to me what meaningful\nattack surface can be reduced for PostgreSQL by forbidding certain\nsyscalls, given the wide variety of syscalls required to run postgres.\nThat's different from something like a browser's CSS process, or such,\nwhich really doesn't need much beyond some IPC and memory\nallocations. But postgres is going to need syscalls as broad as\nfork/clone, exec, connect, shm*, etc. I guess you can argue that we'd\nstill reduce the attack surface for kernel escalations, but that seems\nlike a pretty small win compared to the cost.\n\n\n> * With built-in support, it is possible to lock down backend processes\n> more tightly than the postmaster.\n\nWhich important syscalls would you get away with removing in backends\nthat postmaster needs? I think the only one - which is a good one though\n- that I can think of is listen(). But even that might be too\nrestrictive for some PLs running out of process.\n\n\nMy main problem with seccomp is that it's *incredibly* fragile,\nespecially for a program as complex as postgres. We already had seccomp\nrelated bug reports on list, even just due to the very permissive\nfiltering by some container solutions.\n\nThere's regularly new syscalls (e.g. epoll_create1(), and we'll soon get\nopenat2()), different versions of glibc use different syscalls\n(e.g. switching from open() to always using openat()), the system\nconfiguration influences which syscalls are being used (e.g. using\nvsyscalls only being used for certain clock sources), and kernel.\nbugfixes change the exact set of syscalls being used ([1]).\n\n[1] https://lwn.net/Articles/795128/\n\n\nThen there's also the issue that many extensions are going to need\nadditional syscalls.\n\n\n> Notes on usage:\n> ===============\n> In order to determine your minimally required allow lists, do something\n> like the following on a non-production server with the same architecture\n> as production:\n\n> c) Cut and paste the result as the value of session_syscall_allow.\n\nThat seems nearly guaranteed to miss a significant fraction of\nsyscalls. There's just no way we're going to cover all the potential\npaths and configurations in our testsuite.\n\nI think if you actually wanted to do something like this, you'd need to\nuse static analysis to come up with a more reliable list.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 28 Aug 2019 11:07:09 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "Hi,\n\nOn 2019-08-28 13:28:06 -0400, Joe Conway wrote:\n> > To compute the initial set of allowed system calls, you need to have\n> > fantastic test coverage. What you don't want is some rarely used error\n> > recovery path to cause a system crash. I wouldn't trust our current\n> > coverage for this.\n\n> So if you are worried about that make your default action 'log' and\n> watch audit.log. There will be no errors or crashes of postgres caused\n> by that because there will be no change in postgres visible behavior.\n\nBut the benefit of integrating this into postgres become even less\nclear.\n\n\n> And if returning an error from a syscall causes a crash that would be a\n> serious bug and we should fix it.\n\nErr, there's a lot of syscall failures that'll cause PANICs, and where\nthere's no reasonable way around that.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 28 Aug 2019 11:10:45 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On Wed, Aug 28, 2019 at 1:42 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Peter Eisentraut <peter.eisentraut@2ndquadrant.com> writes:\n> > On 2019-08-28 17:13, Joe Conway wrote:\n> >> Attached is a patch for discussion, adding support for seccomp-bpf\n> >> (nowadays generally just called seccomp) syscall filtering at\n> >> configure-time using libseccomp. I would like to get this in shape to be\n> >> committed by the end of the November CF if possible.\n>\n> > To compute the initial set of allowed system calls, you need to have\n> > fantastic test coverage. What you don't want is some rarely used error\n> > recovery path to cause a system crash. I wouldn't trust our current\n> > coverage for this.\n>\n> Yeah, that seems like quite a serious problem. I think you'd want\n> to have some sort of static-code-analysis-based way of identifying\n> the syscalls in use, rather than trying to test your way to it.\n>\n> > Overall, I think this sounds like a maintenance headache, and the\n> > possible benefits are unclear.\n>\n> After thinking about this for awhile, I really don't follow what\n> threat model it's trying to protect against. Given that we'll allow\n> any syscall that an unmodified PG executable might use, it seems\n> like the only scenarios being protected against involve someone\n> having already compromised the server enough to have arbitrary code\n> execution. OK, fine, but then why wouldn't the attacker just\n> bypass libseccomp? Or tell it to let through the syscall he wants\n> to use? Having the list of allowed syscalls be determined inside\n> the process seems like fundamentally the wrong implementation.\n> I'd have expected a feature like this to be implemented by SELinux,\n\nSELinux is generally an object model and while it does implement e.g.,\ncapability checks, that is not the main intent, nor is it possible for\nLSMs to implement syscall filters, the features are orthogonal.\n\n> or some similar technology where the filtering is done by logic\n> that's outside the executable you wish to not trust.\n> (After googling for libseccomp, I see that it's supposed to not\n> allow syscalls to be turned back on once turned off, but that isn't\n> any protection against this problem. An attacker who's found an ACE\n> hole in Postgres can just issue ALTER SYSTEM SET to disable the\n> feature, then force a postmaster restart, then profit.)\n>\n\nMy preference would have been to enable it unconditionally but Joe was\nbeing more practical.\n\n> I follow the idea of limiting the attack surface for kernel bugs,\n> but this doesn't seem like a useful implementation of that, even\n> ignoring the ease-of-use problems Peter mentions.\n\nLimiting the kernel attack surface for network facing daemons is\nimperative to hardening systems. All modern attacks are chained\ntogether so a kernel bug is useful only if you can execute code, and\nPG is a decent vector for executing code.\n\nAt a minimum I would urge the community to look at adding high risk\nsyscalls to the kill list, systemd has some predefined sets we can\npick from like @obsoluete, @cpu-emulation, @privileged, @mount, and\n@module.\n\nThe goal is to prevent an ACE hole in Postgres from becoming a\ncomplete system compromise. This may not do it alone, and security\nconscious integrators will want to, for example, add seccomp filters\nto systemd to prevent superuser from disabling them. The postmaster\nand per-role lists can further reduce the available syscalls based on\nthe exact extensions and PLs being used. Each step reduced the surface\nmore and throwing it all out because one step can go rogue is\nunsatisfying.\n\nThank you.\n\n\n", "msg_date": "Wed, 28 Aug 2019 14:23:00 -0400", "msg_from": "Joshua Brindle <joshua.brindle@crunchydata.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> Maybe I'm missing something, but it's not clear to me what meaningful\n> attack surface can be reduced for PostgreSQL by forbidding certain\n> syscalls, given the wide variety of syscalls required to run postgres.\n\nI think the idea is to block access to seldom-used syscalls because\nthose are exactly the ones most likely to have bugs. (We certainly\nhope that all the ones PG uses are well-debugged...) That seems fine.\nWhether the incremental protection is really worth the effort is\ndebatable, but as long as it's only people who think it *is* worth\nthe effort who have to deal with it, I don't mind.\n\nWhat I don't like about this proposal is that the filter configuration is\nkept somewhere where it's not at all hard for an attacker to modify it.\nIt can't be a GUC, indeed it can't be in any file that the server has\npermissions to write on, or you might as well not bother. So I'd throw\naway pretty much everything in the submitted patch, and instead think\nabout doing the filtering/limiting in something that's launched from the\nservice start script and in turn launches the postmaster. That makes it\n(mostly?) Not Our Problem, but rather an independent component.\n\nAdmittedly, you can't get per-subprocess restrictions that way, but the\nincremental value from that seems *really* tiny. If listen() has a bug\nyou need to fix the bug, not invent this amount of rickety infrastructure\nto limit who can call it.\n\n(And, TBH, I'm still wondering why SELinux isn't the way to address this.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 28 Aug 2019 14:30:20 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "Hi,\n\nOn 2019-08-28 14:23:00 -0400, Joshua Brindle wrote:\n> > or some similar technology where the filtering is done by logic\n> > that's outside the executable you wish to not trust.\n> > (After googling for libseccomp, I see that it's supposed to not\n> > allow syscalls to be turned back on once turned off, but that isn't\n> > any protection against this problem. An attacker who's found an ACE\n> > hole in Postgres can just issue ALTER SYSTEM SET to disable the\n> > feature, then force a postmaster restart, then profit.)\n\nA postmaster restart might not be enough, because the postmaster's\nrestrictions can't be removed, once in place. But all that's needed to\ncircumvent that is force postmaster to die, and rely on systemd etc to\nrestart it.\n\n\n> My preference would have been to enable it unconditionally but Joe was\n> being more practical.\n\nWell, the current approach is to configure the list of allowed syscalls\nin postgres. How would you ever secure that against the attacks\ndescribed by Tom? As long as the restrictions are put into place by\npostgres itself, and as long they're configurable, such attacks are\npossible, no? And as long as extensions etc need different syscalls,\nyou'll need configurability.\n\n\n> > I follow the idea of limiting the attack surface for kernel bugs,\n> > but this doesn't seem like a useful implementation of that, even\n> > ignoring the ease-of-use problems Peter mentions.\n> \n> Limiting the kernel attack surface for network facing daemons is\n> imperative to hardening systems. All modern attacks are chained\n> together so a kernel bug is useful only if you can execute code, and\n> PG is a decent vector for executing code.\n\nI don't really buy that in case pof postgres. Normally, in a medium to\nhigh security world, once you have RCE in postgres, the valuable data\ncan already be exfiltrated. And that's game over. The only real benefits\nof a kernel vulnerabily is that that might allow to persist the attack\nfor longer - but there's already plenty you can do inside postgres, once\nyou have RCE.\n\n\n> At a minimum I would urge the community to look at adding high risk\n> syscalls to the kill list, systemd has some predefined sets we can\n> pick from like @obsoluete, @cpu-emulation, @privileged, @mount, and\n> @module.\n\nI can see some small value in disallowing these - but we're back to the\npoint where that is better done one layer *above* postgres, by a process\nwith more privileges than PG. Because then a PG RCE doesn't have a way\nto prevent those filters from being applied.\n\n\n> The postmaster and per-role lists can further reduce the available\n> syscalls based on the exact extensions and PLs being used.\n\nI don't buy that per-session configurable lists buy you anything\nmeaningful. With an RCE in one session, it's pretty trivial to corrupt\nshared memory to also trigger RCE in other sessions. And there's no way\nseccomp or anything like that will prevent that.\n\nAn additional reason I'm quite sceptical about more fine grained\nrestrictions is that I think we're going to have to go for some use of\nthreading in the next few years. While I think that's still far from\nagreed upon, I think there's a pretty large number of \"senior\" hackers\nthat see this as the future. You can have per-thread seccomp filters,\nbut that's so trivial to circumvent (just overwrite some vtable like\ndata in another thread's data, and have it call whatever gadget you\nwant), that it's not even worth considering.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 28 Aug 2019 11:41:05 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On Wed, Aug 28, 2019 at 2:30 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n<snip>\n>\n> (And, TBH, I'm still wondering why SELinux isn't the way to address this.)\n\nJust going to address this one now. SELinux is an LSM and therefore\nonly makes decisions when LSM hooks are invoked, which are not 1:1 for\nsyscalls (not even close). Further, SELinux generally determines what\nobjects a subject can access and only implements capabilities because\nit has to, to be non-bypassable.\n\nSeccomp filtering is an orthogonal system to SELinux and LSMs in\ngeneral. We are already doing work to further restrict PG subprocesses\nwith SELinux via [1] and [2], but that doesn't address the unused,\nhigh-risk, obsolete, etc syscall issue. A prime example is madvise()\nwhich was a catastrophic failure that 1) isn't preventable by any LSM\nincluding SELinux, 2) isn't used by PG and is therefore a good\ncandidate for a kill list, and 3) a clear win in the\ndont-let-PG-be-a-vector-for-kernel-compromise arena.\n\nWe are using SELinux, we are also going to use this, they work together.\n\n\n", "msg_date": "Wed, 28 Aug 2019 14:47:04 -0400", "msg_from": "Joshua Brindle <joshua.brindle@crunchydata.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On 2019-08-28 14:30:20 -0400, Tom Lane wrote:\n> Andres Freund <andres@anarazel.de> writes:\n> > Maybe I'm missing something, but it's not clear to me what meaningful\n> > attack surface can be reduced for PostgreSQL by forbidding certain\n> > syscalls, given the wide variety of syscalls required to run postgres.\n> \n> I think the idea is to block access to seldom-used syscalls because\n> those are exactly the ones most likely to have bugs.\n\nYea, I can see some benefit in that. I'm just quite doubtful that the\nset of syscalls pg relies on doesn't already allow any determined\nattacker to trigger kernel bugs. E.g. the whole sysv ipc code is among\nthose seldomly used areas of the code. As is the permission transfer\nthrough unix sockets. As is forking from within a syscall. ...\n\n\n> (We certainly hope that all the ones PG uses are well-debugged...)\n\nOne would hope, but it's not quite my experience...\n\n\n\n> Whether the incremental protection is really worth the effort is\n> debatable, but as long as it's only people who think it *is* worth the\n> effort who have to deal with it, I don't mind.\n\nIt seems almost guaranteed that there'll be bug reports about ominous\ncrashes due to some less commonly used syscall being blacklisted. In a\nlot of cases that'll be hard to debug. After all, we already got such\nbug reports, without us providing anything builtin - and it's not like\nus adding our own filter suport will make container solutions not use\ntheir filter, so there's no argument that doing so ourselves will reduce\nthe fragility.\n\n\n> Admittedly, you can't get per-subprocess restrictions that way, but the\n> incremental value from that seems *really* tiny. If listen() has a bug\n> you need to fix the bug, not invent this amount of rickety infrastructure\n> to limit who can call it.\n\nAnd, as I mentioned in another email, once you can corrupt shared memory\nin arbitrary ways, the differing restrictions aren't worth much\nanyway. Postmaster might be separated out enough to survive attacks like\nthat, but backends definitely aren't.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 28 Aug 2019 11:47:53 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On Wed, Aug 28, 2019 at 2:47 PM Joshua Brindle\n<joshua.brindle@crunchydata.com> wrote:\n>\n> On Wed, Aug 28, 2019 at 2:30 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >\n> <snip>\n> >\n> > (And, TBH, I'm still wondering why SELinux isn't the way to address this.)\n>\n> Just going to address this one now. SELinux is an LSM and therefore\n> only makes decisions when LSM hooks are invoked, which are not 1:1 for\n> syscalls (not even close). Further, SELinux generally determines what\n> objects a subject can access and only implements capabilities because\n> it has to, to be non-bypassable.\n>\n> Seccomp filtering is an orthogonal system to SELinux and LSMs in\n> general. We are already doing work to further restrict PG subprocesses\n> with SELinux via [1] and [2], but that doesn't address the unused,\n\nAnd I forgot the citations *sigh*, actually there should have only been [1]:\n\n1. https://commitfest.postgresql.org/24/2259/\n\n> high-risk, obsolete, etc syscall issue. A prime example is madvise()\n> which was a catastrophic failure that 1) isn't preventable by any LSM\n> including SELinux, 2) isn't used by PG and is therefore a good\n> candidate for a kill list, and 3) a clear win in the\n> dont-let-PG-be-a-vector-for-kernel-compromise arena.\n>\n> We are using SELinux, we are also going to use this, they work together.\n\n\n", "msg_date": "Wed, 28 Aug 2019 14:48:28 -0400", "msg_from": "Joshua Brindle <joshua.brindle@crunchydata.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "Hi,\n\nOn 2019-08-28 14:47:04 -0400, Joshua Brindle wrote:\n> A prime example is madvise() which was a catastrophic failure that 1)\n> isn't preventable by any LSM including SELinux, 2) isn't used by PG\n> and is therefore a good candidate for a kill list, and 3) a clear win\n> in the dont-let-PG-be-a-vector-for-kernel-compromise arena.\n\nIIRC it's used by glibc as part of its malloc implementation (also\nthreading etc) - but not necessarily hit during the most common\npaths. That's *precisely* my problem with this approach.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 28 Aug 2019 11:53:02 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2019-08-28 14:30:20 -0400, Tom Lane wrote:\n>> Admittedly, you can't get per-subprocess restrictions that way, but the\n>> incremental value from that seems *really* tiny. If listen() has a bug\n>> you need to fix the bug, not invent this amount of rickety infrastructure\n>> to limit who can call it.\n\n> And, as I mentioned in another email, once you can corrupt shared memory\n> in arbitrary ways, the differing restrictions aren't worth much\n> anyway. Postmaster might be separated out enough to survive attacks like\n> that, but backends definitely aren't.\n\nAnother point in this area is that if you did feel a need for per-process\nsyscall sets, having a restriction that the postmaster's allowed set be a\nsuperset of all the childrens' allowed sets seems quite the wrong thing.\nThe set of calls the postmaster needs is probably a lot smaller than what\nthe children need, seeing that it does so little. It's just different\nbecause it includes bind+listen which the children likely don't need.\nSo the hierarchical way seccomp goes about this seems fairly wrong for\nour purposes regardless.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 28 Aug 2019 14:58:01 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On Wed, Aug 28, 2019 at 2:53 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> Hi,\n>\n> On 2019-08-28 14:47:04 -0400, Joshua Brindle wrote:\n> > A prime example is madvise() which was a catastrophic failure that 1)\n> > isn't preventable by any LSM including SELinux, 2) isn't used by PG\n> > and is therefore a good candidate for a kill list, and 3) a clear win\n> > in the dont-let-PG-be-a-vector-for-kernel-compromise arena.\n>\n> IIRC it's used by glibc as part of its malloc implementation (also\n> threading etc) - but not necessarily hit during the most common\n> paths. That's *precisely* my problem with this approach.\n>\n\nAs long as glibc handles a returned error cleanly the syscall could be\ndenied without harming the process and the bug would be mitigated.\n\nseccomp also allows argument whitelisting so things can get very\ngranular, depending on who is setting up the lists.\n\n\n", "msg_date": "Wed, 28 Aug 2019 15:02:17 -0400", "msg_from": "Joshua Brindle <joshua.brindle@crunchydata.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "Andres Freund <andres@anarazel.de> writes:\n> On 2019-08-28 14:47:04 -0400, Joshua Brindle wrote:\n>> A prime example is madvise() which was a catastrophic failure that 1)\n>> isn't preventable by any LSM including SELinux, 2) isn't used by PG\n>> and is therefore a good candidate for a kill list, and 3) a clear win\n>> in the dont-let-PG-be-a-vector-for-kernel-compromise arena.\n\n> IIRC it's used by glibc as part of its malloc implementation (also\n> threading etc) - but not necessarily hit during the most common\n> paths. That's *precisely* my problem with this approach.\n\nI think Andres is right here. There are madvise calls in glibc:\n\nglibc-2.28/malloc/malloc.c: __madvise (paligned_mem, size & ~psm1, MADV_DONTNEED);\nglibc-2.28/malloc/arena.c: __madvise ((char *) h + new_size, diff, MADV_DONTNEED);\n\nIt appears that the first is only reachable from __malloc_trim which\nwe don't use, but the second is reachable from free(). However,\nstrace'ing says that it's never called during our standard regression\ntests, confirming Andres' thought that it's in seldom-reached paths.\n(I did not go through the free() logic in any detail, but it looks\nlike it is only reached when dealing with quite-large allocations,\nwhich'd make sense.)\n\nSo this makes a perfect example for Peter's point that testing is\ngoing to be a very fallible way of finding the set of syscalls that\nneed to be allowed. Even if we had 100.00% code coverage of PG\nproper, we would not necessarily find calls like this.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 28 Aug 2019 15:19:19 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "Hi,\n\nOn 2019-08-28 15:02:17 -0400, Joshua Brindle wrote:\n> On Wed, Aug 28, 2019 at 2:53 PM Andres Freund <andres@anarazel.de> wrote:\n> > On 2019-08-28 14:47:04 -0400, Joshua Brindle wrote:\n> > > A prime example is madvise() which was a catastrophic failure that 1)\n> > > isn't preventable by any LSM including SELinux, 2) isn't used by PG\n> > > and is therefore a good candidate for a kill list, and 3) a clear win\n> > > in the dont-let-PG-be-a-vector-for-kernel-compromise arena.\n> >\n> > IIRC it's used by glibc as part of its malloc implementation (also\n> > threading etc) - but not necessarily hit during the most common\n> > paths. That's *precisely* my problem with this approach.\n> >\n> \n> As long as glibc handles a returned error cleanly the syscall could be\n> denied without harming the process and the bug would be mitigated.\n\nAnd we'd hit mysterious slowdowns in production uses of PG when seccomp\nis enabled.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 28 Aug 2019 12:22:55 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On Wed, Aug 28, 2019 at 3:22 PM Andres Freund <andres@anarazel.de> wrote:\n>\n> Hi,\n>\n> On 2019-08-28 15:02:17 -0400, Joshua Brindle wrote:\n> > On Wed, Aug 28, 2019 at 2:53 PM Andres Freund <andres@anarazel.de> wrote:\n> > > On 2019-08-28 14:47:04 -0400, Joshua Brindle wrote:\n> > > > A prime example is madvise() which was a catastrophic failure that 1)\n> > > > isn't preventable by any LSM including SELinux, 2) isn't used by PG\n> > > > and is therefore a good candidate for a kill list, and 3) a clear win\n> > > > in the dont-let-PG-be-a-vector-for-kernel-compromise arena.\n> > >\n> > > IIRC it's used by glibc as part of its malloc implementation (also\n> > > threading etc) - but not necessarily hit during the most common\n> > > paths. That's *precisely* my problem with this approach.\n> > >\n> >\n> > As long as glibc handles a returned error cleanly the syscall could be\n> > denied without harming the process and the bug would be mitigated.\n>\n> And we'd hit mysterious slowdowns in production uses of PG when seccomp\n> is enabled.\n\nIt seems like complete system compromises should be prioritized over\nslowdowns, and it seems very unlikely to cause a noticeable slowdown\nanyway. Are there PG users that backed out all of the Linux KPTI\npatches due to the slowdown?\n\nI think we need to reign in the thread somewhat. The feature allows\nend users to define some sandboxing within PG. Nothing is being forced\non anyone but we would like the capability to harden a PG installation\nfor many reasons already stated. This is being done in places all\nacross the Linux ecosystem and is IMO a very useful mitigation.\n\nThank you.\n\n\n", "msg_date": "Wed, 28 Aug 2019 15:38:11 -0400", "msg_from": "Joshua Brindle <joshua.brindle@crunchydata.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On Thu, Aug 29, 2019 at 7:08 AM Joshua Brindle\n<joshua.brindle@crunchydata.com> wrote:\n> On Wed, Aug 28, 2019 at 2:53 PM Andres Freund <andres@anarazel.de> wrote:\n> > On 2019-08-28 14:47:04 -0400, Joshua Brindle wrote:\n> > > A prime example is madvise() which was a catastrophic failure that 1)\n> > > isn't preventable by any LSM including SELinux, 2) isn't used by PG\n> > > and is therefore a good candidate for a kill list, and 3) a clear win\n> > > in the dont-let-PG-be-a-vector-for-kernel-compromise arena.\n> >\n> > IIRC it's used by glibc as part of its malloc implementation (also\n> > threading etc) - but not necessarily hit during the most common\n> > paths. That's *precisely* my problem with this approach.\n> >\n>\n> As long as glibc handles a returned error cleanly the syscall could be\n> denied without harming the process and the bug would be mitigated.\n>\n> seccomp also allows argument whitelisting so things can get very\n> granular, depending on who is setting up the lists.\n\nJust by the way, there may also be differences between architectures.\nAfter some head scratching, we recently discovered[1] that default\nseccomp whitelists currently cause PostgreSQL to panic for users of\nDocker, Nspawn etc on POWER and ARM because of that. That's a bug\nbeing fixed elsewhere, but it reveals another thing to be careful of\nif you're trying to build your own whitelist by guessing what libc\nneeds to call.\n\n[1] https://www.postgresql.org/message-id/flat/CA%2BhUKGLiR569VHLjtCNp3NT%2BjnKdhy8g2sdgKzWNojyWQVt6Bw%40mail.gmail.com\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Thu, 29 Aug 2019 07:47:35 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "Hi,\n\nOn 2019-08-28 15:38:11 -0400, Joshua Brindle wrote:\n> It seems like complete system compromises should be prioritized over\n> slowdowns, and it seems very unlikely to cause a noticeable slowdown\n> anyway.\n\nThe point isn't really this specific issue, but that the argument that\nyou'll not cause problems by disabling certain syscalls, or that it's\neasy to find which ones are used, just plainly isn't true.\n\n\n> Are there PG users that backed out all of the Linux KPTI patches due\n> to the slowdown?\n\nWell, not backed out on a code level, but straight out disabled at boot\ntime (i.e. pti=off)? Yea, I know of several.\n\n\n> I think we need to reign in the thread somewhat. The feature allows\n> end users to define some sandboxing within PG. Nothing is being forced\n> on anyone\n\nWell, we'll have to deal with the fallout of this to some degree. When\npostgres breaks people will complain, when it's slow, people will\ncomplain, ...\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 28 Aug 2019 12:49:05 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On 2019-08-28 21:38, Joshua Brindle wrote:\n> I think we need to reign in the thread somewhat. The feature allows\n> end users to define some sandboxing within PG. Nothing is being forced\n> on anyone\n\nFeatures come with a maintenance cost. If we ship it, then people are\ngoing to try it out. Then weird things will happen. They will report\nmysterious bugs. They will complain to their colleagues. It all comes\nwith a cost.\n\n> but we would like the capability to harden a PG installation\n> for many reasons already stated.\n\nMost if not all of those reasons seem to have been questioned.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 28 Aug 2019 22:07:56 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On 2019-Aug-28, Joshua Brindle wrote:\n\n> I think we need to reign in the thread somewhat. The feature allows\n> end users to define some sandboxing within PG. Nothing is being forced\n> on anyone but we would like the capability to harden a PG installation\n> for many reasons already stated.\n\nMy own objection to this line of development is that it doesn't seem\nthat any useful policy (allowed/denied syscall list) is part or intends\nto be part of the final feature. So we're shipping a hook system for\nwhich each independent vendor is going to develop their own policy. Joe\nprovided an example syscall list, but it's not part of the patch proper;\nand it seems, per the discussion, that the precise syscall list to use\nis a significant fraction of this.\n\nSo, as part of a committable patch, IMO it'd be good to have some sort\nof final list of syscalls -- maybe as part of the docbook part of the\npatch.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 28 Aug 2019 16:49:14 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On 8/28/19 4:07 PM, Peter Eisentraut wrote:\n> On 2019-08-28 21:38, Joshua Brindle wrote:\n>> I think we need to reign in the thread somewhat. The feature allows\n>> end users to define some sandboxing within PG. Nothing is being forced\n>> on anyone\n> \n> Features come with a maintenance cost. If we ship it, then people are\n> going to try it out. Then weird things will happen. They will report\n> mysterious bugs. They will complain to their colleagues. It all comes\n> with a cost.\n> \n>> but we would like the capability to harden a PG installation\n>> for many reasons already stated.\n> \n> Most if not all of those reasons seem to have been questioned.\n\n\nClearly Joshua and I disagree, but understand that the consensus is not\non our side. It is our assessment that PostgreSQL will be subject to\nseccomp willingly or not (e.g., via docker, systemd, etc.) and the\ncommunity might be better served to get out in front and have first\nclass support.\n\nBut I don't want to waste any more of anyone's time on this topic,\nexcept to ask if two strategically placed hooks are asking too much?\n\nSpecifically hooks to replace these two stanzas in the patch:\n\n8<--------------------------\ndiff --git a/src/backend/postmaster/postmaster.c\nb/src/backend/postmaster/postmaster.c\nindex 62dc93d..2216d49 100644\n*** a/src/backend/postmaster/postmaster.c\n--- b/src/backend/postmaster/postmaster.c\n*************** PostmasterMain(int argc, char *argv[])\n*** 963,968 ****\n--- 963,982 ----\n\n[...]\n\ndiff --git a/src/backend/utils/init/postinit.c\nb/src/backend/utils/init/postinit.c\nindex 43b9f17..aac1940 100644\n*** a/src/backend/utils/init/postinit.c\n--- b/src/backend/utils/init/postinit.c\n*************** InitPostgres(const char *in_dbname, Oid\n*** 1056,1061 ****\n--- 1056,1076 ----\n\n[...]\n\n8<--------------------------\n\n\nWe will continue to pursue this development for customers that require\nit and plan to provide an update on our analysis and results.\n\nWe thank you for your comments and suggestions.\n\nJoe\n-- \nCrunchy Data - http://crunchydata.com\nPostgreSQL Support for Secure Enterprises\nConsulting, Training, & Open Source Development", "msg_date": "Thu, 29 Aug 2019 09:51:25 -0400", "msg_from": "Joe Conway <mail@joeconway.com>", "msg_from_op": true, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "Joe Conway <mail@joeconway.com> writes:\n> Clearly Joshua and I disagree, but understand that the consensus is not\n> on our side. It is our assessment that PostgreSQL will be subject to\n> seccomp willingly or not (e.g., via docker, systemd, etc.) and the\n> community might be better served to get out in front and have first\n> class support.\n\nSure, but ...\n\n> But I don't want to waste any more of anyone's time on this topic,\n> except to ask if two strategically placed hooks are asking too much?\n\n... hooks are still implying a design with the filter control inside\nPostgres. Which, as I said before, seems like a fundamentally incorrect\narchitecture. I'm not objecting to having such control, but I think\nit has to be outside the postmaster, or it's just not a credible\nsecurity improvement. It doesn't help to say \"I'm going to install\na lock to keep out a thief who *by assumption* is carrying lock\npicking tools.\"\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 29 Aug 2019 10:00:54 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On Thu, Aug 29, 2019 at 10:01 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> Joe Conway <mail@joeconway.com> writes:\n> > Clearly Joshua and I disagree, but understand that the consensus is not\n> > on our side. It is our assessment that PostgreSQL will be subject to\n> > seccomp willingly or not (e.g., via docker, systemd, etc.) and the\n> > community might be better served to get out in front and have first\n> > class support.\n>\n> Sure, but ...\n>\n> > But I don't want to waste any more of anyone's time on this topic,\n> > except to ask if two strategically placed hooks are asking too much?\n>\n> ... hooks are still implying a design with the filter control inside\n> Postgres. Which, as I said before, seems like a fundamentally incorrect\n> architecture. I'm not objecting to having such control, but I think\n> it has to be outside the postmaster, or it's just not a credible\n> security improvement. It doesn't help to say \"I'm going to install\n> a lock to keep out a thief who *by assumption* is carrying lock\n> picking tools.\"\n>\n\nI recognize this discussion is over but this is a mischaracterization\nof the intent. Upthread I said:\n\"This may not do it alone, and security\nconscious integrators will want to, for example, add seccomp filters\nto systemd to prevent superuser from disabling them. The postmaster\nand per-role lists can further reduce the available syscalls based on\nthe exact extensions and PLs being used. Each step reduced the surface\nmore and throwing it all out because one step can go rogue is\nunsatisfying.\"\n\nThere are no security silver bullets, each thing we do is risk\nreduction, and that includes this patchset, whether you can see it or\nnot.\n\nThank you.\n\n\n", "msg_date": "Thu, 29 Aug 2019 10:17:29 -0400", "msg_from": "Joshua Brindle <joshua.brindle@crunchydata.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On 8/29/19 10:00 AM, Tom Lane wrote:\n> Joe Conway <mail@joeconway.com> writes:\n>> Clearly Joshua and I disagree, but understand that the consensus is not\n>> on our side. It is our assessment that PostgreSQL will be subject to\n>> seccomp willingly or not (e.g., via docker, systemd, etc.) and the\n>> community might be better served to get out in front and have first\n>> class support.\n> \n> Sure, but ...\n> \n>> But I don't want to waste any more of anyone's time on this topic,\n>> except to ask if two strategically placed hooks are asking too much?\n> \n> ... hooks are still implying a design with the filter control inside\n> Postgres. Which, as I said before, seems like a fundamentally incorrect\n> architecture. I'm not objecting to having such control, but I think\n> it has to be outside the postmaster, or it's just not a credible\n> security improvement.\n\nI disagree. Once a filter is loaded there is no way to unload it short\nof a postmaster restart. That is an easily detected event that can be\nalerted upon, and that is definitely a security improvement.\n\nPerhaps that is a reason to also set the session level GUC to\nPGC_POSTMASTER, but that is an easy change if deemed necessary.\n\nJoe\n\n-- \nCrunchy Data - http://crunchydata.com\nPostgreSQL Support for Secure Enterprises\nConsulting, Training, & Open Source Development", "msg_date": "Thu, 29 Aug 2019 10:28:00 -0400", "msg_from": "Joe Conway <mail@joeconway.com>", "msg_from_op": true, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "Hi,\n\nThis patch is currently in \"needs review\" state, but the last message is\nfrom August 29, and my understanding is that there have been a couple of\nobjections / disagreements about the architecture, difficulties with\nproducing the set of syscalls, and not providing any built-in policy.\n\nI don't think we're any closer to resolve those disagreements since\nAugust, so I think we should make some decision about this patch,\ninstead of just moving it from one CF to the next one. The \"needs\nreview\" status seems not reflecting the situation.\n\nAre there any plans to post a new version of the patch with a different\ndesign, or something like that? If not, I propose we mark it either as\nrejected or returned with feedback (and maybe get a new patch in the\nfuture).\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 7 Jan 2020 02:37:43 +0100", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On 1/6/20 8:37 PM, Tomas Vondra wrote:\n> Hi,\n> \n> This patch is currently in \"needs review\" state, but the last message is\n> from August 29, and my understanding is that there have been a couple of\n> objections / disagreements about the architecture, difficulties with\n> producing the set of syscalls, and not providing any built-in policy.\n> \n> I don't think we're any closer to resolve those disagreements since\n> August, so I think we should make some decision about this patch,\n> instead of just moving it from one CF to the next one. The \"needs\n> review\" status seems not reflecting the situation.\n> \n> Are there any plans to post a new version of the patch with a different\n> design, or something like that? If not, I propose we mark it either as\n> rejected or returned with feedback (and maybe get a new patch in the\n> future).\n\n\nI assumed it was rejected.\n\nJoe\n\n-- \nCrunchy Data - http://crunchydata.com\nPostgreSQL Support for Secure Enterprises\nConsulting, Training, & Open Source Development", "msg_date": "Tue, 7 Jan 2020 06:02:14 -0500", "msg_from": "Joe Conway <mail@joeconway.com>", "msg_from_op": true, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On Tue, Jan 07, 2020 at 06:02:14AM -0500, Joe Conway wrote:\n>On 1/6/20 8:37 PM, Tomas Vondra wrote:\n>> Hi,\n>>\n>> This patch is currently in \"needs review\" state, but the last message is\n>> from August 29, and my understanding is that there have been a couple of\n>> objections / disagreements about the architecture, difficulties with\n>> producing the set of syscalls, and not providing any built-in policy.\n>>\n>> I don't think we're any closer to resolve those disagreements since\n>> August, so I think we should make some decision about this patch,\n>> instead of just moving it from one CF to the next one. The \"needs\n>> review\" status seems not reflecting the situation.\n>>\n>> Are there any plans to post a new version of the patch with a different\n>> design, or something like that? If not, I propose we mark it either as\n>> rejected or returned with feedback (and maybe get a new patch in the\n>> future).\n>\n>\n>I assumed it was rejected.\n>\n\nI don't know. I still see it in the CF app with \"needs review\" status:\n\n https://commitfest.postgresql.org/26/2263/\n\nBarring objections, I'll mark it as rejected.\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 7 Jan 2020 13:59:00 +0100", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On Tue, Jan 7, 2020 at 7:59 AM Tomas Vondra\n<tomas.vondra@2ndquadrant.com> wrote:\n> Barring objections, I'll mark it as rejected.\n\nI think that's right. Since I just caught up on this thread, I'd like\nto offer a few belated comments:\n\n1. I don't think it would kill us to add a few hooks that would allow\nthis feature to be added by a loadable module. Someone may argue that\nwe should never add a hook unless we know exactly how it's going to be\nused and agree with it as a goal, but I don't agree with that.\nRefusing to add hooks just causes people to fork the server. If\nsomebody loads code that uses a hook at least you can tell that\nthey've done it by looking at shared_preload_libraries; if they fork\nthe server it may be much harder to tell that you're not dealing with\nstraight-up PostgreSQL. At any rate, ease-of-debugging considerations\nfor core developers should not take precedence over letting people do\nwith PostgreSQL what they wish.\n\n2. I feel strongly that shipping this feature with mechanism but not\npolicy is unwise; I thought Alvaro articulated this problem\nparticularly well. I think the evidence on this thread is pretty\nclear: this WILL break for some users, and it WILL need fixing. If the\nmechanism is in core and the policy is not, then it seems likely that\nemployees at Crunchy, who apparently run into customers that need this\non a regular basis, will develop a set of best practices which will\nallow them to advise customers as to what settings will or will not\nwork well, but because that knowledge will not be embedded in core, it\nwill be pretty hard for anybody else to support such customers, unless\nthey too have a lot of customers who want to run in this mode. I would\nbe a lot more supportive of this if both the mechanism and the policy\nwere going to ship in core and be maintained in core, with adequate\ndocumentation.\n\n3. The difficulty in making that happen is that the set of system\ncalls that need to be whitelisted seems likely to vary based on\nplatform, kernel version, glibc version, PostgreSQL build options,\nloadable modules used, and which specific PostgreSQL features you care\nabout. I can't help feeling that this is designed mostly for processes\nthat do far simpler things than PostgreSQL. It would be interesting,\nfor example, to know what bash or perl does about this. They have the\nsame problem that PostgreSQL does, namely, that they are intended to\nlet users do almost arbitrary things by design -- not a totally\nunlimited set of things, but an awful lot of things. Perhaps over time\nthis mechanism will undergo design changes, or a clearer set of best\npractices will emerge, so that it's easier to see how PostgreSQL could\nuse this without breaking things. If indeed this is the future, you\ncan imagine something like glibc getting a \"seccomp-clean\" mode in\nwhich it can be built, and if that happened and were widely used, then\nthe difficulties for PostgreSQL would be reduced. Because such\nimprovements typically happen over time through trial and error and\nthe efforts of many people, I think it is to our advantage to allow\npeople to experiment with the feature even as it exists today out of\ncore, which gets me back to point #1. I agree with Joshua Brindle's\npoint that holding our breath in response to a widely-adopted\ntechnology is not a very useful response.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 7 Jan 2020 11:33:07 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On Tue, Jan 07, 2020 at 11:33:07AM -0500, Robert Haas wrote:\n>On Tue, Jan 7, 2020 at 7:59 AM Tomas Vondra\n><tomas.vondra@2ndquadrant.com> wrote:\n>> Barring objections, I'll mark it as rejected.\n>\n>I think that's right.\n\nDone.\n\n>Since I just caught up on this thread, I'd like to offer a few belated\n>comments:\n>\n>1. I don't think it would kill us to add a few hooks that would allow\n>this feature to be added by a loadable module. Someone may argue that\n>we should never add a hook unless we know exactly how it's going to be\n>used and agree with it as a goal, but I don't agree with that.\n>Refusing to add hooks just causes people to fork the server. If\n>somebody loads code that uses a hook at least you can tell that they've\n>done it by looking at shared_preload_libraries; if they fork the server\n>it may be much harder to tell that you're not dealing with straight-up\n>PostgreSQL. At any rate, ease-of-debugging considerations for core\n>developers should not take precedence over letting people do with\n>PostgreSQL what they wish.\n>\n\nNot sure I understand. I don't think anyone argued by hooks vs. forking\nthe server in this particular thread, but the thread is fairly long so\nmaybe I'm missing something.\n\nI think the \"hook issue\" is that the actual code is somewhere else. On\nthe one hand that minimizes the dev/testing/maintenance burden for us,\non the other hand it means we're not really testing the hooks. Meh.\n\nBut in this case I think the main argument against hooks was that Tom\nthinks it's not really the right way to implement this. I don't know if\nhe's right or not, I don't have an opinion on how to integrate seccomp.\n\n>2. I feel strongly that shipping this feature with mechanism but not\n>policy is unwise; I thought Alvaro articulated this problem\n>particularly well. I think the evidence on this thread is pretty clear:\n>this WILL break for some users, and it WILL need fixing. If the\n>mechanism is in core and the policy is not, then it seems likely that\n>employees at Crunchy, who apparently run into customers that need this\n>on a regular basis, will develop a set of best practices which will\n>allow them to advise customers as to what settings will or will not\n>work well, but because that knowledge will not be embedded in core, it\n>will be pretty hard for anybody else to support such customers, unless\n>they too have a lot of customers who want to run in this mode. I would\n>be a lot more supportive of this if both the mechanism and the policy\n>were going to ship in core and be maintained in core, with adequate\n>documentation.\n>\n\nWell, but this exact argument applies to various other approaches:\n\n1) no hooks, forking PostgreSQL\n2) hooks added, but neither code nor policy included\n3) hooks aded, code included, policy not included\n\nEssentially the only case where Crunchy would not have this \"lock-in\"\nadvantage is when everything is included into PostgreSQL, at which point\nwe can probably make this work without hooks I suppose.\n\n>3. The difficulty in making that happen is that the set of system calls\n>that need to be whitelisted seems likely to vary based on platform,\n>kernel version, glibc version, PostgreSQL build options, loadable\n>modules used, and which specific PostgreSQL features you care about. I\n>can't help feeling that this is designed mostly for processes that do\n>far simpler things than PostgreSQL. It would be interesting, for\n>example, to know what bash or perl does about this. They have the same\n>problem that PostgreSQL does, namely, that they are intended to let\n>users do almost arbitrary things by design -- not a totally unlimited\n>set of things, but an awful lot of things. Perhaps over time this\n>mechanism will undergo design changes, or a clearer set of best\n>practices will emerge, so that it's easier to see how PostgreSQL could\n>use this without breaking things. If indeed this is the future, you can\n>imagine something like glibc getting a \"seccomp-clean\" mode in which it\n>can be built, and if that happened and were widely used, then the\n>difficulties for PostgreSQL would be reduced. Because such improvements\n>typically happen over time through trial and error and the efforts of\n>many people, I think it is to our advantage to allow people to\n>experiment with the feature even as it exists today out of core, which\n>gets me back to point #1. I agree with Joshua Brindle's point that\n>holding our breath in response to a widely-adopted technology is not a\n>very useful response.\n>\n\nI think this is probably the main challenge of this patch - development,\nmaintenance and testing of the policies. I think it's pretty clear the\ncommunity can't really support this on all possible environments, or\nwith third-party extensions. I don't know if it's even possible to write\na \"universal policy\" covering significant range of systems? It seems\nmuch more realistic that individual providers will develop policies for\nsystems of customers.\n\n\nregards\n\n-- \nTomas Vondra http://www.2ndQuadrant.com\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 7 Jan 2020 18:56:19 +0100", "msg_from": "Tomas Vondra <tomas.vondra@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" }, { "msg_contents": "On Tue, Jan 7, 2020 at 12:56 PM Tomas Vondra\n<tomas.vondra@2ndquadrant.com> wrote:\n> I think the \"hook issue\" is that the actual code is somewhere else. On\n> the one hand that minimizes the dev/testing/maintenance burden for us,\n> on the other hand it means we're not really testing the hooks. Meh.\n\nI don't care about the testing the hooks. If we provide hooks and\nsomeone finds them useful, great. If not, they don't have to use them.\nThe mere existence of this hook isn't going to put any significant\nmaintenance burden on the community, while the feature as a whole\nprobably would.\n\n> Well, but this exact argument applies to various other approaches:\n>\n> 1) no hooks, forking PostgreSQL\n> 2) hooks added, but neither code nor policy included\n> 3) hooks aded, code included, policy not included\n>\n> Essentially the only case where Crunchy would not have this \"lock-in\"\n> advantage is when everything is included into PostgreSQL, at which point\n> we can probably make this work without hooks I suppose.\n\nWell, from my point of view, in case 1 or 2, the feature is entirely\nCrunchy's. If it works great, good for them. If it sucks, it's their\nproblem. In case 3, the feature is ostensibly a community feature but\nprobably nobody other than Crunchy can actually make it work. That\nlatter situation seems a lot more problematic to me. I don't like\nPostgreSQL features that I can't make work. If it's too complicated\nfor other developers to figure out, it's probably going to be a real\npain for users, too.\n\nPutting my cards on the table, I think it's likely that the proposed\ndesign contains a significant amount of suckitude. Serious usability\nand security concerns have been raised, and I find those concerns\nlegitimate. On the other hand, it may still be useful to some people.\nMore importantly, if they can more easily experiment with it, they'll\nhave a chance to find out whether it sucks and, if so, make it better.\nPerhaps something that we can accept into core will ultimately result.\nThat would be good for everybody.\n\nAlso, generally, I don't think we should block features (hooks or\notherwise) because some other company might get more benefit than our\nown employer. That seems antithetical to the concept of open source.\nBlocking them because they're poorly designed or will impose a burden\non the community is a different thing.\n\n> I think this is probably the main challenge of this patch - development,\n> maintenance and testing of the policies. I think it's pretty clear the\n> community can't really support this on all possible environments, or\n> with third-party extensions. I don't know if it's even possible to write\n> a \"universal policy\" covering significant range of systems? It seems\n> much more realistic that individual providers will develop policies for\n> systems of customers.\n\nI generally agree with this, although I'm not sure that I understand\nwhat you're advocating that we do. Accepting the feature as-is seems\nlike a no-go given the remarks already made, and while I don't think I\nfeel as strongly about it as some of the people who have already\nspoken on the topic, I do share their doubts to some degree and am not\nin a position to override them even if I disagreed completely. But,\nhooks would give individual providers those same options, without\nreally burdening anyone else.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Tue, 7 Jan 2020 14:17:15 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: RFC: seccomp-bpf support" } ]
[ { "msg_contents": "Hackers,\n[apologies if this is the incorrect list or is already discussed material]\n\nI've noticed that mailing list discussions in -hackers and other\nmailing lists appear to not be indexed by google -- at all. We are\nalso not being tracked by any mailing list aggregators -- in contrast\nto a decade ago where we had nabble and other systems to collect and\norganize results (tbh, often better than we do) we are now at an\nextreme disadvantage; mailing list activity was formerly and\nabsolutely fantastic research via google to find solutions to obscure\ntechnical problems in the database. Limited access to this\ninformation will directly lead to increased bug reports, lack of\nsolution confidence, etc.\n\nMy test case here is the query: pgsql-hackers ExecHashJoinNewBatch\nI was searching out a link to recent bug report for copy/paste into\ncorporate email. In the old days this would fire right up but now\nreturns no hits even though the discussion is available in the\narchives (which I had to find by looking up the specific day the\nthread was active). Just a heads up.\n\nmerlin\n\n\n", "msg_date": "Wed, 28 Aug 2019 11:22:44 -0500", "msg_from": "Merlin Moncure <mmoncure@gmail.com>", "msg_from_op": true, "msg_subject": "no mailing list hits in google" }, { "msg_contents": "Merlin Moncure <mmoncure@gmail.com> writes:\n> [apologies if this is the incorrect list or is already discussed material]\n\nIt's not the right list; redirecting to pgsql-www.\n\n> I've noticed that mailing list discussions in -hackers and other\n> mailing lists appear to not be indexed by google -- at all. We are\n> also not being tracked by any mailing list aggregators -- in contrast\n> to a decade ago where we had nabble and other systems to collect and\n> organize results (tbh, often better than we do) we are now at an\n> extreme disadvantage; mailing list activity was formerly and\n> absolutely fantastic research via google to find solutions to obscure\n> technical problems in the database. Limited access to this\n> information will directly lead to increased bug reports, lack of\n> solution confidence, etc.\n\n> My test case here is the query: pgsql-hackers ExecHashJoinNewBatch\n> I was searching out a link to recent bug report for copy/paste into\n> corporate email. In the old days this would fire right up but now\n> returns no hits even though the discussion is available in the\n> archives (which I had to find by looking up the specific day the\n> thread was active). Just a heads up.\n\nHm. When I try googling that, the first thing I get is\n\n\tpgsql-hackers - PostgreSQL\n\n\thttps://www.postgresql.org › list › pgsql-hackers\n\tNo information is available for this page.\n\tLearn why\n\nand the \"learn why\" link says that \"You are seeing this result because the\npage is blocked by a robots.txt file on your website.\"\n\nSo somebody has blocked the archives from being indexed.\nSeems like a bad idea.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 28 Aug 2019 12:51:42 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "On Wed, Aug 28, 2019 at 6:51 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n\n> Merlin Moncure <mmoncure@gmail.com> writes:\n> > [apologies if this is the incorrect list or is already discussed\n> material]\n>\n> It's not the right list; redirecting to pgsql-www.\n>\n> > I've noticed that mailing list discussions in -hackers and other\n> > mailing lists appear to not be indexed by google -- at all. We are\n> > also not being tracked by any mailing list aggregators -- in contrast\n> > to a decade ago where we had nabble and other systems to collect and\n> > organize results (tbh, often better than we do) we are now at an\n> > extreme disadvantage; mailing list activity was formerly and\n> > absolutely fantastic research via google to find solutions to obscure\n> > technical problems in the database. Limited access to this\n> > information will directly lead to increased bug reports, lack of\n> > solution confidence, etc.\n>\n> > My test case here is the query: pgsql-hackers ExecHashJoinNewBatch\n> > I was searching out a link to recent bug report for copy/paste into\n> > corporate email. In the old days this would fire right up but now\n> > returns no hits even though the discussion is available in the\n> > archives (which I had to find by looking up the specific day the\n> > thread was active). Just a heads up.\n>\n> Hm. When I try googling that, the first thing I get is\n>\n> pgsql-hackers - PostgreSQL\n>\n> https://www.postgresql.org › list › pgsql-hackers\n> No information is available for this page.\n> Learn why\n>\n> and the \"learn why\" link says that \"You are seeing this result because the\n> page is blocked by a robots.txt file on your website.\"\n>\n> So somebody has blocked the archives from being indexed.\n> Seems like a bad idea.\n>\n\nIt blocks /list/ which has the subjects only. The actual emails in\n/message-id/ are not blocked by robots.txt. I don't know why they stopped\nappearing in the searches... Nothing has been changed around that for many\nyears from *our* side.\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/ <http://www.hagander.net/>\n Work: https://www.redpill-linpro.com/ <http://www.redpill-linpro.com/>\n\nOn Wed, Aug 28, 2019 at 6:51 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:Merlin Moncure <mmoncure@gmail.com> writes:\n> [apologies if this is the incorrect list or is already discussed material]\n\nIt's not the right list; redirecting to pgsql-www.\n\n> I've noticed that mailing list discussions in -hackers and other\n> mailing lists appear to not be indexed by google -- at all.  We are\n> also not being tracked by any mailing list aggregators -- in contrast\n> to a decade ago where we had nabble and other systems to collect and\n> organize results (tbh, often better than we do) we are now at an\n> extreme disadvantage; mailing list activity was formerly and\n> absolutely fantastic research via google to find solutions to obscure\n> technical problems in the database.  Limited access to this\n> information will directly lead to increased bug reports, lack of\n> solution confidence, etc.\n\n> My test case here is the query: pgsql-hackers ExecHashJoinNewBatch\n> I was searching out a link to recent bug report for copy/paste into\n> corporate email. In the old days this would fire right up but now\n> returns no hits even though the discussion is available in the\n> archives (which I had to find by looking up the specific day the\n> thread was active).  Just a heads up.\n\nHm.  When I try googling that, the first thing I get is\n\n        pgsql-hackers - PostgreSQL\n\n        https://www.postgresql.org › list › pgsql-hackers\n        No information is available for this page.\n        Learn why\n\nand the \"learn why\" link says that \"You are seeing this result because the\npage is blocked by a robots.txt file on your website.\"\n\nSo somebody has blocked the archives from being indexed.\nSeems like a bad idea.It blocks /list/ which has the subjects only. The actual emails in /message-id/ are not blocked by robots.txt.  I don't know why they stopped appearing in the searches... Nothing has been changed around that for many years from *our* side. --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Wed, 28 Aug 2019 19:09:40 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "Hi,\n\nOn August 28, 2019 9:22:44 AM PDT, Merlin Moncure <mmoncure@gmail.com> wrote:\n>Hackers,\n>[apologies if this is the incorrect list or is already discussed\n>material]\n\nProbably should be on the -www list. Redirecting. Please trim in future replies.\n\n>I've noticed that mailing list discussions in -hackers and other\n>mailing lists appear to not be indexed by google -- at all.\n\nI noticed that there's fewer and fewer hits too. Pretty annoying. I have an online archive I can search, but that's not something everyone should have to do.\n\nI think it's because robots.txt tells search engines to ignore the lists. Quite hard to understand how that's a good idea.\n\nhttps://www.postgresql.org/robots.txt\n\nUser-agent: *\nDisallow: /admin/\nDisallow: /account/\nDisallow: /docs/devel/\nDisallow: /list/\nDisallow: /search/\nDisallow: /message-id/raw/\nDisallow: /message-id/flat/\n\nSitemap: https://www.postgresql.org/sitemap.xml \n\nWithout /list, there's no links to the individual messages. So there needs to be another external reference for a search engine to arrive at individual messages.\n\nAndres\n-- \nSent from my Android device with K-9 Mail. Please excuse my brevity.\nHi,-- Sent from my Android device with K-9 Mail. Please excuse my brevity.", "msg_date": "Wed, 28 Aug 2019 10:26:35 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "Hi,\n\nOn 2019-08-28 19:09:40 +0200, Magnus Hagander wrote:\n> It blocks /list/ which has the subjects only.\n\nYea. But there's no way to actually get to all the individual messages\nwithout /list/? Sure, some will be linked to from somewhere else, but\nwithout the content below /list/, most won't be reached?\n\nWhy is that /list/ exclusion there in the first place?\n\n\n> Nothing has been changed around that for many years from *our* side.\n\nAny chance that there previously still was an archives.postgresql.org\nview or such that allowed to reach the individual messages without being\nblocked by robots.txt?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 28 Aug 2019 10:45:53 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "Hi,\n\nOn 2019-08-28 10:26:35 -0700, Andres Freund wrote:\n> On August 28, 2019 9:22:44 AM PDT, Merlin Moncure <mmoncure@gmail.com> wrote:\n> >Hackers,\n> >[apologies if this is the incorrect list or is already discussed\n> >material]\n> \n> Probably should be on the -www list. Redirecting. Please trim in future replies.\n> \n> >I've noticed that mailing list discussions in -hackers and other\n> >mailing lists appear to not be indexed by google -- at all.\n> \n> I noticed that there's fewer and fewer hits too. Pretty annoying. I have an online archive I can search, but that's not something everyone should have to do.\n> \n> I think it's because robots.txt tells search engines to ignore the lists. Quite hard to understand how that's a good idea.\n> \n> https://www.postgresql.org/robots.txt\n> \n> User-agent: *\n> Disallow: /admin/\n> Disallow: /account/\n> Disallow: /docs/devel/\n> Disallow: /list/\n> Disallow: /search/\n> Disallow: /message-id/raw/\n> Disallow: /message-id/flat/\n> \n> Sitemap: https://www.postgresql.org/sitemap.xml \n> \n> Without /list, there's no links to the individual messages. So there needs to be another external reference for a search engine to arrive at individual messages.\n> \n> Andres\n> -- \n> Sent from my Android device with K-9 Mail. Please excuse my brevity.\n\nFor reasons that I do not understand, the previous mail had a broken\nhtml part, making the above message invisible for people viewing the\nhtml part.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 28 Aug 2019 10:48:00 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "Magnus Hagander <magnus@hagander.net> writes:\n> It blocks /list/ which has the subjects only. The actual emails in\n> /message-id/ are not blocked by robots.txt. I don't know why they stopped\n> appearing in the searches... Nothing has been changed around that for many\n> years from *our* side.\n\nIf I go to\n\nhttps://www.postgresql.org/message-id/\n\nI get a page saying \"Not Found\". So I'm not clear on how a web crawler\nwould descend through that to individual messages.\n\nEven if it looks different to a robot, what would it look like exactly?\nA flat space of umpteen zillion immediate-child pages? It seems not\nimprobable that Google's search engine would intentionally decide not to\nindex that, or unintentionally just fail due to some internal resource\nlimit. (This theory can explain why it used to work and no longer does:\nwe got past whatever the limit is.)\n\nAndres' idea of allowing access to /list/ would allow the archives to be\ntraversed in more bite-size pieces, which might fix the issue.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 28 Aug 2019 13:59:40 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "Merlin Moncure schrieb am 28.08.2019 um 18:22:\n> My test case here is the query: pgsql-hackers\n\nThat search term is the first hit on DuckDuckGo:\nhttps://duckduckgo.com/?q=pgsql-hackers+ExecHashJoinNewBatch&t=h_&ia=web\n\nSearching for \"postgres ExecHashJoinNewBatch\" returns that ot position 4\nhttps://duckduckgo.com/?q=postgres+ExecHashJoinNewBatch&t=h_&ia=web\n\n\n\n", "msg_date": "Wed, 28 Aug 2019 20:20:38 +0200", "msg_from": "Thomas Kellerer <shammat@gmx.net>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "On 2019-Aug-28, Thomas Kellerer wrote:\n\n> Merlin Moncure schrieb am 28.08.2019 um 18:22:\n> > My test case here is the query: pgsql-hackers\n> \n> That search term is the first hit on DuckDuckGo:\n> https://duckduckgo.com/?q=pgsql-hackers+ExecHashJoinNewBatch&t=h_&ia=web\n\nYes, but that's an old post, not the one from this year.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 28 Aug 2019 14:31:51 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "On Wed, Aug 28, 2019 at 7:45 PM Andres Freund <andres@anarazel.de> wrote:\n\n> Hi,\n>\n> On 2019-08-28 19:09:40 +0200, Magnus Hagander wrote:\n> > It blocks /list/ which has the subjects only.\n>\n> Yea. But there's no way to actually get to all the individual messages\n> without /list/? Sure, some will be linked to from somewhere else, but\n> without the content below /list/, most won't be reached?\n>\n\nThat is indeed a good point. But it has been that way for many years, so\nsomething must've changed. We last modified this in 2013....\n\nMaybe Google used to load the pages under /list/ and crawl them for links\nbut just not include the actual pages in the index or something\n\nI wonder if we can inject these into Google using a sitemap. I think that\nshould work -- will need some investigation on exactly how to do it, as\nsitemaps also have individual restrictions on the number of urls per file,\nand we do have quite a few messages.\n\n\nWhy is that /list/ exclusion there in the first place?\n>\n\nBecause there are basically infinite number of pages in that space, due to\nthe fact that you can pick an arbitrary point in time to view from.\n\n\n> Nothing has been changed around that for many years from *our* side.\n>\n> Any chance that there previously still was an archives.postgresql.org\n> view or such that allowed to reach the individual messages without being\n> blocked by robots.txt?\n>\n\nThat one had a robots.txt blocking this going back even further in time.\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/ <http://www.hagander.net/>\n Work: https://www.redpill-linpro.com/ <http://www.redpill-linpro.com/>\n\nOn Wed, Aug 28, 2019 at 7:45 PM Andres Freund <andres@anarazel.de> wrote:Hi,\n\nOn 2019-08-28 19:09:40 +0200, Magnus Hagander wrote:\n> It blocks /list/ which has the subjects only.\n\nYea. But there's no way to actually get to all the individual messages\nwithout /list/? Sure, some will be linked to from somewhere else, but\nwithout the content below /list/, most won't be reached?That is indeed a good point. But it has been that way for many years, so something must've changed.   We last modified this in 2013....Maybe Google used to load the pages under /list/ and crawl them for links but just not include the actual pages in the index or somethingI wonder if we can inject these into Google using a sitemap. I think that should work -- will need some investigation on exactly how to do it, as sitemaps also have individual restrictions on the number of urls per file, and we do have quite a few messages.\nWhy is that /list/ exclusion there in the first place?Because there are basically infinite number of pages in that space, due to the fact that you can pick an arbitrary point in time to view from.\n> Nothing has been changed around that for many years from *our* side.\n\nAny chance that there previously still was an archives.postgresql.org\nview or such that allowed to reach the individual messages without being\nblocked by robots.txt?That one had a robots.txt blocking this going back even further in time. --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Thu, 29 Aug 2019 13:12:00 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "On Wed, Aug 28, 2019 at 10:31 PM Alvaro Herrera <alvherre@2ndquadrant.com>\nwrote:\n\n> On 2019-Aug-28, Thomas Kellerer wrote:\n>\n> > Merlin Moncure schrieb am 28.08.2019 um 18:22:\n> > > My test case here is the query: pgsql-hackers\n> >\n> > That search term is the first hit on DuckDuckGo:\n> > https://duckduckgo.com/?q=pgsql-hackers+ExecHashJoinNewBatch&t=h_&ia=web\n>\n> Yes, but that's an old post, not the one from this year.\n>\n>\nIt does show another interesting point though -- it *also* includes hits\nfrom third party list archiving sites, which are *also* gone from Google at\nthis point. And those are definitely not gone from Google because we have a\nrobots.txt blocking /list/ -- it must be something else.\n\n//Magnus\n\nOn Wed, Aug 28, 2019 at 10:31 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:On 2019-Aug-28, Thomas Kellerer wrote:\n\n> Merlin Moncure schrieb am 28.08.2019 um 18:22:\n> > My test case here is the query: pgsql-hackers\n> \n> That search term is the first hit on DuckDuckGo:\n> https://duckduckgo.com/?q=pgsql-hackers+ExecHashJoinNewBatch&t=h_&ia=web\n\nYes, but that's an old post, not the one from this year.It does show another interesting point though -- it *also* includes hits from third party list archiving sites, which are *also* gone from Google at this point. And those are definitely not gone from Google because we have a robots.txt blocking /list/ -- it must be something else. //Magnus", "msg_date": "Thu, 29 Aug 2019 13:13:33 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "On 2019-Aug-29, Magnus Hagander wrote:\n\n> Maybe Google used to load the pages under /list/ and crawl them for links\n> but just not include the actual pages in the index or something\n> \n> I wonder if we can inject these into Google using a sitemap. I think that\n> should work -- will need some investigation on exactly how to do it, as\n> sitemaps also have individual restrictions on the number of urls per file,\n> and we do have quite a few messages.\n> \n> > Why is that /list/ exclusion there in the first place?\n> \n> Because there are basically infinite number of pages in that space, due to\n> the fact that you can pick an arbitrary point in time to view from.\n\nMaybe we can create a new page that's specifically to be used by\ncrawlers, that lists all emails, each only once. Say (unimaginatively)\n/list_crawlers/2019-08/ containing links to all emails of all public\nlists occurring during August 2019.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 29 Aug 2019 09:32:35 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "On Thu, Aug 29, 2019 at 3:32 PM Alvaro Herrera <alvherre@2ndquadrant.com>\nwrote:\n\n> On 2019-Aug-29, Magnus Hagander wrote:\n>\n> > Maybe Google used to load the pages under /list/ and crawl them for links\n> > but just not include the actual pages in the index or something\n> >\n> > I wonder if we can inject these into Google using a sitemap. I think that\n> > should work -- will need some investigation on exactly how to do it, as\n> > sitemaps also have individual restrictions on the number of urls per\n> file,\n> > and we do have quite a few messages.\n> >\n> > > Why is that /list/ exclusion there in the first place?\n> >\n> > Because there are basically infinite number of pages in that space, due\n> to\n> > the fact that you can pick an arbitrary point in time to view from.\n>\n> Maybe we can create a new page that's specifically to be used by\n> crawlers, that lists all emails, each only once. Say (unimaginatively)\n> /list_crawlers/2019-08/ containing links to all emails of all public\n> lists occurring during August 2019.\n>\n>\nThat's pretty much what I'm suggesting but using a sitemap so it's directly\ninjected.\n\n//Magnus\n\nOn Thu, Aug 29, 2019 at 3:32 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:On 2019-Aug-29, Magnus Hagander wrote:\n\n> Maybe Google used to load the pages under /list/ and crawl them for links\n> but just not include the actual pages in the index or something\n> \n> I wonder if we can inject these into Google using a sitemap. I think that\n> should work -- will need some investigation on exactly how to do it, as\n> sitemaps also have individual restrictions on the number of urls per file,\n> and we do have quite a few messages.\n> \n> > Why is that /list/ exclusion there in the first place?\n> \n> Because there are basically infinite number of pages in that space, due to\n> the fact that you can pick an arbitrary point in time to view from.\n\nMaybe we can create a new page that's specifically to be used by\ncrawlers, that lists all emails, each only once.  Say (unimaginatively)\n/list_crawlers/2019-08/ containing links to all emails of all public\nlists occurring during August 2019.That's pretty much what I'm suggesting but using a sitemap so it's directly injected.//Magnus", "msg_date": "Thu, 29 Aug 2019 15:39:39 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "Hi,\n\nOn 2019-08-29 13:12:00 +0200, Magnus Hagander wrote:\n> On Wed, Aug 28, 2019 at 7:45 PM Andres Freund <andres@anarazel.de> wrote:\n> \n> > Hi,\n> >\n> > On 2019-08-28 19:09:40 +0200, Magnus Hagander wrote:\n> > > It blocks /list/ which has the subjects only.\n> >\n> > Yea. But there's no way to actually get to all the individual messages\n> > without /list/? Sure, some will be linked to from somewhere else, but\n> > without the content below /list/, most won't be reached?\n> >\n> \n> That is indeed a good point. But it has been that way for many years, so\n> something must've changed. We last modified this in 2013....\n\nHm. I guess it's possible that most pages were found due to the\nnext/prev links in individual messages, once one of them is linked from\nsomewhere externally. Any chance there's enough logs around to see\nfrom where to where the indexers currently move?\n\n\n> I wonder if we can inject these into Google using a sitemap. I think that\n> should work -- will need some investigation on exactly how to do it, as\n> sitemaps also have individual restrictions on the number of urls per file,\n> and we do have quite a few messages.\n\nHm. You mean in addition to allowing /list/ or solely?\n\n\n> > Why is that /list/ exclusion there in the first place?\n\n> Because there are basically infinite number of pages in that space, due to\n> the fact that you can pick an arbitrary point in time to view from.\n\nYou mean because of the per-day links, that aren't really per-day? I\nthink the number of links due to that would still be manageable traffic\nwise? Or are they that expensive to compute? Perhaps we could make the\n\"jump to day\" links smarter in some way? Perhaps by not including\ncontent for the following days in the per-day pages?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 29 Aug 2019 07:50:13 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "Hi,\n\nOn 2019-08-29 09:32:35 -0400, Alvaro Herrera wrote:\n> On 2019-Aug-29, Magnus Hagander wrote:\n> \n> > Maybe Google used to load the pages under /list/ and crawl them for links\n> > but just not include the actual pages in the index or something\n> > \n> > I wonder if we can inject these into Google using a sitemap. I think that\n> > should work -- will need some investigation on exactly how to do it, as\n> > sitemaps also have individual restrictions on the number of urls per file,\n> > and we do have quite a few messages.\n> > \n> > > Why is that /list/ exclusion there in the first place?\n> > \n> > Because there are basically infinite number of pages in that space, due to\n> > the fact that you can pick an arbitrary point in time to view from.\n> \n> Maybe we can create a new page that's specifically to be used by\n> crawlers, that lists all emails, each only once. Say (unimaginatively)\n> /list_crawlers/2019-08/ containing links to all emails of all public\n> lists occurring during August 2019.\n\nHm. Weren't there occasionally downranking rules for pages that were\nclearly aimed just at search engines? Honestly I find the current\nnavigation with the overlapping content to be not great for humans too,\nso I think it might be worthwhile to rather improve the general\nnavigation and allow robots for /list/. But if that's too much/not well\nspecified enough: perhaps we could mark the per-day links as\nrel=nofollow, but not the prev/next links when starting at certain\nboundaries?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Thu, 29 Aug 2019 07:55:35 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "> On 29 Aug 2019, at 16:55, Andres Freund <andres@anarazel.de> wrote:\n> On 2019-08-29 09:32:35 -0400, Alvaro Herrera wrote:\n>> On 2019-Aug-29, Magnus Hagander wrote:\n>> \n>>> Maybe Google used to load the pages under /list/ and crawl them for links\n>>> but just not include the actual pages in the index or something\n>>> \n>>> I wonder if we can inject these into Google using a sitemap. I think that\n>>> should work -- will need some investigation on exactly how to do it, as\n>>> sitemaps also have individual restrictions on the number of urls per file,\n>>> and we do have quite a few messages.\n>>> \n>>>> Why is that /list/ exclusion there in the first place?\n>>> \n>>> Because there are basically infinite number of pages in that space, due to\n>>> the fact that you can pick an arbitrary point in time to view from.\n>> \n>> Maybe we can create a new page that's specifically to be used by\n>> crawlers, that lists all emails, each only once. Say (unimaginatively)\n>> /list_crawlers/2019-08/ containing links to all emails of all public\n>> lists occurring during August 2019.\n> \n> Hm. Weren't there occasionally downranking rules for pages that were\n> clearly aimed just at search engines?\n\nI think that’s mainly been for pages which are clearly keyword spamming, I\ndoubt our content would get caught there. The sitemap, as proposed upthread,\nis the solution to this however and is also the recommended way from Google for\nsites with lots of content.\n\nGoogle does however explicitly downrank duplicated/similar content, or content\nwhich can be reached via multiple URLs and which doesn’t list a canonical URL\nin the page. A single message and the whole-thread link does contain the same\ncontent, and neither are canonical so we might be incurring penalties from\nthat. Also, the postgr.es/m/ shortener makes content available via two URLs,\nwithout a canonical URL specified.\n\nThat being said, since we haven’t changed anything, and DuckDuckGo happily\nindex the mailinglist posts, this smells a lot more like a policy change than a\ntechnical change if my experience with Google SEO is anything to go by. The\nWebmaster Tools Search Console can quite often give insights as to why a page\nis missing, that’s probably a better place to start then second guessing Google\nSEO. AFAICR, using that requires proving that one owns the site/domain, but\ndoesn’t require adding any google trackers or similar things.\n\ncheers ./daniel\n\n", "msg_date": "Fri, 30 Aug 2019 11:40:16 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "On Fri, Aug 30, 2019 at 11:40 AM Daniel Gustafsson <daniel@yesql.se> wrote:\n\n> > On 29 Aug 2019, at 16:55, Andres Freund <andres@anarazel.de> wrote:\n> > On 2019-08-29 09:32:35 -0400, Alvaro Herrera wrote:\n> >> On 2019-Aug-29, Magnus Hagander wrote:\n> >>\n> >>> Maybe Google used to load the pages under /list/ and crawl them for\n> links\n> >>> but just not include the actual pages in the index or something\n> >>>\n> >>> I wonder if we can inject these into Google using a sitemap. I think\n> that\n> >>> should work -- will need some investigation on exactly how to do it, as\n> >>> sitemaps also have individual restrictions on the number of urls per\n> file,\n> >>> and we do have quite a few messages.\n> >>>\n> >>>> Why is that /list/ exclusion there in the first place?\n> >>>\n> >>> Because there are basically infinite number of pages in that space,\n> due to\n> >>> the fact that you can pick an arbitrary point in time to view from.\n> >>\n> >> Maybe we can create a new page that's specifically to be used by\n> >> crawlers, that lists all emails, each only once. Say (unimaginatively)\n> >> /list_crawlers/2019-08/ containing links to all emails of all public\n> >> lists occurring during August 2019.\n> >\n> > Hm. Weren't there occasionally downranking rules for pages that were\n> > clearly aimed just at search engines?\n>\n> I think that’s mainly been for pages which are clearly keyword spamming, I\n> doubt our content would get caught there. The sitemap, as proposed\n> upthread,\n> is the solution to this however and is also the recommended way from\n> Google for\n> sites with lots of content.\n>\n> Google does however explicitly downrank duplicated/similar content, or\n> content\n> which can be reached via multiple URLs and which doesn’t list a canonical\n> URL\n> in the page. A single message and the whole-thread link does contain the\n> same\n> content, and neither are canonical so we might be incurring penalties from\n> that. Also, the postgr.es/m/ shortener makes content available via two\n> URLs,\n> without a canonical URL specified.\n>\n\nBut robots.txt blocks the whole-thread view (and this is the reason for it).\nAnd postgr.es/m/ does not actually make the content available there, it\nredirects.\n\nSo I don't think those should actually have an effect?\n\n\nThat being said, since we haven’t changed anything, and DuckDuckGo happily\n> index the mailinglist posts, this smells a lot more like a policy change\n> than a\n> technical change if my experience with Google SEO is anything to go by.\n> The\n> Webmaster Tools Search Console can quite often give insights as to why a\n> page\n> is missing, that’s probably a better place to start then second guessing\n> Google\n> SEO. AFAICR, using that requires proving that one owns the site/domain,\n> but\n> doesn’t require adding any google trackers or similar things.\n>\n\nI've tried but failed to get any relevant data out of it. It does clearly\nshow large amounts of URLs blocked because they are in /flat/ or /raw/, but\nnothing at all about the regular messages.\n\n-- \n Magnus Hagander\n Me: https://www.hagander.net/ <http://www.hagander.net/>\n Work: https://www.redpill-linpro.com/ <http://www.redpill-linpro.com/>\n\nOn Fri, Aug 30, 2019 at 11:40 AM Daniel Gustafsson <daniel@yesql.se> wrote:> On 29 Aug 2019, at 16:55, Andres Freund <andres@anarazel.de> wrote:\n> On 2019-08-29 09:32:35 -0400, Alvaro Herrera wrote:\n>> On 2019-Aug-29, Magnus Hagander wrote:\n>> \n>>> Maybe Google used to load the pages under /list/ and crawl them for links\n>>> but just not include the actual pages in the index or something\n>>> \n>>> I wonder if we can inject these into Google using a sitemap. I think that\n>>> should work -- will need some investigation on exactly how to do it, as\n>>> sitemaps also have individual restrictions on the number of urls per file,\n>>> and we do have quite a few messages.\n>>> \n>>>> Why is that /list/ exclusion there in the first place?\n>>> \n>>> Because there are basically infinite number of pages in that space, due to\n>>> the fact that you can pick an arbitrary point in time to view from.\n>> \n>> Maybe we can create a new page that's specifically to be used by\n>> crawlers, that lists all emails, each only once.  Say (unimaginatively)\n>> /list_crawlers/2019-08/ containing links to all emails of all public\n>> lists occurring during August 2019.\n> \n> Hm. Weren't there occasionally downranking rules for pages that were\n> clearly aimed just at search engines?\n\nI think that’s mainly been for pages which are clearly keyword spamming, I\ndoubt our content would get caught there.  The sitemap, as proposed upthread,\nis the solution to this however and is also the recommended way from Google for\nsites with lots of content.\n\nGoogle does however explicitly downrank duplicated/similar content, or content\nwhich can be reached via multiple URLs and which doesn’t list a canonical URL\nin the page.  A single message and the whole-thread link does contain the same\ncontent, and neither are canonical so we might be incurring penalties from\nthat.  Also, the postgr.es/m/ shortener makes content available via two URLs,\nwithout a canonical URL specified.But robots.txt blocks the whole-thread view (and this is the reason for it).And postgr.es/m/ does not actually make the content available there, it redirects.So I don't think those should actually have an effect?\nThat being said, since we haven’t changed anything, and DuckDuckGo happily\nindex the mailinglist posts, this smells a lot more like a policy change than a\ntechnical change if my experience with Google SEO is anything to go by.  The\nWebmaster Tools Search Console can quite often give insights as to why a page\nis missing, that’s probably a better place to start then second guessing Google\nSEO.  AFAICR, using that requires proving that one owns the site/domain, but\ndoesn’t require adding any google trackers or similar things.I've tried but failed to get any relevant data out of it. It does clearly show large amounts of URLs blocked because they are in /flat/ or /raw/, but nothing at all about the regular messages. --  Magnus Hagander Me: https://www.hagander.net/ Work: https://www.redpill-linpro.com/", "msg_date": "Fri, 30 Aug 2019 12:08:28 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "> On 30 Aug 2019, at 12:08, Magnus Hagander <magnus@hagander.net> wrote:\n> On Fri, Aug 30, 2019 at 11:40 AM Daniel Gustafsson <daniel@yesql.se <mailto:daniel@yesql.se>> wrote:\n> > On 29 Aug 2019, at 16:55, Andres Freund <andres@anarazel.de <mailto:andres@anarazel.de>> wrote:\n> > On 2019-08-29 09:32:35 -0400, Alvaro Herrera wrote:\n> >> On 2019-Aug-29, Magnus Hagander wrote:\n> >> \n> >>> Maybe Google used to load the pages under /list/ and crawl them for links\n> >>> but just not include the actual pages in the index or something\n> >>> \n> >>> I wonder if we can inject these into Google using a sitemap. I think that\n> >>> should work -- will need some investigation on exactly how to do it, as\n> >>> sitemaps also have individual restrictions on the number of urls per file,\n> >>> and we do have quite a few messages.\n> >>> \n> >>>> Why is that /list/ exclusion there in the first place?\n> >>> \n> >>> Because there are basically infinite number of pages in that space, due to\n> >>> the fact that you can pick an arbitrary point in time to view from.\n> >> \n> >> Maybe we can create a new page that's specifically to be used by\n> >> crawlers, that lists all emails, each only once. Say (unimaginatively)\n> >> /list_crawlers/2019-08/ containing links to all emails of all public\n> >> lists occurring during August 2019.\n> > \n> > Hm. Weren't there occasionally downranking rules for pages that were\n> > clearly aimed just at search engines?\n> \n> I think that’s mainly been for pages which are clearly keyword spamming, I\n> doubt our content would get caught there. The sitemap, as proposed upthread,\n> is the solution to this however and is also the recommended way from Google for\n> sites with lots of content.\n> \n> Google does however explicitly downrank duplicated/similar content, or content\n> which can be reached via multiple URLs and which doesn’t list a canonical URL\n> in the page. A single message and the whole-thread link does contain the same\n> content, and neither are canonical so we might be incurring penalties from\n> that. Also, the postgr.es/m/ <http://postgr.es/m/> shortener makes content available via two URLs,\n> without a canonical URL specified.\n> \n> But robots.txt blocks the whole-thread view (and this is the reason for it).\n\nMaybe that’s part of the explanation, since Google no longer wants sites to use\nrobots.txt for restricting crawlers on what to index (contrary to much indexing\nadvice which is vague at best they actually say so explicitly)? Being in\nrobots.txt doesn’t restrict the page from being indexed, if it is linked to\nfrom somewhere else with enough context etc (for example if a thread is\nreproduced on a forum with a link to /message-id/raw). Their recommended way\nis to mark the page with noindex:\n\n\t<meta name=“robots” content=“noindex” />\n\n> And postgr.es/m/ <http://postgr.es/m/> does not actually make the content available there, it redirects.\n\nRight, but a 301 redirect is considered by Google as deprecating the old page,\nwhich may or may not throw the indexer off since we continue to use\npostgr.es/m/ without a canonicalization?\n\n> So I don't think those should actually have an effect?\n\nThat could very well be true, as with most things SEO it’s all a guessing game.\n\n> That being said, since we haven’t changed anything, and DuckDuckGo happily\n> index the mailinglist posts, this smells a lot more like a policy change than a\n> technical change if my experience with Google SEO is anything to go by. The\n> Webmaster Tools Search Console can quite often give insights as to why a page\n> is missing, that’s probably a better place to start then second guessing Google\n> SEO. AFAICR, using that requires proving that one owns the site/domain, but\n> doesn’t require adding any google trackers or similar things.\n> \n> I've tried but failed to get any relevant data out of it. It does clearly show large amounts of URLs blocked because they are in /flat/ or /raw/, but nothing at all about the regular messages. \n\nThat’s disappointing, I’ve gotten quite good advice there in past.\n\ncheers ./daniel\n\n", "msg_date": "Fri, 30 Aug 2019 13:09:14 +0200", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" }, { "msg_contents": "Hi,\n\nThis got brought up again on in a twitter discussion, see\nhttps://twitter.com/AndresFreundTec/status/1403418002951794688\n\nOn 2019-08-29 07:50:13 -0700, Andres Freund wrote:\n> > > Why is that /list/ exclusion there in the first place?\n> \n> > Because there are basically infinite number of pages in that space, due to\n> > the fact that you can pick an arbitrary point in time to view from.\n> \n> You mean because of the per-day links, that aren't really per-day? I\n> think the number of links due to that would still be manageable traffic\n> wise? Or are they that expensive to compute? Perhaps we could make the\n> \"jump to day\" links smarter in some way? Perhaps by not including\n> content for the following days in the per-day pages?\n\nI still don't understand why all of /list/ is in robots.txt. I\nunderstand why we don't necessarily want to index /list/.../since/...,\nbut prohibiting all of /list/ seems like a extremely poorly aimed\nbig hammer.\n\nCan't we use wildcards to at least allow everything but the /since/\nlinks? E.g. Disallow: /list/*/since/*. Is it because we're some less\ncommon crawler doesn't implement wildcards at all?\n\nOr slap rel=nofollow on links / add a meta tag preventing /since/ pages\nfrom being indexed.\n\nYes, that'd not be perfect for the bigger lists, because there's no\n\"direct\" way to get from the month's archive to all the month's emails\nwhen paginated. But there's still the next/prev links. And it'd be much\nbetter than what we have right now.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Sat, 12 Jun 2021 12:05:42 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: no mailing list hits in google" } ]
[ { "msg_contents": "Hi,\n\nThere's been a lot of complaints over the years about how annoying it is\nto keep the out/read/copy/equalfuncs.c functions in sync with the actual\nunderlying structs.\n\nThere've been various calls for automating their generation, but no\nactual patches that I am aware of.\n\nThere also recently has been discussion about generating more efficient\nmemory layout for node trees that we know are read only (e.g. plan trees\ninside the plancache), and about copying such trees more efficiently\n(e.g. by having one big allocation, and then just adjusting pointers).\n\n\nOne way to approach this problem would be to to parse the type\ndefinitions, and directly generate code for the various functions. But\nthat does mean that such a code-generator needs to be expanded for each\nsuch functions.\n\nAn alternative approach is to have a parser of the node definitions that\ndoesn't generate code directly, but instead generates metadata. And then\nuse that metadata to write node aware functions. This seems more\npromising to me.\n\nIn the attached, *very experimental WIP*, patch I've played around with\nthis approach. I have written a small C program that uses libclang\n(more on that later) to parse relevant headers, and generate metadata\nabout node types.\n\nCurrently the generated metadata roughly looks like this:\n\n#define TYPE_CAT_SCALAR (1 << 0) // FIXME: this isn't well named rn\n#define TYPE_CAT_POINTER (1 << 1)\n#define TYPE_CAT_UNION (1 << 2) // FIXME: unused\n#define TYPE_CAT_INCOMPLETE (1 << 3)\n\n#define KNOWN_TYPE_UNKNOWN 0\n#define KNOWN_TYPE_STRING 1\n#define KNOWN_TYPE_INT 2\n#define KNOWN_TYPE_NODE 3\n#define KNOWN_TYPE_BITMAPSET 4\n\ntypedef struct NodeTypeInfo\n{\n\t/* FIXME: intern me */\n\tconst char *structname;\n\tint16 nelems;\n\tint16 start_at;\n\tint16 size;\n} NodeTypeInfo;\n\ntypedef struct NodeTypeComponents\n{\n\t/* FIXME: intern me */\n\tconst char *fieldname;\n\t/* FIXME: intern me */\n\tconst char *fieldtype;\n\tint16 offset;\n\tint16 size;\n\tint16 flags;\n\tint16 node_type_id;\n\tint16 known_type_id;\n} NodeTypeComponents;\n\nNodeTypeInfo node_type_info[] = {\n\t{0},\n\t{.structname = \"IndexInfo\", .nelems = 22, .start_at = 2128, .size = sizeof(IndexInfo)},\n...\n\t{.structname = \"Append\", .nelems = 4, .start_at = 1878, .size = sizeof(Append)},\n ...\n\nNodeTypeComponents node_type_components[] = {\n...\n\t{.fieldname = \"plan\", .fieldtype = \"struct Plan\", .offset = offsetof(struct Append, plan), .size = sizeof(struct Plan), .flags = TYPE_CAT_SCALAR, .node_type_id = 9, .known_type_id = KNOWN_TYPE_UNKNOWN},\n\t{.fieldname = \"appendplans\", .fieldtype = \"struct List *\", .offset = offsetof(struct Append, appendplans), .size = sizeof(struct List *), .flags = TYPE_CAT_POINTER, .node_type_id = 223, .known_type_id = KNOWN_TYPE_UNKNOWN},\n\t{.fieldname = \"first_partial_plan\", .fieldtype = \"int\", .offset = offsetof(struct Append, first_partial_plan), .size = sizeof(int), .flags = TYPE_CAT_SCALAR, .node_type_id = -1, .known_type_id = KNOWN_TYPE_UNKNOWN},\n\t{.fieldname = \"part_prune_info\", .fieldtype = \"struct PartitionPruneInfo *\", .offset = offsetof(struct Append, part_prune_info), .size = sizeof(struct PartitionPruneInfo *), .flags = TYPE_CAT_POINTER, .node_type_id = 53, .known_type_id = KNOWN_TYPE_UNKNOWN},\n...\n\ni.e. each node type is listed in node_type_info, indexed by the NodeTag\nvalue. The fields building up the node are defined in\nnode_type_components. By including the size for Node structs, and\ncomponents, and by including the offset for components, we can write\ngeneric routines accessing node trees.\n\n\nIn the attached I used this metadata to write a function that can\ncompute the amount of memory a node tree needs (without currently\nconsidering memory allocator overhead). The function for doing so has a\npretty limited amount of type awareness - it needs to know about\nstrings, the various list types, value nodes and Bitmapset.\n\nI'm fairly sure this metadata can also be used to write the other\ncurrently existing node functions.\n\nI *suspect* that it'll be quite OK performancewise, compared to bespoke\ncode, but I have *NOT* measured that.\n\n\nThe one set of fields this currently can not deal with is the various\narrays that we directly reference from nodes. For e.g.\n\ntypedef struct Sort\n{\n\tPlan\t\tplan;\n\tint\t\t\tnumCols;\t\t/* number of sort-key columns */\n\tAttrNumber *sortColIdx;\t\t/* their indexes in the target list */\n\tOid\t\t *sortOperators;\t/* OIDs of operators to sort them by */\n\tOid\t\t *collations;\t\t/* OIDs of collations */\n\tbool\t *nullsFirst;\t\t/* NULLS FIRST/LAST directions */\n} Sort;\n\nthe generic code has no way of knowing that sortColIdx, sortOperators,\ncollations, nullsFirst are all numCols long arrays.\n\nI can see various ways of dealing with that:\n\n1) We could convert them all to lists, now that we have fast arbitrary\n access. But that'd add a lot of indirection / separate allocations.\n\n2) We could add annotations to the sourcecode, to declare that\n association. That's probably not trivial, but wouldn't be that hard -\n one disadvantage is that we probably couldn't use that declaration\n for automated asserts etc.\n\n3) We could introduce a few macros to create array type that include the\n length of the members. That'd duplicate the lenght for each of those\n arrays, but I have a bit of a hard time believing that that's a\n meaningful enough overhead.\n\n I'm thinking of a macro that'd be used like\n ARRAY_FIELD(AttrNumber) *sortColIdx;\n that'd generate code like\n struct\n {\n size_t nmembers;\n AttrNumber members[FLEXIBLE_ARRAY_MEMBER];\n } *sortColIdx;\n\n plus a set of macros (or perhaps inline functions + macros) to access\n them.\n\n\nWith any of these we could add enough metadata for node type members to\nbe able to handle such arrays in a generic manner, rather than having to\nwrite code for each of them.\n\n\nWith regards to using libclang for the parsing: I chose that because it\nseemed the easiest to experiment with, compared to annotating all the\nstructs with enough metadata to be able to easily parse them from a perl\nscript. The node definitions are after all distributed over quite a few\nheaders.\n\nI think it might even be the correct way forward, over inventing our own\nmini-languages and writing ad-hoc parsers for those. It sure is easier\nto understand plain C code, compared to having to understand various\nembeded mini-languages consisting out of macros.\n\nThe obvious drawback is that it'd require more people to install\nlibclang - a significant imposition. I think it might be OK if we only\nrequired it to be installed when changing node types (although it's not\nnecessarily trivial how to detect that node types haven't changed, if we\nwanted to allow other code changes in the relevant headers), and stored\nthe generated code in the repository.\n\nAlternatively we could annotate the code enough to be able to write our\nown parser, or use some other C parser.\n\n\nI don't really want to invest significantly more time into this without\nfirst debating the general idea.\n\n\nThe attached patch really just is a fairly minimal prototype. It does\nnot:\n- properly integrate into the buildsystem, to automatically re-generate\n the node information when necessary - instead one has to\n \"make -C src/backend/catalog gennodes-run\"\n- solve the full problem (see discussion of referenced arrays above)\n- actually use the metadata in a useful manner (there just is a function\n that estimates node tree sizes, which is used for parse/plan trees)\n- have clean code\n\n\nOne interesting - but less important - bit is that the patch currently\nhas the declared node type id available for node members, e.g:\n\ntypedef struct FieldStore\n{\n\tExpr\t\txpr;\n\tExpr\t *arg;\t\t\t/* input tuple value */\n\tList\t *newvals;\t\t/* new value(s) for field(s) */\n\tList\t *fieldnums;\t\t/* integer list of field attnums */\n\tOid\t\t\tresulttype;\t\t/* type of result (same as type of arg) */\n\t/* Like RowExpr, we deliberately omit a typmod and collation here */\n} FieldStore;\n\nbut we cannot actually rely on arg actually pointing to a node of type\nExpr* - it'll always point to a \"subclass\". Obviously we can handle\nthat by dispatching using nodeTag(arg), but it'd be more efficient if we\ndidn't need that. And we also loose some error checking due to that.\n\nI wonder if we could collect enough metadata to determine which\npotential subclasses a node type has. And then dispatch more efficiently\nwhen only one, and assert that it's a legal subclass for the other\ncases.\n\nGreetings,\n\nAndres Freund", "msg_date": "Wed, 28 Aug 2019 16:41:36 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "WIP: Generic functions for Node types using generated metadata" }, { "msg_contents": "Hello Andres,\n\nJust my 0.02 €:\n\n> There's been a lot of complaints over the years about how annoying it is\n> to keep the out/read/copy/equalfuncs.c functions in sync with the actual\n> underlying structs.\n>\n> There've been various calls for automating their generation, but no\n> actual patches that I am aware of.\n\nI started something a while back, AFAICR after spending stupid time \nlooking for a stupid missing field copy or whatever. I wrote a (simple) \nperl script deriving all (most) node utility functions for the header \nfiles.\n\nI gave up as the idea did not gather much momentum from committers, so I \nassumed the effort would be rejected in the end. AFAICR the feedback \nspirit was something like \"node definition do not change often, we can \nmanage it by hand\".\n\n> There also recently has been discussion about generating more efficient\n> memory layout for node trees that we know are read only (e.g. plan trees\n> inside the plancache), and about copying such trees more efficiently\n> (e.g. by having one big allocation, and then just adjusting pointers).\n\nIf pointers are relative to the start, it could be just indexes that do \nnot need much adjusting.\n\n> One way to approach this problem would be to to parse the type \n> definitions, and directly generate code for the various functions. But \n> that does mean that such a code-generator needs to be expanded for each \n> such functions.\n\nNo big deal for the effort I made. The issue was more dealing with \nexceptions (eg \"we do not serialize this field because it is not used for \nsome reason\") and understanding some implicit assumptions in the struct \ndeclarations.\n\n> An alternative approach is to have a parser of the node definitions that\n> doesn't generate code directly, but instead generates metadata. And then\n> use that metadata to write node aware functions. This seems more\n> promising to me.\n\nHmmm. The approach we had in an (old) research project was to write the \nmeta data, and derive all struct & utility functions from these. It is \nsimpler this way because you save parsing some C, and it can be made \nlanguage agnostic (i.e. serializing the data structure from a language and \nreading its value from another).\n\n> I'm fairly sure this metadata can also be used to write the other\n> currently existing node functions.\n\nBeware of strange exceptions…\n\n> With regards to using libclang for the parsing: I chose that because it\n> seemed the easiest to experiment with, compared to annotating all the\n> structs with enough metadata to be able to easily parse them from a perl\n> script.\n\nI did not find this an issue when I tried, because the annotation needed \nis basically the type name of the field.\n\n> The node definitions are after all distributed over quite a few headers.\n\nYep.\n\n> I think it might even be the correct way forward, over inventing our own\n> mini-languages and writing ad-hoc parsers for those. It sure is easier\n> to understand plain C code, compared to having to understand various\n> embeded mini-languages consisting out of macros.\n\nDunno.\n\n> The obvious drawback is that it'd require more people to install \n> libclang - a significant imposition.\n\nIndeed. A perl-only dependence would be much simpler that relying on a \nparticular library from a particular compiler to compile postgres, \npossibly with an unrelated compiler.\n\n> Alternatively we could annotate the code enough to be able to write our\n> own parser, or use some other C parser.\n\nIf you can dictate some conventions, eg one line/one field, simple perl \nregexpr would work well I think, you would not need a parser per se.\n\n> I don't really want to invest significantly more time into this without\n> first debating the general idea.\n\nThat what I did, and I quitted quickly:-)\n\nOn the general idea, I'm 100% convinced that stupid utility functions \nshould be either generic or generated, not maintained by hand.\n\n-- \nFabien.", "msg_date": "Fri, 30 Aug 2019 14:35:34 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: WIP: Generic functions for Node types using generated metadata" }, { "msg_contents": "Hallo Andres,\n\n>> There've been various calls for automating their generation, but no\n>> actual patches that I am aware of.\n>\n> I started something a while back\n\nI have found this thread:\n\nhttps://www.postgresql.org/message-id/flat/E1cq93r-0004ey-Mp%40gemulon.postgresql.org\n\nIt seems that comments from committers discouraged me to go on… :-) For \ninstance Robert wanted a \"checker\", which is basically harder than a \ngenerator because you have to parse both sides and then compare.\n\nBasically there was no consensus at the time (March 2017), so I gave up. \nIt seems that I even distroyed the branch I was working on, so the no \ndoubt magnificent perl script I wrote is also lost.\n\n-- \nFabien.", "msg_date": "Fri, 30 Aug 2019 15:02:43 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: WIP: Generic functions for Node types using generated metadata" }, { "msg_contents": "Hi,\n\nOn 2019-08-28 16:41:36 -0700, Andres Freund wrote:\n> There's been a lot of complaints over the years about how annoying it is\n> to keep the out/read/copy/equalfuncs.c functions in sync with the actual\n> underlying structs.\n>\n> There've been various calls for automating their generation, but no\n> actual patches that I am aware of.\n>\n> There also recently has been discussion about generating more efficient\n> memory layout for node trees that we know are read only (e.g. plan trees\n> inside the plancache), and about copying such trees more efficiently\n> (e.g. by having one big allocation, and then just adjusting pointers).\n>\n>\n> One way to approach this problem would be to to parse the type\n> definitions, and directly generate code for the various functions. But\n> that does mean that such a code-generator needs to be expanded for each\n> such functions.\n>\n> An alternative approach is to have a parser of the node definitions that\n> doesn't generate code directly, but instead generates metadata. And then\n> use that metadata to write node aware functions. This seems more\n> promising to me.\n>\n> In the attached, *very experimental WIP*, patch I've played around with\n> this approach. I have written a small C program that uses libclang\n> (more on that later) to parse relevant headers, and generate metadata\n> about node types.\n>\n> [more detailed explanation of the approach]\n\nAttached is a patchset that implements this approach. At the end the patchset\nentirely replaces\nsrc/backend/nodes/{copyfuncs.c,equalfuncs.c,outfuncs.c,readfuncs.c, read.c}\nwith relatively generic code using the metadata mentioned above.\n\nTo show how nice this is, here's the diffstat for the most relevant\ncommits in the series:\n\n1) WIP: Introduce compile-time node type metadata collection & reimplement node funcs.\n 18 files changed, 3192 insertions(+), 30 deletions(-)\n\n2) WIP: Add generated node metadata.\n 1 file changed, 7279 insertions(+)\n\n3) WIP: Remove manually maintained out/read/copy/equalfuncs code.\n 11 files changed, 49 insertions(+), 17277 deletions(-)\n\nEven including the full auto-generated metadata, it's still a quite\nsubstantial win.\n\n\nUsing that metadata one can do stuff that wasn't feasible before. As an\nexample, the last patch in the series implements a version of\ncopyObject() (badly named copyObjectRo()) that copies an object into a\nsingle allocation. That's quite worthwhile memory-usage wise:\n\n PREPARE foo AS SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, c.relhastriggers, c.relrowsecurity, c.relforcerowsecurity, false AS relhasoids, c.relispartition, pg_catalog.array_to_string(c.reloptions || array(select 'toast.' || x from pg_catalog.unnest(tc.reloptions) x), ', '), c.reltablespace, CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, c.relpersistence, c.relreplident, am.amname FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid) LEFT JOIN pg_catalog.pg_am am ON (c.relam = am.oid) WHERE c.oid = '1259';\n EXECUTE foo ;\n\n With single-allocation:\n CachedPlan: 24504 total in 2 blocks; 664 free (0 chunks); 23840 used\n Grand total: 24504 bytes in 2 blocks; 664 free (0 chunks); 23840 used\n\n Default:\n CachedPlan: 65536 total in 7 blocks; 16016 free (0 chunks); 49520 used\n Grand total: 65536 bytes in 7 blocks; 16016 free (0 chunks); 49520 used\n\nAnd with a bit more elbow grease we could expand that logic so that\ncopyObject from such a \"block allocated\" node tree would already know\nhow much memory to allocate, memcpy() the source over to the target, and\njust adjust the pointer offsets.\n\n\nWe could also use this to have a version of IsA() that supported our\nform of inheritance. In a quick hack I wrote a function that computes a\nper-node-type bitmap indicating whether other nodetypes are subtypes of\nthat node. While there's still a bug (it doesn't correctly handle node\ntypes that are just typedefed to each other), it already allows to\nproduce:\n\ttype T_JoinState has 3 subtypes\n\t\tchild: T_NestLoopState\n\t\tchild: T_MergeJoinState\n\t\tchild: T_HashJoinState\n\ttype T_Expr has 44 subtypes\n\t\tchild: T_Var\n\t\tchild: T_Const\n\t\tchild: T_Param\n\t\tchild: T_Aggref\n\t\tchild: T_GroupingFunc\n\t\tchild: T_WindowFunc\n\t\tchild: T_SubscriptingRef\n\t\tchild: T_FuncExpr\n\t\tchild: T_NamedArgExpr\n\nIt seems quite useful to be able to assert such relationsship.\n\n\n> I *suspect* that it'll be quite OK performancewise, compared to bespoke\n> code, but I have *NOT* measured that.\n\nI now have. When testing with COPY_PARSE_PLAN_TREES,\nWRITE_READ_PARSE_PLAN_TREES the \"generic\" code is a bit slower, but not\nmuch (< %5).\n\nTo some degree that's possibly inherent, but I think the bigger issue\nright now is that the new code does more appendStringInfo() calls,\nbecause it outputs the field name separately. Also, the slightly\nexpanded node format adds a few more tokens, which needs to be parsed\n(pg_strtok (or rather its replacement) is the slowest bit.\n\nI think with a bit of optimization we can get that back, and the\nfacilities allow us to make much bigger wins. So I think this is quite\ngood.\n\n\n> With regards to using libclang for the parsing: I chose that because it\n> seemed the easiest to experiment with, compared to annotating all the\n> structs with enough metadata to be able to easily parse them from a perl\n> script. The node definitions are after all distributed over quite a few\n> headers.\n>\n> I think it might even be the correct way forward, over inventing our own\n> mini-languages and writing ad-hoc parsers for those. It sure is easier\n> to understand plain C code, compared to having to understand various\n> embeded mini-languages consisting out of macros.\n>\n> The obvious drawback is that it'd require more people to install\n> libclang - a significant imposition. I think it might be OK if we only\n> required it to be installed when changing node types (although it's not\n> necessarily trivial how to detect that node types haven't changed, if we\n> wanted to allow other code changes in the relevant headers), and stored\n> the generated code in the repository.\n>\n> Alternatively we could annotate the code enough to be able to write our\n> own parser, or use some other C parser.\n\nStill using libclang. The .c file containing the metadata is now part of\nthe source tree (i.e. would be checked in), and would only need to be\nregenerated when one of the relevant headers change (but obviously such\na change could be unimportant).\n\n\n> The one set of fields this currently can not deal with is the various\n> arrays that we directly reference from nodes. For e.g.\n>\n> typedef struct Sort\n> {\n> \tPlan\t\tplan;\n> \tint\t\t\tnumCols;\t\t/* number of sort-key columns */\n> \tAttrNumber *sortColIdx;\t\t/* their indexes in the target list */\n> \tOid\t\t *sortOperators;\t/* OIDs of operators to sort them by */\n> \tOid\t\t *collations;\t\t/* OIDs of collations */\n> \tbool\t *nullsFirst;\t\t/* NULLS FIRST/LAST directions */\n> } Sort;\n>\n> the generic code has no way of knowing that sortColIdx, sortOperators,\n> collations, nullsFirst are all numCols long arrays.\n>\n> I can see various ways of dealing with that:\n>\n> 1) We could convert them all to lists, now that we have fast arbitrary\n> access. But that'd add a lot of indirection / separate allocations.\n>\n> 2) We could add annotations to the sourcecode, to declare that\n> association. That's probably not trivial, but wouldn't be that hard -\n> one disadvantage is that we probably couldn't use that declaration\n> for automated asserts etc.\n>\n> 3) We could introduce a few macros to create array type that include the\n> length of the members. That'd duplicate the lenght for each of those\n> arrays, but I have a bit of a hard time believing that that's a\n> meaningful enough overhead.\n>\n> I'm thinking of a macro that'd be used like\n> ARRAY_FIELD(AttrNumber) *sortColIdx;\n> that'd generate code like\n> struct\n> {\n> size_t nmembers;\n> AttrNumber members[FLEXIBLE_ARRAY_MEMBER];\n> } *sortColIdx;\n>\n> plus a set of macros (or perhaps inline functions + macros) to access\n> them.\n\nI've implemented 3), which seems to work well. But it's a fair bit of\nmacro magic.\n\nBasically, one can define a type to be array supported, by once using\nPGARR_DEFINE_TYPE(element_type); which defines a struct type that has a\nmembers array of type element_type. After that variables of the array\ntype can be defined using PGARR(element_type) (as members in a struct,\nvariables, ...).\n\nMacros like pgarr_size(arr), pgarr_empty(arr), pgarr_at(arr, at) can be\nused to query (and in the last case also modify) the array.\n\npgarr_append(element_type, arr, newel) can be used to append to the\narray. Unfortunately I haven't figured out a satisfying a way to write\npgarr_append() without specifying the element_type. Either there's\nmultiple-evaluation of any of the types (for checking whether the\ncapacity needs to be increased), only `newel`s that can have their\naddress taken are supported (so it can be passed to a helper function),\nor compiler specific magic has to be used (__typeof__ solves this\nnicely).\n\nThe array can be allocated (using pgarr_alloc_ro(type, capacity)) so\nthat a certain number of elements fit inline.\n\n\nBoring stuff aside, there's a few more parts of the patchseries:\n\n1) Move int->string routines to src/common, and expand.\n\n The current pg_*toa routines are quite incomplete (no unsigned\n support), are terribly named, and require unnecessary strlen() calls\n to recompute the length of the number, even though the routines\n already know them.\n\n Fix all of that, and move to src/common/string.c for good measure.\n\n\n2) WIP: Move stringinfo to common/\n\n The metadata collection program needed a string buffer. PQExpBuffer\n is weird, and has less functionality.\n\n\n3) WIP: Improve and expand stringinfo.[ch].\n\n Expands the set of functions exposed, to allow appending various\n numeric types etc. Also improve efficiency by moving code to inline\n functions - that's beneficial because the size is often known, which\n can make the copy faster.\n\n\nThe code is also available at\nhttps://github.com/anarazel/postgres/tree/header\nhttps://git.postgresql.org/gitweb/?p=users/andresfreund/postgres.git;a=summary\n(in the header branch).\n\n\nWhile working on this I evolved the node string format a bit:\n\n1) Node types start with the their \"normal\" name, rather than\n uppercase. There seems little point in having such a divergence.\n\n2) The node type is followed by the node-type id. That allows to more\n quickly locate the corresponding node metadata (array and one name\n recheck, rather than a binary search). I.e. the node starts with\n \"{Scan 18 \" rather than \"{SCAN \" as before.\n\n3) Nodes that contain other nodes as sub-types \"inline\", still emit {}\n for the subtype. There's no functional need for this, but I found the\n output otherwise much harder to read. E.g. for mergejoin we'd have\n something like\n\n {MergeJoin 37 :join {Join 35 :plan {Plan ...} :jointype JOIN_INNER ...} :skip_mark_restore true ...}\n\n4) As seen in the above example, enums are decoded to their string\n values. I found that makes the output easier to read. Again, not\n functionally required.\n\n5) Value nodes aren't emitted without a {Value ...} anymore. I changed\n this when I expanded the WRITE/READ tests, and encountered failures\n because the old encoding is not entirely rountrip safe\n (e.g. -INT32_MIN will be parsed as a float at raw parse time, but\n after write/read, it'll be parsed as an integer). While that could be\n fixed in other ways (e.g. by emitting a trailing . for all floats), I\n also found it to be clearer this way - Value nodes are otherwise\n undistinguishable from raw strings, raw numbers etc, which is not\n great.\n\nIt'd also be easier to now just change the node format to something else.\n\n\nComments?\n\n\nTodo / Questions:\n- lots of cleanup\n- better error checking when looking up node definitions\n- better dealing with node types that are just typedef'ed to another type\n- don't use full tokenizer in all places, too expensive\n\n\nGreetings,\n\nAndres Freund", "msg_date": "Thu, 19 Sep 2019 22:18:57 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: WIP: Generic functions for Node types using generated metadata" }, { "msg_contents": "Hi,\n\nOn 2019-09-19 22:18:57 -0700, Andres Freund wrote:\n> While working on this I evolved the node string format a bit:\n> \n> 1) Node types start with the their \"normal\" name, rather than\n> uppercase. There seems little point in having such a divergence.\n> \n> 2) The node type is followed by the node-type id. That allows to more\n> quickly locate the corresponding node metadata (array and one name\n> recheck, rather than a binary search). I.e. the node starts with\n> \"{Scan 18 \" rather than \"{SCAN \" as before.\n> \n> 3) Nodes that contain other nodes as sub-types \"inline\", still emit {}\n> for the subtype. There's no functional need for this, but I found the\n> output otherwise much harder to read. E.g. for mergejoin we'd have\n> something like\n> \n> {MergeJoin 37 :join {Join 35 :plan {Plan ...} :jointype JOIN_INNER ...} :skip_mark_restore true ...}\n> \n> 4) As seen in the above example, enums are decoded to their string\n> values. I found that makes the output easier to read. Again, not\n> functionally required.\n> \n> 5) Value nodes aren't emitted without a {Value ...} anymore. I changed\n> this when I expanded the WRITE/READ tests, and encountered failures\n> because the old encoding is not entirely rountrip safe\n> (e.g. -INT32_MIN will be parsed as a float at raw parse time, but\n> after write/read, it'll be parsed as an integer). While that could be\n> fixed in other ways (e.g. by emitting a trailing . for all floats), I\n> also found it to be clearer this way - Value nodes are otherwise\n> undistinguishable from raw strings, raw numbers etc, which is not\n> great.\n> \n> It'd also be easier to now just change the node format to something else.\n\nE.g. to just use json. Which'd certainly be a lot easier to delve into,\ngiven the amount of tooling (both on the pg SQL level, and for\ncommandline / editors / etc). I don't think it'd be any less\nefficient. There'd be a few more = signs, but the lexer is smarter /\nfaster than the one currently in use for the outfuncs format. And we'd\njust reuse pg_parse_json rather than having a dedicated parser.\n\n- Andres\n\n\n", "msg_date": "Fri, 20 Sep 2019 15:43:54 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: WIP: Generic functions for Node types using generated metadata" }, { "msg_contents": "On Fri, Sep 20, 2019 at 03:43:54PM -0700, Andres Freund wrote:\n> Hi,\n> \n> On 2019-09-19 22:18:57 -0700, Andres Freund wrote:\n> > While working on this I evolved the node string format a bit:\n> > \n> > 1) Node types start with the their \"normal\" name, rather than\n> > uppercase. There seems little point in having such a divergence.\n> > \n> > 2) The node type is followed by the node-type id. That allows to more\n> > quickly locate the corresponding node metadata (array and one name\n> > recheck, rather than a binary search). I.e. the node starts with\n> > \"{Scan 18 \" rather than \"{SCAN \" as before.\n> > \n> > 3) Nodes that contain other nodes as sub-types \"inline\", still emit {}\n> > for the subtype. There's no functional need for this, but I found the\n> > output otherwise much harder to read. E.g. for mergejoin we'd have\n> > something like\n> > \n> > {MergeJoin 37 :join {Join 35 :plan {Plan ...} :jointype JOIN_INNER ...} :skip_mark_restore true ...}\n> > \n> > 4) As seen in the above example, enums are decoded to their string\n> > values. I found that makes the output easier to read. Again, not\n> > functionally required.\n> > \n> > 5) Value nodes aren't emitted without a {Value ...} anymore. I changed\n> > this when I expanded the WRITE/READ tests, and encountered failures\n> > because the old encoding is not entirely rountrip safe\n> > (e.g. -INT32_MIN will be parsed as a float at raw parse time, but\n> > after write/read, it'll be parsed as an integer). While that could be\n> > fixed in other ways (e.g. by emitting a trailing . for all floats), I\n> > also found it to be clearer this way - Value nodes are otherwise\n> > undistinguishable from raw strings, raw numbers etc, which is not\n> > great.\n> > \n> > It'd also be easier to now just change the node format to something else.\n> \n> E.g. to just use json.\n\n+many\n\nJSON's been around long enough to give some assurance that it's not\ngoing away, and it's pretty simple. \n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate\n\n\n", "msg_date": "Sat, 21 Sep 2019 11:15:27 +0200", "msg_from": "David Fetter <david@fetter.org>", "msg_from_op": false, "msg_subject": "Re: WIP: Generic functions for Node types using generated metadata" }, { "msg_contents": "On Fri, Aug 30, 2019 at 9:03 AM Fabien COELHO <coelho@cri.ensmp.fr> wrote:\n> I have found this thread:\n>\n> https://www.postgresql.org/message-id/flat/E1cq93r-0004ey-Mp%40gemulon.postgresql.org\n>\n> It seems that comments from committers discouraged me to go on… :-) For\n> instance Robert wanted a \"checker\", which is basically harder than a\n> generator because you have to parse both sides and then compare.\n\nWell, I don't think I intended to ask for something that was more\ndifficult than a full generator. I think it's more that I had the\nidea that a checker would be simpler. It's true that you'd have to\nparse both sides and compare. On the other hand, a checker can be\nincomplete -- only checking certain things -- whereas a generator has\nto work completely -- including all of the strange cases. So it seemed\nto me that a checker would allow for tolerating more in the way of\nexceptions than a generator. A generator also has to integrate\nproperly into the build system, which can be tricky.\n\nIt seems like the approach Andres is proposing here could work pretty\nwell. I think the biggest possible problem is that any semi-serious\ndeveloper will basically have to have LLVM installed. To build the\nsoftware, you wouldn't need LLVM unless you want to build with JIT\nsupport. But to modify the software, you'll need LLVM for any\nmodification that touches node definitions. I don't know how much of a\nnuisance that's likely to be for people, especially people developing\non less-mainstream platforms. One concern I have is about whether the\ncode that uses LLVM is likely to be dependent on specific LLVM\nversions. If I can just type something like 'yum/port/brew/apt-get\ninstall llvm' on any semi-modern platform and have that be good\nenough, it won't bother me much at all.\n\nOn the other hand, if I have to hand-compile it because RHEL version\n$X only ships older LLVM $Y (or ships unexpectedly-newer version $YY)\nthen that's going to be annoying. We already have the same annoyance\nwith autoconf; at some times, I've needed to have multiple versions\ninstalled locally to cater to all the branches. However, that's less\nof a problem than this would be, because (1) updating configure is a\nsubstantially less-common need than updating node definitions and (2)\nautoconf is a much smaller piece of software than libclang. It builds\nin about 1 second, which I bet LLVM does not.\n\nTo point to an analogous case, note that we pretty much have to adjust\na bunch of things every few years to be able to support new versions\nof Visual Studio, and until we do, it Just Doesn't Work. That stinks.\nIn contrast, new versions of gcc often cause new warnings, but those\nare easier to work around until such time as somebody gets around to\ncleaning them up. But most developers get to ignore Windows most of\nthe time, whereas if this breaks for somebody, they can't really work\nat all until they either work around it on their side or it gets fixed\nupstream. So it's a significant potential inconvenience.\n\nAs a benchmark, I'd propose this: if the LLVM interfaces that this new\ncode would use work in all versions of LLVM released in the last 3\nyears and there's no indication that they will change in the next\nrelease, then I'd feel pretty comfortable. If they've changed once,\nthat'd probably still be OK. If they've changed more than once,\nperhaps we should think about a Perl script under our own control as\nan alternative, so as to avoid having to keep adjusting the C code\nevery time LLVM whacks the interfaces around.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Wed, 2 Oct 2019 11:52:38 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP: Generic functions for Node types using generated metadata" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> It seems like the approach Andres is proposing here could work pretty\n> well. I think the biggest possible problem is that any semi-serious\n> developer will basically have to have LLVM installed. To build the\n> software, you wouldn't need LLVM unless you want to build with JIT\n> support. But to modify the software, you'll need LLVM for any\n> modification that touches node definitions. I don't know how much of a\n> nuisance that's likely to be for people, especially people developing\n> on less-mainstream platforms.\n\nI'm afraid that's going to be a deal-breaker for lots of people.\nIt's fine for prototyping the idea but we'll need to find another\nimplementation before we can move to commit.\n\n> One concern I have is about whether the\n> code that uses LLVM is likely to be dependent on specific LLVM\n> versions.\n\nYeah, that's one of the reasons it's a deal-breaker. We've been able to\ninsist that everybody touching configure use the same autoconf version,\nbut I don't think that could possibly fly for LLVM. But without that,\nall the derived files would change in random ways depending on who'd\ncommitted last. Even if it's only whitespace changes, that'd be a mess.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 02 Oct 2019 12:03:05 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: WIP: Generic functions for Node types using generated metadata" }, { "msg_contents": "On Wed, Oct 2, 2019 at 12:03 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> I'm afraid that's going to be a deal-breaker for lots of people.\n> It's fine for prototyping the idea but we'll need to find another\n> implementation before we can move to commit.\n\nWhy do you think it will be a deal-breaker for lots of people? I mean,\nif we get this to a point where it just requires installing some\nreasonably modern version of LLVM, I don't see why that's worse than\nhaving to do the same thing for say, Perl if you want to build\n--with-perl, or Python if you want to build --with-python, or bison or\nlex if you want to change the lexer and parser. One more build-time\ndependency shouldn't be a big deal, as long as we don't need a really\nspecific version. Or am I missing something?\n\n> > One concern I have is about whether the\n> > code that uses LLVM is likely to be dependent on specific LLVM\n> > versions.\n>\n> Yeah, that's one of the reasons it's a deal-breaker. We've been able to\n> insist that everybody touching configure use the same autoconf version,\n> but I don't think that could possibly fly for LLVM. But without that,\n> all the derived files would change in random ways depending on who'd\n> committed last. Even if it's only whitespace changes, that'd be a mess.\n\nI don't really see a reason why that would be an issue here. The code\nAndres wrote just uses LLVM to parse the structure definitions from\nour header files; the code generation stuff is hand-rolled and just\nprints out C. It's basically two big arrays, one of which is indexed\nby NodeTag and thus in a fixed order, and the other of which is an\narray of all structure members of all node types. The latter doesn't\nseem to be sorted in any terribly obvious way at the moment --\nstructure members are in order of occurrence within the corresponding\ndefinition, but the definitions themselves are not in any\nsuper-obvious order. That could presumably be fixed pretty easily,\nthough.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Wed, 2 Oct 2019 14:30:08 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP: Generic functions for Node types using generated metadata" }, { "msg_contents": "Robert Haas <robertmhaas@gmail.com> writes:\n> On Wed, Oct 2, 2019 at 12:03 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>> I'm afraid that's going to be a deal-breaker for lots of people.\n>> It's fine for prototyping the idea but we'll need to find another\n>> implementation before we can move to commit.\n\n> Why do you think it will be a deal-breaker for lots of people? I mean,\n> if we get this to a point where it just requires installing some\n> reasonably modern version of LLVM, I don't see why that's worse than\n> having to do the same thing for say, Perl if you want to build\n> --with-perl, or Python if you want to build --with-python, or bison or\n> lex if you want to change the lexer and parser. One more build-time\n> dependency shouldn't be a big deal, as long as we don't need a really\n> specific version. Or am I missing something?\n\nThink it's available/trivially installable on e.g. Windows? I'm not\nconvinced. In any case, our list of build requirements is depressingly\nlong already.\n\nThe existing expectation is that we make our build tools in Perl.\nI'm sure Andres doesn't want to write a C parser in Perl, but\npoking around suggests that there are multiple options already\navailable in CPAN. I'd much rather tell people \"oh, there's YA\nmodule you need to get from CPAN\" than \"figure out how to install\nversion XXX of LLVM\".\n\nThe other direction we could plausibly go in is to give up the\nassuption that parsenodes.h and friends are the authoritative\nsource of info, and instead declare all these structs in a little\nlanguage based on JSON or what-have-you, from which we generate\nparsenodes.h along with the backend/nodes/ files. I kind of\nsuspect that we'll be forced into that eventually anyway, because\none thing you are not going to get from LLVM or a pre-existing\nPerl C parser is anything but the lowest-common-denominator version\nof what's in the structs. I find it really hard to believe that\nwe won't need some semantic annotations in addition to the bare C\nstruct declarations. As an example: in some cases, pointer values\nin a Node struct point to arrays of length determined by a different\nfield in the struct. How do we tie those together without magic?\nI think there has to be an annotation marking the connection, and\nwe're not going to find that out from LLVM.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 02 Oct 2019 14:47:22 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: WIP: Generic functions for Node types using generated metadata" }, { "msg_contents": "Hi,\n\nOn 2019-10-02 14:30:08 -0400, Robert Haas wrote:\n> On Wed, Oct 2, 2019 at 12:03 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> > I'm afraid that's going to be a deal-breaker for lots of people.\n> > It's fine for prototyping the idea but we'll need to find another\n> > implementation before we can move to commit.\n> \n> Why do you think it will be a deal-breaker for lots of people? I mean,\n> if we get this to a point where it just requires installing some\n> reasonably modern version of LLVM, I don't see why that's worse than\n> having to do the same thing for say, Perl if you want to build\n> --with-perl, or Python if you want to build --with-python, or bison or\n> lex if you want to change the lexer and parser. One more build-time\n> dependency shouldn't be a big deal, as long as we don't need a really\n> specific version. Or am I missing something?\n\nIt shouldn't be that bad. On windows it can just be a binary to install:\nhttp://releases.llvm.org/download.html\nand newer versions of visual studio apparently even have GUI support for\ninstalling LLVM + clang + ...\n\n\n> > > One concern I have is about whether the\n> > > code that uses LLVM is likely to be dependent on specific LLVM\n> > > versions.\n\nFWIW, after one forward-compatible code change (a convenience function\ndidn't exist), one configure check (3.7 is older than what we support\nfor JIT), gennodes.c generated exactly the same output with 3.7 and\nthe tip-of-tree libclang that I used for development.\n\nI did not check further back, but 3.7 is plenty old.\n\nThe libclang API is part of the small set of \"stable\" APIs (which only\nexpose C) in LLVM, and the deprecation cycles are fairly long. That\nobviously doesn't protect against accidentally adding dependencies on a\nfeature only available in newer libclang versions, but I don't think\nwe'd be likely to change the feature set of the node generation program\nall that often, and we already have buildfarm animals using most llvm\nversions.\n\n\n> > Yeah, that's one of the reasons it's a deal-breaker. We've been able to\n> > insist that everybody touching configure use the same autoconf version,\n> > but I don't think that could possibly fly for LLVM. But without that,\n> > all the derived files would change in random ways depending on who'd\n> > committed last. Even if it's only whitespace changes, that'd be a mess.\n> \n> I don't really see a reason why that would be an issue here. The code\n> Andres wrote just uses LLVM to parse the structure definitions from\n> our header files; the code generation stuff is hand-rolled and just\n> prints out C. It's basically two big arrays, one of which is indexed\n> by NodeTag and thus in a fixed order, and the other of which is an\n> array of all structure members of all node types. The latter doesn't\n> seem to be sorted in any terribly obvious way at the moment --\n> structure members are in order of occurrence within the corresponding\n> definition, but the definitions themselves are not in any\n> super-obvious order. That could presumably be fixed pretty easily,\n> though.\n\nYea, I don't think there should be any big problem here. The order\nalready is \"consistent\" between versions etc, and only depends on the\ncontent of our include files. It's not quite right yet, because adding\na structure member currently can causes a too big diff in the generated\nmetadata file, due to renumbering of array indexes included in struct\ncontents of structs.\n\nFor the \"structure members\" array that is probably best solved by simply\nremoving it, and instead referencing the members directly from within\nthe node aray. That'll slightly increase the size (pointer, rather than\nuint16) of the \"node structs\" array, and make it harder to iterate over\nthe members of all structures (uh, why would you want that?), but is\notherwise easy.\n\nThe strings table, which is currently \"uniqued\", is suboptimal for\nsimilar reasons, and also performance (one more lookup in a separate\narray). I suspect the best way there too might be to just inline them,\ninstead of storing them de-duplicated.\n\nInlining the contents of those would also make it fairly easy to update\nthe file when doing small changes, if somebody doesn't want to/can't\ninstall libclang. We could probably include a few static asserts (once\nwe can have them on file scope) in the generated node file, to make\nmistakes more apparent.\n\nIf we decide that size is enough of an issue, we'd probably have to\noutput some macros to reduce the amount of visible\nre-numbering. So instead of something like\n\n\t{.name = 2201 /* Result */, .first_field_at = 1857, .num_fields = 2, .size = sizeof(Result)},\nwe'd have\n\t{.name = TI_STRINGOFF_RESULT, .first_field_at = TI_FIRST_FIELD_RESULT, .num_fields = 2, .size = sizeof(Result)},\n\n#define TI_STRINGOFF_RESULT (TI_STRINGOFF_RESCONSTQUAL + 1)\n#define TI_FIRST_FIELD_RESULT (TI_FIRST_FIELD_PLAN + 15)\n\n(with a bit more smarts for how to name the string #defines in a\nnon-conflicting way)\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 2 Oct 2019 13:21:46 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: WIP: Generic functions for Node types using generated metadata" }, { "msg_contents": "Hi,\n\nOn 2019-10-02 14:47:22 -0400, Tom Lane wrote:\n> Robert Haas <robertmhaas@gmail.com> writes:\n> > On Wed, Oct 2, 2019 at 12:03 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n> >> I'm afraid that's going to be a deal-breaker for lots of people.\n> >> It's fine for prototyping the idea but we'll need to find another\n> >> implementation before we can move to commit.\n>\n> > Why do you think it will be a deal-breaker for lots of people? I mean,\n> > if we get this to a point where it just requires installing some\n> > reasonably modern version of LLVM, I don't see why that's worse than\n> > having to do the same thing for say, Perl if you want to build\n> > --with-perl, or Python if you want to build --with-python, or bison or\n> > lex if you want to change the lexer and parser. One more build-time\n> > dependency shouldn't be a big deal, as long as we don't need a really\n> > specific version. Or am I missing something?\n>\n> Think it's available/trivially installable on e.g. Windows? I'm not\n> convinced. In any case, our list of build requirements is depressingly\n> long already.\n\nAs I wrote nearby, it's just a download of an installer away.\n\n\n> The existing expectation is that we make our build tools in Perl.\n> I'm sure Andres doesn't want to write a C parser in Perl, but\n> poking around suggests that there are multiple options already\n> available in CPAN. I'd much rather tell people \"oh, there's YA\n> module you need to get from CPAN\" than \"figure out how to install\n> version XXX of LLVM\".\n\nAs far as I can tell they're all at least one of\n1) written in C, so also have build requirements (obviously a shorter\n build time)\n2) not very good (including plenty unsupported C, not to speak of\n various optional extensions we use, not having preprocessor support,\n ...)\n3) unmaintained for many years.\n\nDid you find any convincing ones?\n\nWhereas libclang / llvm seem very unlikely to be unmaintained anytime\nsoon, given the still increasing adoption. It's also much more complete,\nthan any such perl module will realistically be.\n\n\n> The other direction we could plausibly go in is to give up the\n> assuption that parsenodes.h and friends are the authoritative\n> source of info, and instead declare all these structs in a little\n> language based on JSON or what-have-you, from which we generate\n> parsenodes.h along with the backend/nodes/ files.\n\nI think this should really work for more than just parsenodes (if you\nmean primnodes etc with \"friends\"), and even more than just node types\n(if you mean all the common node types with \"friends\"). For other Node\ntypes we already have to have pretty complete out/readfuncs support\n(e.g. to ship plans to parallel workers). and there's plenty other cases\nwhere we can use that information, e.g. as done in the prototype\nattached upthread:\n\nOn 2019-09-19 22:18:57 -0700, Andres Freund wrote:\n> Using that metadata one can do stuff that wasn't feasible before. As an\n> example, the last patch in the series implements a version of\n> copyObject() (badly named copyObjectRo()) that copies an object into a\n> single allocation. That's quite worthwhile memory-usage wise:\n>\n> PREPARE foo AS SELECT c.relchecks, c.relkind, c.relhasindex, c.relhasrules, c.relhastriggers, c.relrowsecurity, c.relforcerowsecurity, false AS relhasoids, c.relispartition, pg_catalog.array_to_string(c.reloptions || array(select 'toast.' || x from pg_catalog.unnest(tc.reloptions) x), ', '), c.reltablespace, CASE WHEN c.reloftype = 0 THEN '' ELSE c.reloftype::pg_catalog.regtype::pg_catalog.text END, c.relpersistence, c.relreplident, am.amname FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_class tc ON (c.reltoastrelid = tc.oid) LEFT JOIN pg_catalog.pg_am am ON (c.relam = am.oid) WHERE c.oid = '1259';\n> EXECUTE foo ;\n>\n> With single-allocation:\n> CachedPlan: 24504 total in 2 blocks; 664 free (0 chunks); 23840 used\n> Grand total: 24504 bytes in 2 blocks; 664 free (0 chunks); 23840 used\n>\n> Default:\n> CachedPlan: 65536 total in 7 blocks; 16016 free (0 chunks); 49520 used\n> Grand total: 65536 bytes in 7 blocks; 16016 free (0 chunks); 49520 used\n>\n> And with a bit more elbow grease we could expand that logic so that\n> copyObject from such a \"block allocated\" node tree would already know\n> how much memory to allocate, memcpy() the source over to the target, and\n> just adjust the pointer offsets.\n\n\nAnd I'm currently prototyping implementing the\nserialization/deserialization of UNDO records into a compressed format\nusing very similar information, to resolve the impasse that one side\n(among others, Robert) wants efficient and meaningful compression of\nundo records, while not believing a general compression library can\nprovide that, and the other side (most prominently Heikki), doesn't want\nto limit format of undo record that much.\n\n\n> I kind of suspect that we'll be forced into that eventually anyway,\n> because one thing you are not going to get from LLVM or a pre-existing\n> Perl C parser is anything but the lowest-common-denominator version of\n> what's in the structs. I find it really hard to believe that we won't\n> need some semantic annotations in addition to the bare C struct\n> declarations. As an example: in some cases, pointer values in a Node\n> struct point to arrays of length determined by a different field in\n> the struct. How do we tie those together without magic?\n\nI did solve that in the patchset posted here by replacing such \"bare\"\narrays with an array type that includes both the length, and the members\n(without loosing the type, using some macro magic). I think that\napproach has some promise, not just for this - I'd greatly appreciate\nthoughts on the part of the messages upthread (copied at the bottom, for\nconvenience).\n\nBut also:\n\n> I think there has to be an annotation marking the connection, and\n> we're not going to find that out from LLVM.\n\nlibclang does allow to access macro \"expansions\" and also parsing of\ncomments. So I don't think it'd be a problem to just recognize such\nconnections if we added a few macros for that purpose.\n\n\nOn 2019-09-19 22:18:57 -0700, Andres Freund wrote:\n> > The one set of fields this currently can not deal with is the various\n> > arrays that we directly reference from nodes. For e.g.\n> >\n> > typedef struct Sort\n> > {\n> > \tPlan\t\tplan;\n> > \tint\t\t\tnumCols;\t\t/* number of sort-key columns */\n> > \tAttrNumber *sortColIdx;\t\t/* their indexes in the target list */\n> > \tOid\t\t *sortOperators;\t/* OIDs of operators to sort them by */\n> > \tOid\t\t *collations;\t\t/* OIDs of collations */\n> > \tbool\t *nullsFirst;\t\t/* NULLS FIRST/LAST directions */\n> > } Sort;\n> >\n> > the generic code has no way of knowing that sortColIdx, sortOperators,\n> > collations, nullsFirst are all numCols long arrays.\n> >\n> > I can see various ways of dealing with that:\n> >\n> > 1) We could convert them all to lists, now that we have fast arbitrary\n> > access. But that'd add a lot of indirection / separate allocations.\n> >\n> > 2) We could add annotations to the sourcecode, to declare that\n> > association. That's probably not trivial, but wouldn't be that hard -\n> > one disadvantage is that we probably couldn't use that declaration\n> > for automated asserts etc.\n> >\n> > 3) We could introduce a few macros to create array type that include the\n> > length of the members. That'd duplicate the lenght for each of those\n> > arrays, but I have a bit of a hard time believing that that's a\n> > meaningful enough overhead.\n> >\n> > I'm thinking of a macro that'd be used like\n> > ARRAY_FIELD(AttrNumber) *sortColIdx;\n> > that'd generate code like\n> > struct\n> > {\n> > size_t nmembers;\n> > AttrNumber members[FLEXIBLE_ARRAY_MEMBER];\n> > } *sortColIdx;\n> >\n> > plus a set of macros (or perhaps inline functions + macros) to access\n> > them.\n> \n> I've implemented 3), which seems to work well. But it's a fair bit of\n> macro magic.\n> \n> Basically, one can define a type to be array supported, by once using\n> PGARR_DEFINE_TYPE(element_type); which defines a struct type that has a\n> members array of type element_type. After that variables of the array\n> type can be defined using PGARR(element_type) (as members in a struct,\n> variables, ...).\n> \n> Macros like pgarr_size(arr), pgarr_empty(arr), pgarr_at(arr, at) can be\n> used to query (and in the last case also modify) the array.\n> \n> pgarr_append(element_type, arr, newel) can be used to append to the\n> array. Unfortunately I haven't figured out a satisfying a way to write\n> pgarr_append() without specifying the element_type. Either there's\n> multiple-evaluation of any of the types (for checking whether the\n> capacity needs to be increased), only `newel`s that can have their\n> address taken are supported (so it can be passed to a helper function),\n> or compiler specific magic has to be used (__typeof__ solves this\n> nicely).\n> \n> The array can be allocated (using pgarr_alloc_ro(type, capacity)) so\n> that a certain number of elements fit inline.\n> \n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 2 Oct 2019 13:46:30 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Re: WIP: Generic functions for Node types using generated metadata" }, { "msg_contents": "On Wed, Oct 2, 2019 at 4:46 PM Andres Freund <andres@anarazel.de> wrote:\n> > The existing expectation is that we make our build tools in Perl.\n> > I'm sure Andres doesn't want to write a C parser in Perl, but\n> > poking around suggests that there are multiple options already\n> > available in CPAN. I'd much rather tell people \"oh, there's YA\n> > module you need to get from CPAN\" than \"figure out how to install\n> > version XXX of LLVM\".\n>\n> As far as I can tell they're all at least one of\n> 1) written in C, so also have build requirements (obviously a shorter\n> build time)\n> 2) not very good (including plenty unsupported C, not to speak of\n> various optional extensions we use, not having preprocessor support,\n> ...)\n> 3) unmaintained for many years.\n\nI find this argument to be compelling.\n\nTo me, it seems like having to install some random CPAN module is\nprobably more likely to be a problem than having to install LLVM. For\none thing, it's pretty likely that any given developer already has\nLLVM, either because they're using clang as their C compiler in\ngeneral, or because their system has it installed anyway, or because\nthey've built with JIT support at least once. And, if they haven't got\nit, their favorite packaging system will certainly have a build of\nLLVM, but it may not have a build of Parse::C::Erratically.\n\nReally, this has been a problem even just for TAP tests, where we've\nhad periodic debates over whether it's OK for a test to depend on some\nnew module that everyone may not have installed, possibly because\nthey're running some ancient Perl distribution (and our definition of\n\"ancient\" might make a historian giggle) where it wasn't bundled with\ncore Perl. Can we rewrite the test so it doesn't need the module? Do\nwe just skip the test, possibly masking a failure for some users? Do\nwe make it fail and force everybody to find a way to install that\nmodule?\n\nJust to be clear, I'm not in love with using LLVM. It's a big hairy\npiece of technology that I don't understand. However, it's also a very\nwidely-supported and very capable piece of technology that other\npeople do understand, and we're already using it for other things. I\ndon't think we're going to do better by using something different and\nprobably less capable and less well-supported for this thing.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 3 Oct 2019 10:18:04 -0400", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP: Generic functions for Node types using generated metadata" }, { "msg_contents": "On Fri, 20 Sep 2019 at 17:19, Andres Freund <andres@anarazel.de> wrote:\n> 3) WIP: Improve and expand stringinfo.[ch].\n>\n> Expands the set of functions exposed, to allow appending various\n> numeric types etc. Also improve efficiency by moving code to inline\n> functions - that's beneficial because the size is often known, which\n> can make the copy faster.\n\nI've thought it might be useful to have appendStringInfoInt() and the\nlike before. However, I wondered if there's a good reason that the\nformat needs to be easily human-readable. We could reduce the size of\nthe output and speed up read/write functions if we were to use base16\nor even base64 output.\n\nI also think the Bitmapset output is pretty inefficient. The output is\noptimized for something that Bitmapsets themselves are not optimized\nfor. The only time the current output will be efficient is if there\nare very few set bits but the values of those bits are very far apart.\nBitmapsets themselves are not optimal for that, so I don't see why our\nout function for it should be. ISTM it would be better encoded as a\nhex string, or perhaps if we still want to optimize a bit for sparse\nBitmapsets then it could be done as word_number:word_value. However,\nthat would mean the output would be variable depending on the width of\nthe bitmapword.\n\nDavid\n\n\n", "msg_date": "Tue, 9 Jun 2020 20:27:12 +1200", "msg_from": "David Rowley <dgrowleyml@gmail.com>", "msg_from_op": false, "msg_subject": "Re: WIP: Generic functions for Node types using generated metadata" } ]
[ { "msg_contents": "Hi\n\nHere:\n\n https://www.postgresql.org/docs/current/plpgsql-control-structures.html#PLPGSQL-RECORDS-ITERATING\n\nwe have a sample PL/PgSQL function (dating from at least 7.2) demonstrating\nquery result loops, which refreshes some pseudo materialized views stored in\na user-defined table.\n\nAs we've had proper materialized views since 9.3, I thought it might\nbe nice to update this with a self-contained sample which can be used\nas-is; see attached patch.\n\n(As a side note the current sample function contains a couple of \"%s\"\nplaceholders which should be just \"%\"; a quick search of plpgsql.sgml\nshows this is the only place they occur).\n\nWill submit to the next commitfest.\n\n\nRegards\n\nIan Barwick\n\n-- \n Ian Barwick https://www.2ndQuadrant.com/\n PostgreSQL Development, 24x7 Support, Training & Services", "msg_date": "Thu, 29 Aug 2019 12:03:08 +0900", "msg_from": "Ian Barwick <ian.barwick@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "doc: update PL/pgSQL sample loop function" }, { "msg_contents": "Hi\n\nčt 29. 8. 2019 v 5:03 odesílatel Ian Barwick <ian.barwick@2ndquadrant.com>\nnapsal:\n\n> Hi\n>\n> Here:\n>\n>\n> https://www.postgresql.org/docs/current/plpgsql-control-structures.html#PLPGSQL-RECORDS-ITERATING\n>\n> we have a sample PL/PgSQL function (dating from at least 7.2) demonstrating\n> query result loops, which refreshes some pseudo materialized views stored\n> in\n> a user-defined table.\n>\n> As we've had proper materialized views since 9.3, I thought it might\n> be nice to update this with a self-contained sample which can be used\n> as-is; see attached patch.\n>\n> (As a side note the current sample function contains a couple of \"%s\"\n> placeholders which should be just \"%\"; a quick search of plpgsql.sgml\n> shows this is the only place they occur).\n>\n> Will submit to the next commitfest.\n>\n\n+1\n\nPavel\n\n\n>\n> Regards\n>\n> Ian Barwick\n>\n> --\n> Ian Barwick https://www.2ndQuadrant.com/\n> PostgreSQL Development, 24x7 Support, Training & Services\n>\n\nHičt 29. 8. 2019 v 5:03 odesílatel Ian Barwick <ian.barwick@2ndquadrant.com> napsal:Hi\n\nHere:\n\n   https://www.postgresql.org/docs/current/plpgsql-control-structures.html#PLPGSQL-RECORDS-ITERATING\n\nwe have a sample PL/PgSQL function (dating from at least 7.2) demonstrating\nquery result loops, which refreshes some pseudo materialized views stored in\na user-defined table.\n\nAs we've had proper materialized views since 9.3, I thought it might\nbe nice to update this with a self-contained sample which can be used\nas-is; see attached patch.\n\n(As a side note the current sample function contains a couple of \"%s\"\nplaceholders which should be just \"%\"; a quick search of plpgsql.sgml\nshows this is the only place they occur).\n\nWill submit to the next commitfest.+1Pavel\n\n\nRegards\n\nIan Barwick\n\n-- \n  Ian Barwick                   https://www.2ndQuadrant.com/\n  PostgreSQL Development, 24x7 Support, Training & Services", "msg_date": "Thu, 29 Aug 2019 06:36:06 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: doc: update PL/pgSQL sample loop function" }, { "msg_contents": "On Thu, Aug 29, 2019 at 10:07 AM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>\n> Hi\n>\n> čt 29. 8. 2019 v 5:03 odesílatel Ian Barwick <ian.barwick@2ndquadrant.com> napsal:\n>>\n>> Hi\n>>\n>> Here:\n>>\n>> https://www.postgresql.org/docs/current/plpgsql-control-structures.html#PLPGSQL-RECORDS-ITERATING\n>>\n>> we have a sample PL/PgSQL function (dating from at least 7.2) demonstrating\n>> query result loops, which refreshes some pseudo materialized views stored in\n>> a user-defined table.\n>>\n>> As we've had proper materialized views since 9.3, I thought it might\n>> be nice to update this with a self-contained sample which can be used\n>> as-is; see attached patch.\n>>\n>> (As a side note the current sample function contains a couple of \"%s\"\n>> placeholders which should be just \"%\"; a quick search of plpgsql.sgml\n>> shows this is the only place they occur).\n>>\n>> Will submit to the next commitfest.\n>\n> +1\n>\n\nThe current example shows the usage of looping in plpgsql, so as such\nthere is no correctness issue, but OTOH there is no harm in updating\nthe example as proposed by Ian Barwick. Does anyone else see any\nproblem with this idea? If we agree to proceed with this update, it\nmight be better to backpatch it for the sake of consistency though I\nam not sure about that.\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Sun, 1 Sep 2019 09:09:24 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: doc: update PL/pgSQL sample loop function" }, { "msg_contents": "On Sun, Sep 1, 2019 at 9:09 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> The current example shows the usage of looping in plpgsql, so as such\n> there is no correctness issue, but OTOH there is no harm in updating\n> the example as proposed by Ian Barwick. Does anyone else see any\n> problem with this idea? If we agree to proceed with this update, it\n> might be better to backpatch it for the sake of consistency though I\n> am not sure about that.\n>\n\nWhile checking the patch in back-branches, I noticed that it doesn't\nget applied to 9.4 due to the way the example forms the string. I\nhave done the required changes for 9.4 as well and attached is the\nresult.\n\nIan, if possible, can you once check the patch for 9.4?\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Wed, 11 Sep 2019 11:14:59 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: doc: update PL/pgSQL sample loop function" }, { "msg_contents": "st 11. 9. 2019 v 7:45 odesílatel Amit Kapila <amit.kapila16@gmail.com>\nnapsal:\n\n> On Sun, Sep 1, 2019 at 9:09 AM Amit Kapila <amit.kapila16@gmail.com>\n> wrote:\n> >\n> > The current example shows the usage of looping in plpgsql, so as such\n> > there is no correctness issue, but OTOH there is no harm in updating\n> > the example as proposed by Ian Barwick. Does anyone else see any\n> > problem with this idea? If we agree to proceed with this update, it\n> > might be better to backpatch it for the sake of consistency though I\n> > am not sure about that.\n> >\n>\n> While checking the patch in back-branches, I noticed that it doesn't\n> get applied to 9.4 due to the way the example forms the string. I\n> have done the required changes for 9.4 as well and attached is the\n> result.\n>\n>\nIs question if for this queries should not be used some from\ninformation_schema instead direct access to pg_catalog.\n\nBut I looked now, and we don't see materialized views in information_schema\n- what is probably bug.\n\nPavel\n\n\n> Ian, if possible, can you once check the patch for 9.4?\n>\n> --\n> With Regards,\n> Amit Kapila.\n> EnterpriseDB: http://www.enterprisedb.com\n>\n\nst 11. 9. 2019 v 7:45 odesílatel Amit Kapila <amit.kapila16@gmail.com> napsal:On Sun, Sep 1, 2019 at 9:09 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>\n> The current example shows the usage of looping in plpgsql, so as such\n> there is no correctness issue, but OTOH there is no harm in updating\n> the example as proposed by Ian Barwick.  Does anyone else see any\n> problem with this idea?  If we agree to proceed with this update, it\n> might be better to backpatch it for the sake of consistency though I\n> am not sure about that.\n>\n\nWhile checking the patch in back-branches, I noticed that it doesn't\nget applied to 9.4 due to the way the example forms the string.  I\nhave done the required changes for 9.4 as well and attached is the\nresult.\nIs question if for this queries should not be used some from information_schema instead direct access to pg_catalog.But I looked now, and we don't see materialized views in information_schema - what is probably bug.Pavel \nIan, if possible, can you once check the patch for 9.4?\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Wed, 11 Sep 2019 08:09:40 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: doc: update PL/pgSQL sample loop function" }, { "msg_contents": "On Wed, Sep 11, 2019 at 11:40 AM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>\n> st 11. 9. 2019 v 7:45 odesílatel Amit Kapila <amit.kapila16@gmail.com> napsal:\n>>\n>> On Sun, Sep 1, 2019 at 9:09 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>> >\n>> > The current example shows the usage of looping in plpgsql, so as such\n>> > there is no correctness issue, but OTOH there is no harm in updating\n>> > the example as proposed by Ian Barwick. Does anyone else see any\n>> > problem with this idea? If we agree to proceed with this update, it\n>> > might be better to backpatch it for the sake of consistency though I\n>> > am not sure about that.\n>> >\n>>\n>> While checking the patch in back-branches, I noticed that it doesn't\n>> get applied to 9.4 due to the way the example forms the string. I\n>> have done the required changes for 9.4 as well and attached is the\n>> result.\n>>\n>\n> Is question if for this queries should not be used some from information_schema instead direct access to pg_catalog.\n>\n> But I looked now, and we don't see materialized views in information_schema - what is probably bug.\n>\n\nI think you got the answer of this on a related thread. Do you see\nany other problems or have any concerns about this?\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 11 Sep 2019 15:20:59 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: doc: update PL/pgSQL sample loop function" }, { "msg_contents": "st 11. 9. 2019 v 11:51 odesílatel Amit Kapila <amit.kapila16@gmail.com>\nnapsal:\n\n> On Wed, Sep 11, 2019 at 11:40 AM Pavel Stehule <pavel.stehule@gmail.com>\n> wrote:\n> >\n> > st 11. 9. 2019 v 7:45 odesílatel Amit Kapila <amit.kapila16@gmail.com>\n> napsal:\n> >>\n> >> On Sun, Sep 1, 2019 at 9:09 AM Amit Kapila <amit.kapila16@gmail.com>\n> wrote:\n> >> >\n> >> > The current example shows the usage of looping in plpgsql, so as such\n> >> > there is no correctness issue, but OTOH there is no harm in updating\n> >> > the example as proposed by Ian Barwick. Does anyone else see any\n> >> > problem with this idea? If we agree to proceed with this update, it\n> >> > might be better to backpatch it for the sake of consistency though I\n> >> > am not sure about that.\n> >> >\n> >>\n> >> While checking the patch in back-branches, I noticed that it doesn't\n> >> get applied to 9.4 due to the way the example forms the string. I\n> >> have done the required changes for 9.4 as well and attached is the\n> >> result.\n> >>\n> >\n> > Is question if for this queries should not be used some from\n> information_schema instead direct access to pg_catalog.\n> >\n> > But I looked now, and we don't see materialized views in\n> information_schema - what is probably bug.\n> >\n>\n> I think you got the answer of this on a related thread. Do you see\n> any other problems or have any concerns about this?\n>\n\nno\n\nPavel\n\n\n> --\n> With Regards,\n> Amit Kapila.\n> EnterpriseDB: http://www.enterprisedb.com\n>\n\nst 11. 9. 2019 v 11:51 odesílatel Amit Kapila <amit.kapila16@gmail.com> napsal:On Wed, Sep 11, 2019 at 11:40 AM Pavel Stehule <pavel.stehule@gmail.com> wrote:\n>\n> st 11. 9. 2019 v 7:45 odesílatel Amit Kapila <amit.kapila16@gmail.com> napsal:\n>>\n>> On Sun, Sep 1, 2019 at 9:09 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>> >\n>> > The current example shows the usage of looping in plpgsql, so as such\n>> > there is no correctness issue, but OTOH there is no harm in updating\n>> > the example as proposed by Ian Barwick.  Does anyone else see any\n>> > problem with this idea?  If we agree to proceed with this update, it\n>> > might be better to backpatch it for the sake of consistency though I\n>> > am not sure about that.\n>> >\n>>\n>> While checking the patch in back-branches, I noticed that it doesn't\n>> get applied to 9.4 due to the way the example forms the string.  I\n>> have done the required changes for 9.4 as well and attached is the\n>> result.\n>>\n>\n> Is question if for this queries should not be used some from information_schema instead direct access to pg_catalog.\n>\n> But I looked now, and we don't see materialized views in information_schema - what is probably bug.\n>\n\nI think you got the answer of this on a related thread.  Do you see\nany other problems or have any concerns about this?noPavel\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com", "msg_date": "Wed, 11 Sep 2019 12:05:36 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: doc: update PL/pgSQL sample loop function" }, { "msg_contents": "On 2019/09/11 14:44, Amit Kapila wrote:\n> On Sun, Sep 1, 2019 at 9:09 AM Amit Kapila <amit.kapila16@gmail.com> wrote:\n>>\n>> The current example shows the usage of looping in plpgsql, so as such\n>> there is no correctness issue, but OTOH there is no harm in updating\n>> the example as proposed by Ian Barwick. Does anyone else see any\n>> problem with this idea? If we agree to proceed with this update, it\n>> might be better to backpatch it for the sake of consistency though I\n>> am not sure about that.\n>>\n> \n> While checking the patch in back-branches, I noticed that it doesn't\n> get applied to 9.4 due to the way the example forms the string. I\n> have done the required changes for 9.4 as well and attached is the\n> result.\n\nAha, I had it in my head that 9.4 was being deprecated soon and didn't\ncheck that far back, but turns out it's around until Feb. 2020.\n\n> Ian, if possible, can you once check the patch for 9.4?\n\nLooks good, thanks for catching that!\n\n\nRegards\n\nIan Barwick\n\n-- \n Ian Barwick https://www.2ndQuadrant.com/\n PostgreSQL Development, 24x7 Support, Training & Services\n\n\n", "msg_date": "Thu, 12 Sep 2019 13:00:02 +0900", "msg_from": "Ian Barwick <ian.barwick@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: doc: update PL/pgSQL sample loop function" } ]
[ { "msg_contents": "\n> Patch works for me, and solution seems appropriate. It should be committed \n> for pg 12.0.\n\nI have listed this as an open issue of the upcoming pg 12:\n\n \thttps://wiki.postgresql.org/wiki/PostgreSQL_12_Open_Items#Open_Issues\n\n-- \nFabien.\n\n\n", "msg_date": "Thu, 29 Aug 2019 09:24:11 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": true, "msg_subject": "Re: BUG #15977: Inconsistent behavior in chained transactions" } ]
[ { "msg_contents": "Dear Hackers.\n\nKuroda-san and I are interested in the GIN index and have been testing\nvarious things.\nWhile testing, we are found a little bug.\nSome cases, the value of nEntries in the metapage was set to the wrong value.\n\nThis is a reproduce of bug situation.\n=# SET maintenance_work_mem TO '1MB';\n=# CREATE TABLE foo(i jsonb);\n=# INSERT INTO foo(i) select jsonb_build_object('foobar001', i) FROM\ngenerate_series(1, 10000) AS i;\n\n# Input the same value again.\n=# INSERT INTO foo(i) select jsonb_build_object('foobar001', i) FROM\ngenerate_series(1, 10000) AS i;\n# Creates GIN Index.\n=# CREATE INDEX foo_idx ON foo USING gin (i jsonb_ops);\n\n\n=# SELECT * FROM gin_metapage_info(get_raw_page('foo_idx', 0)) WITH\n(fastupdate=off);\n-[ RECORD 1 ]----+-----------\npending_head | 4294967295\npending_tail | 4294967295\ntail_free_size | 0\nn_pending_pages | 0\nn_pending_tuples | 0\nn_total_pages | 74\nn_entry_pages | 69\nn_data_pages | 4\nn_entries | 20004 <--★\nversion | 2\n\nIn this example, the nentries value should be 10001 because the gin\nindex stores duplicate values in one leaf(posting tree or posting\nlist).\nBut, if look at the nentries value of metapage using pageinspect, it\nis stored as 20004.\nSo, Let's run the vacuum.\n\n\n=# VACUUM foo;\n=# SELECT * FROM gin_metapage_info(get_raw_page('foo_idx', 0));\n-[ RECORD 1 ]----+-----------\npending_head | 4294967295\npending_tail | 4294967295\ntail_free_size | 0\nn_pending_pages | 0\nn_pending_tuples | 0\nn_total_pages | 74\nn_entry_pages | 69\nn_data_pages | 4\nn_entries | 10001 <--★\nversion | 2\n\nAh. Run to the vacuum, nEntries is changing the normal value.\n\nThere is a problem with the ginEntryInsert function. That calls the\ntable scan when creating the gin index, ginBuildCallback function\nstores the new heap value inside buildstate struct.\nAnd next step, If GinBuildState struct is the size of the memory to be\nusing is equal to or larger than the maintenance_work_mem value, run\nto input value into the GIN index.\nThis process is a function called ginEnctryInsert.\nThe ginEntryInsert function called at this time determines that a new\nentry is added and increase the value of nEntries.\nHowever currently, ginEntryInsert is first to increase in the value of\nnEntries, and to determine if there are the same entries in the\ncurrent GIN index.\nThat causes the bug.\n\nThe patch is very simple.\nFix to increase the value of nEntries only when a non-duplicate GIN\nindex leaf added.\n\nThis bug detection and code fix worked with Kuroda-san.\n\nBest Regards.\nMoon.", "msg_date": "Thu, 29 Aug 2019 17:19:51 +0900", "msg_from": "\"Moon, Insung\" <tsukiwamoon.pgsql@gmail.com>", "msg_from_op": true, "msg_subject": "Wrong value in metapage of GIN INDEX." }, { "msg_contents": "Hi Moon-san.\n\nThank you for posting.\n\nWe are testing the GIN index onJSONB type.\nThe default maintenance_work_mem (64MB) was fine in usually cases.\nHowever, this problem occurs when indexing very large JSONB data.\n\nbest regards,\nKeisuke Kuroda\n\n2019年8月29日(木) 17:20 Moon, Insung <tsukiwamoon.pgsql@gmail.com>:\n\n> Dear Hackers.\n>\n> Kuroda-san and I are interested in the GIN index and have been testing\n> various things.\n> While testing, we are found a little bug.\n> Some cases, the value of nEntries in the metapage was set to the wrong\n> value.\n>\n> This is a reproduce of bug situation.\n> =# SET maintenance_work_mem TO '1MB';\n> =# CREATE TABLE foo(i jsonb);\n> =# INSERT INTO foo(i) select jsonb_build_object('foobar001', i) FROM\n> generate_series(1, 10000) AS i;\n>\n> # Input the same value again.\n> =# INSERT INTO foo(i) select jsonb_build_object('foobar001', i) FROM\n> generate_series(1, 10000) AS i;\n> # Creates GIN Index.\n> =# CREATE INDEX foo_idx ON foo USING gin (i jsonb_ops);\n>\n>\n> =# SELECT * FROM gin_metapage_info(get_raw_page('foo_idx', 0)) WITH\n> (fastupdate=off);\n> -[ RECORD 1 ]----+-----------\n> pending_head | 4294967295\n> pending_tail | 4294967295\n> tail_free_size | 0\n> n_pending_pages | 0\n> n_pending_tuples | 0\n> n_total_pages | 74\n> n_entry_pages | 69\n> n_data_pages | 4\n> n_entries | 20004 <--★\n> version | 2\n>\n> In this example, the nentries value should be 10001 because the gin\n> index stores duplicate values in one leaf(posting tree or posting\n> list).\n> But, if look at the nentries value of metapage using pageinspect, it\n> is stored as 20004.\n> So, Let's run the vacuum.\n>\n>\n> =# VACUUM foo;\n> =# SELECT * FROM gin_metapage_info(get_raw_page('foo_idx', 0));\n> -[ RECORD 1 ]----+-----------\n> pending_head | 4294967295\n> pending_tail | 4294967295\n> tail_free_size | 0\n> n_pending_pages | 0\n> n_pending_tuples | 0\n> n_total_pages | 74\n> n_entry_pages | 69\n> n_data_pages | 4\n> n_entries | 10001 <--★\n> version | 2\n>\n> Ah. Run to the vacuum, nEntries is changing the normal value.\n>\n> There is a problem with the ginEntryInsert function. That calls the\n> table scan when creating the gin index, ginBuildCallback function\n> stores the new heap value inside buildstate struct.\n> And next step, If GinBuildState struct is the size of the memory to be\n> using is equal to or larger than the maintenance_work_mem value, run\n> to input value into the GIN index.\n> This process is a function called ginEnctryInsert.\n> The ginEntryInsert function called at this time determines that a new\n> entry is added and increase the value of nEntries.\n> However currently, ginEntryInsert is first to increase in the value of\n> nEntries, and to determine if there are the same entries in the\n> current GIN index.\n> That causes the bug.\n>\n> The patch is very simple.\n> Fix to increase the value of nEntries only when a non-duplicate GIN\n> index leaf added.\n>\n> This bug detection and code fix worked with Kuroda-san.\n>\n> Best Regards.\n> Moon.\n>\n\nHi Moon-san.Thank you for posting.We are testing the GIN index onJSONB type.The default maintenance_work_mem (64MB) was fine in usually cases.However, this problem occurs when indexing very large JSONB data.best regards,Keisuke Kuroda2019年8月29日(木) 17:20 Moon, Insung <tsukiwamoon.pgsql@gmail.com>:Dear Hackers.\n\nKuroda-san and I are interested in the GIN index and have been testing\nvarious things.\nWhile testing, we are found a little bug.\nSome cases, the value of nEntries in the metapage was set to the wrong value.\n\nThis is a reproduce of bug situation.\n=# SET maintenance_work_mem TO '1MB';\n=# CREATE TABLE foo(i jsonb);\n=# INSERT INTO foo(i) select jsonb_build_object('foobar001', i) FROM\ngenerate_series(1, 10000) AS i;\n\n# Input the same value again.\n=# INSERT INTO foo(i) select jsonb_build_object('foobar001', i) FROM\ngenerate_series(1, 10000) AS i;\n# Creates GIN Index.\n=# CREATE INDEX foo_idx ON foo USING gin (i jsonb_ops);\n\n\n=# SELECT * FROM gin_metapage_info(get_raw_page('foo_idx', 0)) WITH\n(fastupdate=off);\n-[ RECORD 1 ]----+-----------\npending_head     | 4294967295\npending_tail     | 4294967295\ntail_free_size   | 0\nn_pending_pages  | 0\nn_pending_tuples | 0\nn_total_pages    | 74\nn_entry_pages    | 69\nn_data_pages     | 4\nn_entries        | 20004 <--★\nversion          | 2\n\nIn this example, the nentries value should be 10001 because the gin\nindex stores duplicate values in one leaf(posting tree or posting\nlist).\nBut, if look at the nentries value of metapage using pageinspect, it\nis stored as 20004.\nSo, Let's run the vacuum.\n\n\n=# VACUUM foo;\n=# SELECT * FROM gin_metapage_info(get_raw_page('foo_idx', 0));\n-[ RECORD 1 ]----+-----------\npending_head     | 4294967295\npending_tail     | 4294967295\ntail_free_size   | 0\nn_pending_pages  | 0\nn_pending_tuples | 0\nn_total_pages    | 74\nn_entry_pages    | 69\nn_data_pages     | 4\nn_entries        | 10001 <--★\nversion          | 2\n\nAh. Run to the vacuum, nEntries is changing the normal value.\n\nThere is a problem with the ginEntryInsert function. That calls the\ntable scan when creating the gin index, ginBuildCallback function\nstores the new heap value inside buildstate struct.\nAnd next step, If GinBuildState struct is the size of the memory to be\nusing is equal to or larger than the maintenance_work_mem value, run\nto input value into the GIN index.\nThis process is a function called ginEnctryInsert.\nThe ginEntryInsert function called at this time determines that a new\nentry is added and increase the value of nEntries.\nHowever currently, ginEntryInsert is first to increase in the value of\nnEntries, and to determine if there are the same entries in the\ncurrent GIN index.\nThat causes the bug.\n\nThe patch is very simple.\nFix to increase the value of nEntries only when a non-duplicate GIN\nindex leaf added.\n\nThis bug detection and code fix worked with Kuroda-san.\n\nBest Regards.\nMoon.", "msg_date": "Fri, 30 Aug 2019 11:48:47 +0900", "msg_from": "keisuke kuroda <keisuke.kuroda.3862@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Wrong value in metapage of GIN INDEX." }, { "msg_contents": "Moon-san, kuroda.keisuke-san\r\n\r\nOn Thu, Aug 29, 2019 at 8:20 AM, Moon, Insung wrote:\r\n> =# CREATE INDEX foo_idx ON foo USING gin (i jsonb_ops);\r\n> =# SELECT * FROM gin_metapage_info(get_raw_page('foo_idx', 0)) WITH (fastupdate=off);\r\n\r\nThis is not important thing but some mistakes are here.\r\n\r\n=# CREATE INDEX foo_idx ON foo USING gin (i jsonb_ops) WITH (fastupdate=off);\r\n=# SELECT * FROM gin_metapage_info(get_raw_page('foo_idx', 0));\r\n\r\n\r\n> In this example, the nentries value should be 10001 because the gin index stores duplicate values in one leaf(posting\r\n> tree or posting list).\r\n...\r\n> The patch is very simple.\r\n> Fix to increase the value of nEntries only when a non-duplicate GIN index leaf added.\r\n\r\nDoes nentries show the number of entries in the leaf pages?\r\nIf so, the fix seems to be correct.\r\n\r\n--\r\nYoshikazu Imai\r\n", "msg_date": "Tue, 8 Oct 2019 06:46:10 +0000", "msg_from": "\"imai.yoshikazu@fujitsu.com\" <imai.yoshikazu@fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: Wrong value in metapage of GIN INDEX." }, { "msg_contents": "\"imai.yoshikazu@fujitsu.com\" <imai.yoshikazu@fujitsu.com> writes:\n> Moon-san, kuroda.keisuke-san\n> On Thu, Aug 29, 2019 at 8:20 AM, Moon, Insung wrote:\n>> The patch is very simple.\n>> Fix to increase the value of nEntries only when a non-duplicate GIN index leaf added.\n\n> Does nentries show the number of entries in the leaf pages?\n> If so, the fix seems to be correct.\n\nI looked at this issue. The code in ginEntryInsert is not obviously wrong\nby itself; it depends on what you think nEntries is supposed to count.\nHowever, ginvacuum.c updates nEntries to the sum of PageGetMaxOffsetNumber()\nacross all the index's leaf pages, ie the number of surviving leaf items.\n\nIt's hard to see how ginvacuum could reverse-engineer a value that would\nmatch what ginEntryInsert is doing, so probably we ought to define\nnEntries as the number of leaf items, which seems to make the proposed\npatch correct. (It could use a bit more commentary though.)\n\nI'm inclined to apply this to HEAD only; it doesn't seem significant\nenough to justify back-patching.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 04 Nov 2019 13:55:02 -0500", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Wrong value in metapage of GIN INDEX." }, { "msg_contents": "Dear Tom Lane.\n\nOn Tue, Nov 5, 2019 at 3:55 AM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> \"imai.yoshikazu@fujitsu.com\" <imai.yoshikazu@fujitsu.com> writes:\n> > Moon-san, kuroda.keisuke-san\n> > On Thu, Aug 29, 2019 at 8:20 AM, Moon, Insung wrote:\n> >> The patch is very simple.\n> >> Fix to increase the value of nEntries only when a non-duplicate GIN index leaf added.\n>\n> > Does nentries show the number of entries in the leaf pages?\n> > If so, the fix seems to be correct.\n>\n> I looked at this issue. The code in ginEntryInsert is not obviously wrong\n> by itself; it depends on what you think nEntries is supposed to count.\n> However, ginvacuum.c updates nEntries to the sum of PageGetMaxOffsetNumber()\n> across all the index's leaf pages, ie the number of surviving leaf items.\n>\n> It's hard to see how ginvacuum could reverse-engineer a value that would\n> match what ginEntryInsert is doing, so probably we ought to define\n> nEntries as the number of leaf items, which seems to make the proposed\n> patch correct. (It could use a bit more commentary though.)\n>\n> I'm inclined to apply this to HEAD only; it doesn't seem significant\n> enough to justify back-patching.\n\nThank you for review and push to patch.\nYes. I don't think it's a bug that has a big impact like your opinion.\n\nBest regards.\nMoon.\n\n>\n> regards, tom lane\n\n\n", "msg_date": "Tue, 5 Nov 2019 17:21:14 +0900", "msg_from": "\"Moon, Insung\" <tsukiwamoon.pgsql@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Wrong value in metapage of GIN INDEX." } ]
[ { "msg_contents": "Hello\n\nI hear is not recommended to set pg_resetwal with --wal-segsize for wal\nincreasing. Are any more detailed information exists about it? What an\neffects could be? Does it possible change it due full offline?\n\nRegards,\nPaul\n\nHelloI hear is not recommended to set pg_resetwal with --wal-segsize for wal increasing. Are any more detailed information exists about it? What an effects could be? Does it possible change it due full offline?Regards,Paul", "msg_date": "Thu, 29 Aug 2019 15:55:17 +0300", "msg_from": "Pavel Demidov <zeller56@gmail.com>", "msg_from_op": true, "msg_subject": "pg_resetwal and --wal-segsize" } ]
[ { "msg_contents": "Hi\n\nI just noticed \"\\df[TAB]\" fails to offer any tab-completion for\nthe possible suffixes (\"\\dfa\", \"\\dfn\", \"\\dfp\", \"\\dft\" and \"\\dfw\").\nTrivial patch attached, which applies back to Pg96, and separate\npatches for Pg95 and Pg94.\n\nI'll add this to the next commitfest.\n\nRegards\n\nIan Barwick\n\n-- \n Ian Barwick https://www.2ndQuadrant.com/\n PostgreSQL Development, 24x7 Support, Training & Services", "msg_date": "Fri, 30 Aug 2019 14:01:19 +0900", "msg_from": "Ian Barwick <ian.barwick@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "[PATCH] psql: add tab completion for \\df slash command suffixes" }, { "msg_contents": "Hello Ian,\n\nOn Fri, Aug 30, 2019 at 10:31 AM Ian Barwick\n<ian.barwick@2ndquadrant.com> wrote:\n> I just noticed \"\\df[TAB]\" fails to offer any tab-completion for\n> the possible suffixes (\"\\dfa\", \"\\dfn\", \"\\dfp\", \"\\dft\" and \"\\dfw\").\n> Trivial patch attached, which applies back to Pg96, and separate\n> patches for Pg95 and Pg94.\n>\n> I'll add this to the next commitfest.\nI've reviewed the patch. It works as expected in master. But, the\nsyntax \"\\dfp\" doesn't exist beyond Pg11. So, you've to remove the same\nfrom the patches for Pg95 and Pg94. I guess the same patch should be\napplied on Pg10 and Pg96.\n\n\n\n-- \nThanks & Regards,\nKuntal Ghosh\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 4 Sep 2019 11:44:23 +0530", "msg_from": "Kuntal Ghosh <kuntalghosh.2007@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] psql: add tab completion for \\df slash command suffixes" }, { "msg_contents": "On 2019/09/04 15:14, Kuntal Ghosh wrote:\n> Hello Ian,\n> \n> On Fri, Aug 30, 2019 at 10:31 AM Ian Barwick\n> <ian.barwick@2ndquadrant.com> wrote:\n>> I just noticed \"\\df[TAB]\" fails to offer any tab-completion for\n>> the possible suffixes (\"\\dfa\", \"\\dfn\", \"\\dfp\", \"\\dft\" and \"\\dfw\").\n>> Trivial patch attached, which applies back to Pg96, and separate\n>> patches for Pg95 and Pg94.\n>>\n>> I'll add this to the next commitfest.\n> I've reviewed the patch. It works as expected in master. But, the\n> syntax \"\\dfp\" doesn't exist beyond Pg11. So, you've to remove the same\n> from the patches for Pg95 and Pg94. I guess the same patch should be\n> applied on Pg10 and Pg96.\n\nAh, good catch, I will update and resubmit.\n\n\nThanks!\n\nIan Barwick\n\n\n-- \n Ian Barwick https://www.2ndQuadrant.com/\n PostgreSQL Development, 24x7 Support, Training & Services\n\n\n", "msg_date": "Wed, 4 Sep 2019 15:19:57 +0900", "msg_from": "Ian Barwick <ian.barwick@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] psql: add tab completion for \\df slash command suffixes" }, { "msg_contents": "On Wed, Sep 04, 2019 at 03:19:57PM +0900, Ian Barwick wrote:\n> Ah, good catch, I will update and resubmit.\n\nPing. Ian, could you update and resubmit please?\n--\nMichael", "msg_date": "Fri, 27 Sep 2019 17:26:50 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [PATCH] psql: add tab completion for \\df slash command suffixes" } ]
[ { "msg_contents": "My buildfarm animal dromedary ran out of disk space yesterday, which\nI found rather surprising because the last time I'd looked it had\ntens of GB to spare. On investigation, the problem was lots and lots\nof core images in /cores, which is where macOS drops them (by default\nat least). It looked like I was getting one new core image per\nbuildfarm run, even successful runs. Even odder, they mostly seemed\nto be images from /bin/cp, not Postgres.\n\nAfter investigation, the mechanism that's causing that is that the\nsrc/test/recovery/t/010_logical_decoding_timelines.pl test shuts\ndown its replica server with a mode-immediate stop, which causes\nthat postmaster to shut down all its children with SIGQUIT, and\nin particular that signal propagates to a \"cp\" command that the\narchiver process is executing. The \"cp\" is unsurprisingly running\nwith default SIGQUIT handling, which per the signal man page\nincludes dumping core.\n\nThis makes me wonder whether we shouldn't be using some other signal\nto shut down archiver subprocesses. It's not real cool if we're\nspewing cores all over the place. Admittedly, production servers\nare likely running with \"ulimit -c 0\" on most modern platforms,\nso this might not be a huge problem in the field; but accumulation\nof core files could be a problem anywhere that's configured to allow\nserver core dumps.\n\nI suspect the reason we've not noticed this in the buildfarm is that most\nof those platforms are configured to dump core into the data directory,\nwhere it'll be thrown away when we clean up after the run. But aside\nfrom macOS, the machines running recent systemd releases are likely\naccumulating cores somewhere behind the scenes, since systemd has seen\nfit to insert itself into core-handling along with everything else.\n\nIdeally, perhaps, we'd be using SIGINT not SIGQUIT to shut down\nnon-Postgres child processes. But redesigning the system's signal\nhandling to make that possible seems like a bit of a mess.\n\nThoughts?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sat, 31 Aug 2019 16:58:25 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "From: Tom Lane [mailto:tgl@sss.pgh.pa.us]\n> After investigation, the mechanism that's causing that is that the\n> src/test/recovery/t/010_logical_decoding_timelines.pl test shuts\n> down its replica server with a mode-immediate stop, which causes\n> that postmaster to shut down all its children with SIGQUIT, and\n> in particular that signal propagates to a \"cp\" command that the\n> archiver process is executing. The \"cp\" is unsurprisingly running\n> with default SIGQUIT handling, which per the signal man page\n> includes dumping core.\n\nWe've experienced this (core dump in the data directory by an archive command) years ago. Related to this, the example of using cp in the PostgreSQL manual is misleading, because cp doesn't reliably persist the WAL archive file.\n\n\n> This makes me wonder whether we shouldn't be using some other signal\n> to shut down archiver subprocesses. It's not real cool if we're\n> spewing cores all over the place. Admittedly, production servers\n> are likely running with \"ulimit -c 0\" on most modern platforms,\n> so this might not be a huge problem in the field; but accumulation\n> of core files could be a problem anywhere that's configured to allow\n> server core dumps.\n\nWe enable the core dump in production to help the investigation just in case.\n\n\n> Ideally, perhaps, we'd be using SIGINT not SIGQUIT to shut down\n> non-Postgres child processes. But redesigning the system's signal\n> handling to make that possible seems like a bit of a mess.\n> \n> Thoughts?\n\nWe're using a shell script and a command that's called in the shell script. That is:\n\narchive_command = 'call some_shell_script.sh ...'\n\n[some_shell_script.sh]\nulimit -c 0\ntrap SIGQUIT to just exit on the receipt of the signal\ncall some_command to copy file\n\nsome_command also catches SIGQUIT just exit. It copies and syncs the file.\n\nI proposed something in this line as below, but I couldn't respond to Peter's review comments due to other tasks. Does anyone think it's worth resuming this?\n\nhttps://www.postgresql.org/message-id/7E37040CF3804EA5B018D7A022822984@maumau\n\n\nRegards\nTakayuki Tsunakawa\n\n\n\n\n\n", "msg_date": "Mon, 2 Sep 2019 00:27:09 +0000", "msg_from": "\"Tsunakawa, Takayuki\" <tsunakawa.takay@jp.fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "On Mon, Sep 02, 2019 at 12:27:09AM +0000, Tsunakawa, Takayuki wrote:\n> From: Tom Lane [mailto:tgl@sss.pgh.pa.us]\n>> After investigation, the mechanism that's causing that is that the\n>> src/test/recovery/t/010_logical_decoding_timelines.pl test shuts\n>> down its replica server with a mode-immediate stop, which causes\n>> that postmaster to shut down all its children with SIGQUIT, and\n>> in particular that signal propagates to a \"cp\" command that the\n>> archiver process is executing. The \"cp\" is unsurprisingly running\n>> with default SIGQUIT handling, which per the signal man page\n>> includes dumping core.\n> \n> We've experienced this (core dump in the data directory by an\n> archive command) years ago. Related to this, the example of using\n> cp in the PostgreSQL manual is misleading, because cp doesn't\n> reliably persist the WAL archive file.\n\nThe previous talks about having pg_copy are still where they were a\ncouple of years ago as we did not agree on which semantics it should\nhave. If we could move forward with that and update the documentation\nfrom its insanity that would be great and... The signal handling is\nsomething else we could customize in a more favorable way with the\narchiver. Anyway, switching from something else than SIGQUIT to stop\nthe archiver will not prevent any other tools from generating core\ndumps with this other signal.\n\n> We enable the core dump in production to help the investigation just in case.\n\nSo do I in some of the stuff I work on.\n\n> some_command also catches SIGQUIT just exit. It copies and syncs the file.\n> \n> I proposed something in this line as below, but I couldn't respond to Peter's review comments due to other tasks. Does anyone think it's worth resuming this?\n> \n> https://www.postgresql.org/message-id/7E37040CF3804EA5B018D7A022822984@maumau\n\nAnd I was looking for this thread a couple of lines ago :)\nThanks.\n--\nMichael", "msg_date": "Mon, 2 Sep 2019 15:51:34 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "At Mon, 2 Sep 2019 15:51:34 +0900, Michael Paquier <michael@paquier.xyz> wrote in <20190902065134.GE1841@paquier.xyz>\n> On Mon, Sep 02, 2019 at 12:27:09AM +0000, Tsunakawa, Takayuki wrote:\n> > From: Tom Lane [mailto:tgl@sss.pgh.pa.us]\n> >> After investigation, the mechanism that's causing that is that the\n> >> src/test/recovery/t/010_logical_decoding_timelines.pl test shuts\n> >> down its replica server with a mode-immediate stop, which causes\n> >> that postmaster to shut down all its children with SIGQUIT, and\n> >> in particular that signal propagates to a \"cp\" command that the\n> >> archiver process is executing. The \"cp\" is unsurprisingly running\n> >> with default SIGQUIT handling, which per the signal man page\n> >> includes dumping core.\n> > \n> > We've experienced this (core dump in the data directory by an\n> > archive command) years ago. Related to this, the example of using\n> > cp in the PostgreSQL manual is misleading, because cp doesn't\n> > reliably persist the WAL archive file.\n> \n> The previous talks about having pg_copy are still where they were a\n> couple of years ago as we did not agree on which semantics it should\n> have. If we could move forward with that and update the documentation\n> from its insanity that would be great and... The signal handling is\n> something else we could customize in a more favorable way with the\n> archiver. Anyway, switching from something else than SIGQUIT to stop\n> the archiver will not prevent any other tools from generating core\n> dumps with this other signal.\n\nSince we are allowing OPs to use arbitrary command as\narchive_command, providing a replacement with non-standard signal\nhandling for a specific command doesn't seem a general solution\nto me. Couldn't we have pg_system(a tentative name), which\nintercepts SIGQUIT then sends SIGINT to children? Might be need\nto resend SIGQUIT after some interval, though..\n\n> > We enable the core dump in production to help the investigation just in case.\n> \n> So do I in some of the stuff I work on.\n> \n> > some_command also catches SIGQUIT just exit. It copies and syncs the file.\n> > \n> > I proposed something in this line as below, but I couldn't respond to Peter's review comments due to other tasks. Does anyone think it's worth resuming this?\n> > \n> > https://www.postgresql.org/message-id/7E37040CF3804EA5B018D7A022822984@maumau\n> \n> And I was looking for this thread a couple of lines ago :)\n> Thanks.\n\n# Is there any means to view the whole of a thread from archive?\n# I'm a kind of reluctant to wander among messages like a rat in\n# a maze:p\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Mon, 02 Sep 2019 18:31:53 +0900 (Tokyo Standard Time)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "From: Kyotaro Horiguchi [mailto:horikyota.ntt@gmail.com]\n> Since we are allowing OPs to use arbitrary command as\n> archive_command, providing a replacement with non-standard signal\n> handling for a specific command doesn't seem a general solution\n> to me. Couldn't we have pg_system(a tentative name), which\n> intercepts SIGQUIT then sends SIGINT to children? Might be need\n> to resend SIGQUIT after some interval, though..\n\nThe same idea that you referred to as pg_system occurred to me, too. But I wondered if the archiver process can get the pid of its child (shell? archive_command?), while keeping the capabilities of system() (= the shell). Even if we fork() and then system(), doesn't the OS send SIGQUIT to any descendents of the archiver when postmaster sends SIGQUIT to the child process group?\n\n\n> # Is there any means to view the whole of a thread from archive?\n> # I'm a kind of reluctant to wander among messages like a rat in\n> # a maze:p\n\nYou can see the whole thread by clicking the \"Whole Thread\" link.\n\n\nRegards\nTakayuki Tsunakawa\n\n\n\n", "msg_date": "Tue, 3 Sep 2019 02:42:19 +0000", "msg_from": "\"Tsunakawa, Takayuki\" <tsunakawa.takay@jp.fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "On Tue, Sep 3, 2019 at 2:43 PM Tsunakawa, Takayuki\n<tsunakawa.takay@jp.fujitsu.com> wrote:\n> From: Kyotaro Horiguchi [mailto:horikyota.ntt@gmail.com]\n> > Since we are allowing OPs to use arbitrary command as\n> > archive_command, providing a replacement with non-standard signal\n> > handling for a specific command doesn't seem a general solution\n> > to me. Couldn't we have pg_system(a tentative name), which\n> > intercepts SIGQUIT then sends SIGINT to children? Might be need\n> > to resend SIGQUIT after some interval, though..\n>\n> The same idea that you referred to as pg_system occurred to me, too. But I wondered if the archiver process can get the pid of its child (shell? archive_command?), while keeping the capabilities of system() (= the shell). Even if we fork() and then system(), doesn't the OS send SIGQUIT to any descendents of the archiver when postmaster sends SIGQUIT to the child process group?\n\nSo, to recap what's happening here, we have a tree of processes like this:\n\npostmaster\n-> archiver\n -> sh\n -> cp [user-supplied archiving command]\n\nThe archiver is a process group leader, because it called setsid().\nThe postmaster's signal_child() does kill(pid, ...) and also\nkill(-pid, ...), so the kernel sends SIGQUIT to archiver (twice), sh\nand cp. As for what they do with the signal, it depends on timing:\n\n1. The archiver normally exits immediately in pgarch_exit(), but\nwhile system() is running, SIGQUIT and SIGINT are ignored (see POSIX).\n2. sh normally uses SIGINT to break out of loops etc, but while it's\nwaiting for a subprocess, it also ignores SIGQUIT and SIGINT (see\nPOSIX).\n3. cp inherits the default disposition and (unless it handles it\nspecially) dumps core.\n\nI think the general idea here is that interactive shells and similar\nthings want to ignore signals from users typing ^C (SIGINT) or ^\\\n(SIGQUIT) so they can affect just the thing that's actually running\nat this moment, not the tree of processes waiting.\n\nYeah, I guess we could have our own pg_system() function that does\nroughly what system() does, namely fork(), then execl() in the child\nand waitpid() in the parent, but the child could begin a new process\ngroup with setsid() before running execl() (so that it no longer gets\nSIGQUIT with the postmaster signals the archiver), and the parent\ncould record pg_system_child_pid when forking, and install a QUIT\nhandler that does kill(-pg_system_child_pid, SIGTERM), as well as\nsetting a flag that will cause its main loop to exit (but not before\nit has run waitpid()). With some carefully placed blocks and unblocks\nand ignores, to avoid races.\n\nThat all sounds like a lot of work though, and it might be easier to\njust make an exception and use SIGTERM to shut down the archiver, as I\nthink Tom was suggesting. Unfortunately we have the same problem\nelsewhere, where we use popen(). I just wrote a C program that does\njust \"sleep(60)\", ran it with COPY FROM PROGRAM, then sent SIGQUIT to\nthe postmaster, and got a dumped core.\n\n-- \nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Tue, 3 Sep 2019 17:43:57 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "At Tue, 3 Sep 2019 02:42:19 +0000, \"Tsunakawa, Takayuki\" <tsunakawa.takay@jp.fujitsu.com> wrote in <0A3221C70F24FB45833433255569204D1FD1609C@G01JPEXMBYT05>\n> From: Kyotaro Horiguchi [mailto:horikyota.ntt@gmail.com]\n> > Since we are allowing OPs to use arbitrary command as\n> > archive_command, providing a replacement with non-standard signal\n> > handling for a specific command doesn't seem a general solution\n> > to me. Couldn't we have pg_system(a tentative name), which\n> > intercepts SIGQUIT then sends SIGINT to children? Might be need\n> > to resend SIGQUIT after some interval, though..\n> \n> The same idea that you referred to as pg_system occurred to me,\n> too. But I wondered if the archiver process can get the pid of\n> its child (shell? archive_command?), while keeping the\n> capabilities of system() (= the shell). Even if we fork() and\n> then system(), doesn't the OS send SIGQUIT to any descendents\n\nI imagnined that we don't use system(3) at all. It would be\nalmost simplified version of system(3), but doesn't use\nit.\n\n> of the archiver when postmaster sends SIGQUIT to the child\n> process group?\n\nMmmm.. That's bad. The commit 3ad0728c81 intends to send SIGQUIT\nto the programs under system() for archiver process. I found the\ndiscusion for the patch.\n\nhttps://www.postgresql.org/message-id/flat/24849.1163826231%40sss.pgh.pa.us#c987fc18a4b9113c6276ae8b5d85abba\n\n> Reimplementing system() seems pretty ugly, but maybe we have no choice.\n> It strikes me that system() has a race condition as defined anyway,\n> because if a signal arrives between blocking the handler and issuing the\n> fork(), it'll disappear into the ether; and the same at the end of the\n> routine.\n..\n>> Alternatively perhaps Postgres really ought to be using USR1/USR2 or other\n>> signals that library routines won't think they have any business rearranging.\n>\n> The existing signal assignments were all picked for what seem to me\n> to be good reasons; I'm disinclined to change them. In any case, the\n> important point here is that we'd really like an archive or recovery\n> script, or for that matter any command executed via system() from a\n> backend, to abort when the parent backend is SIGINT'd or SIGQUIT'd.\n\nBut now we know that sending it to grand-children is wrong in a\nsense that that leads to left-alone unwanted core files. But the\nbehavior is already knwon at the time.\n\nSo, Now I know that we need to revert that in certain extent if\nwe want to stop the core-dumping behavior...\n\n\nI'm inclined to think that we should just document that behavior..\n\n\n> > # Is there any means to view the whole of a thread from archive?\n> > # I'm a kind of reluctant to wander among messages like a rat in\n> > # a maze:p\n> \n> You can see the whole thread by clicking the \"Whole Thread\" link.\n\nWhat??? Oops!!! I found it among \"Whole Mssage\", \"Download mbox\"\nand \"Resend email\". Sorry for my slipperly eyes and thanks!\n\nregrds.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Tue, 03 Sep 2019 15:13:01 +0900 (Tokyo Standard Time)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "Kyotaro Horiguchi <horikyota.ntt@gmail.com> writes:\n> But now we know that sending it to grand-children is wrong in a\n> sense that that leads to left-alone unwanted core files. But the\n> behavior is already knwon at the time.\n\n> So, Now I know that we need to revert that in certain extent if\n> we want to stop the core-dumping behavior...\n\nYeah. After thinking about this more, I'm inclined to propose that\nwe just change what the postmaster does, as per attached patch.\n\nA couple of questions arise:\n\n* Would it be better to substitute SIGTERM instead of SIGINT?\nThe POSIX default handling is the same for both, but some programs\nmight interpret them differently.\n\n* With this patch, our own processes would see SIGQUIT then\nSIGINT (or SIGTERM). Would any of them misbehave? I think not\n(and this patch does pass check-world) but it might be a good\nidea to double-check.\n\n\t\t\tregards, tom lane", "msg_date": "Tue, 03 Sep 2019 12:04:20 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "On 9/3/19 12:04 PM, Tom Lane wrote:\n> Kyotaro Horiguchi <horikyota.ntt@gmail.com> writes:\n>> But now we know that sending it to grand-children is wrong in a\n>> sense that that leads to left-alone unwanted core files. But the\n>> behavior is already knwon at the time.\n> \n>> So, Now I know that we need to revert that in certain extent if\n>> we want to stop the core-dumping behavior...\n> \n> Yeah. After thinking about this more, I'm inclined to propose that\n> we just change what the postmaster does, as per attached patch.\n> \n> A couple of questions arise:\n> \n> * Would it be better to substitute SIGTERM instead of SIGINT?\n> The POSIX default handling is the same for both, but some programs\n> might interpret them differently.\n\nI prefer SIGTERM, but FWIW pgBackRest handles them both the same way.\n\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Tue, 3 Sep 2019 14:09:18 -0400", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "Greetings,\n\n* Michael Paquier (michael@paquier.xyz) wrote:\n> On Mon, Sep 02, 2019 at 12:27:09AM +0000, Tsunakawa, Takayuki wrote:\n> > From: Tom Lane [mailto:tgl@sss.pgh.pa.us]\n> >> After investigation, the mechanism that's causing that is that the\n> >> src/test/recovery/t/010_logical_decoding_timelines.pl test shuts\n> >> down its replica server with a mode-immediate stop, which causes\n> >> that postmaster to shut down all its children with SIGQUIT, and\n> >> in particular that signal propagates to a \"cp\" command that the\n> >> archiver process is executing. The \"cp\" is unsurprisingly running\n> >> with default SIGQUIT handling, which per the signal man page\n> >> includes dumping core.\n> > \n> > We've experienced this (core dump in the data directory by an\n> > archive command) years ago. Related to this, the example of using\n> > cp in the PostgreSQL manual is misleading, because cp doesn't\n> > reliably persist the WAL archive file.\n> \n> The previous talks about having pg_copy are still where they were a\n> couple of years ago as we did not agree on which semantics it should\n> have. If we could move forward with that and update the documentation\n> from its insanity that would be great and... The signal handling is\n> something else we could customize in a more favorable way with the\n> archiver. Anyway, switching from something else than SIGQUIT to stop\n> the archiver will not prevent any other tools from generating core\n> dumps with this other signal.\n\nAny tools being used for archive command (which should basically be\nthings designed to be used as such and certainly not cp...) should be\nprepared to handle what PG ends up doing here. I don't think we should\nchange to a different signal because it'll make 'cp' do something\ndifferent. If there's a good reason to use a different signal, great.\n\nIn other words, I think I agree with Tom that maybe we should be using\nSIGINT here, but not so much because of exactly what cp does but rather\nbecause that's a more appropriate signal, as shown by what the default\nhandling for those signals is.\n\nThanks,\n\nStephen", "msg_date": "Tue, 3 Sep 2019 15:43:37 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "Greetings,\n\n* David Steele (david@pgmasters.net) wrote:\n> On 9/3/19 12:04 PM, Tom Lane wrote:\n> > Kyotaro Horiguchi <horikyota.ntt@gmail.com> writes:\n> >> But now we know that sending it to grand-children is wrong in a\n> >> sense that that leads to left-alone unwanted core files. But the\n> >> behavior is already knwon at the time.\n> > \n> >> So, Now I know that we need to revert that in certain extent if\n> >> we want to stop the core-dumping behavior...\n> > \n> > Yeah. After thinking about this more, I'm inclined to propose that\n> > we just change what the postmaster does, as per attached patch.\n> > \n> > A couple of questions arise:\n> > \n> > * Would it be better to substitute SIGTERM instead of SIGINT?\n> > The POSIX default handling is the same for both, but some programs\n> > might interpret them differently.\n> \n> I prefer SIGTERM, but FWIW pgBackRest handles them both the same way.\n\nYeah, I wondered about that too, perhaps SIGTERM is better. I'm not\nreally particular either way.\n\nThanks,\n\nStephen", "msg_date": "Tue, 3 Sep 2019 15:48:42 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> * David Steele (david@pgmasters.net) wrote:\n>> On 9/3/19 12:04 PM, Tom Lane wrote:\n>>> * Would it be better to substitute SIGTERM instead of SIGINT?\n>>> The POSIX default handling is the same for both, but some programs\n>>> might interpret them differently.\n\n>> I prefer SIGTERM, but FWIW pgBackRest handles them both the same way.\n\n> Yeah, I wondered about that too, perhaps SIGTERM is better. I'm not\n> really particular either way.\n\nYeah, after thinking about it, SIGTERM is probably what to use.\nIt's less likely that some random program would think it should\nmaybe not terminate in response. Catching SIGINT is pretty common\namong \"interactive\" programs, and while there doesn't seem an\nobvious reason to be using something like that below a PG process,\nyou never know.\n\nI looked around for potential problems arising from my other\npoint about our own processes seeing SIGQUIT then SIGTERM.\nFor the most part this shouldn't be an issue because the\nSIGQUIT handlers will just do _exit(2) anyway. However,\npgarch.c is a bit out of step. For one thing, its SIGTERM\nhandler has a comment saying the postmaster will never send\nSIGTERM, which needs to be adjusted. For another, its\nSIGQUIT handler does exit(1) not _exit(2), which seems rather\ndubious ... should we make it more like the rest? I think\nthe reasoning there might've been that if some DBA decides to\nSIGQUIT the archiver, we don't need to force a database-wide\nreset; but why exactly should we tolerate that?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 10 Sep 2019 16:01:32 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": true, "msg_subject": "Re: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "From: Tom Lane [mailto:tgl@sss.pgh.pa.us]\n> SIGTERM, which needs to be adjusted. For another, its\n> SIGQUIT handler does exit(1) not _exit(2), which seems rather\n> dubious ... should we make it more like the rest? I think\n> the reasoning there might've been that if some DBA decides to\n> SIGQUIT the archiver, we don't need to force a database-wide\n> reset; but why exactly should we tolerate that?\n\npostmaster doesn't distinguish return codes other than 0 for the archiver, and just starts the archiver unless postmaster is shutting down. So we can use _exit(2) like the other children.\n\nCan't we use SIGKILL instead of SIGINT/SIGTERM to stop the grandchildren, just in case they are slow to respond to or ignore SIGINT/SIGTERM? That matches the idea of pg_ctl's immediate shutdown.\n\n(Windows cannot stop grandchildren because kill() in src/port/kill.c doesn't support the process group... That's a separate topic.)\n\n\nRegards\nTakayuki Tsunakawa\n\n\n\n\n", "msg_date": "Wed, 11 Sep 2019 01:36:15 +0000", "msg_from": "\"Tsunakawa, Takayuki\" <tsunakawa.takay@jp.fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "At Wed, 11 Sep 2019 01:36:15 +0000, \"Tsunakawa, Takayuki\" <tsunakawa.takay@jp.fujitsu.com> wrote in <0A3221C70F24FB45833433255569204D1FD33579@G01JPEXMBYT05>\n> From: Tom Lane [mailto:tgl@sss.pgh.pa.us]\n> > SIGTERM, which needs to be adjusted. For another, its\n> > SIGQUIT handler does exit(1) not _exit(2), which seems rather\n> > dubious ... should we make it more like the rest? I think\n> > the reasoning there might've been that if some DBA decides to\n> > SIGQUIT the archiver, we don't need to force a database-wide\n> > reset; but why exactly should we tolerate that?\n> \n> postmaster doesn't distinguish return codes other than 0 for the archiver, and just starts the archiver unless postmaster is shutting down. So we can use _exit(2) like the other children.\n> \n> Can't we use SIGKILL instead of SIGINT/SIGTERM to stop the grandchildren, just in case they are slow to respond to or ignore SIGINT/SIGTERM? That matches the idea of pg_ctl's immediate shutdown.\n\nPerhaps +1.. immediate -> SIGKILL fast -> SIGTERM?\n\n> (Windows cannot stop grandchildren because kill() in src/port/kill.c doesn't support the process group... That's a separate topic.)\n\nreagards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Wed, 11 Sep 2019 11:01:24 +0900 (Tokyo Standard Time)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "On 9/10/19 9:36 PM, Tsunakawa, Takayuki wrote:\n> From: Tom Lane [mailto:tgl@sss.pgh.pa.us]\n>> SIGTERM, which needs to be adjusted. For another, its\n>> SIGQUIT handler does exit(1) not _exit(2), which seems rather\n>> dubious ... should we make it more like the rest? I think\n>> the reasoning there might've been that if some DBA decides to\n>> SIGQUIT the archiver, we don't need to force a database-wide\n>> reset; but why exactly should we tolerate that?\n> \n> Can't we use SIGKILL instead of SIGINT/SIGTERM to stop the grandchildren, just in case they are slow to respond to or ignore SIGINT/SIGTERM? That matches the idea of pg_ctl's immediate shutdown.\n\n-1, at least not immediately. Archivers can be complex processes and \nthey should be given the chance to do a graceful shutdown.\n\nRegards,\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Tue, 10 Sep 2019 22:11:52 -0400", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "From: David Steele [mailto:david@pgmasters.net]\n> > Can't we use SIGKILL instead of SIGINT/SIGTERM to stop the grandchildren,\n> just in case they are slow to respond to or ignore SIGINT/SIGTERM? That\n> matches the idea of pg_ctl's immediate shutdown.\n> \n> -1, at least not immediately. Archivers can be complex processes and\n> they should be given the chance to do a graceful shutdown.\n\nI agree that the user's archiver program should receive the chance for graceful stop in smart or fast shutdown. But I think in immediate shutdown, all should stop immediately. That's what I expect from the word \"immediate.\"\n\nIf the grandchildren left running don't disturb the cleanup of PostgreSQL's resources (shared memory, file/directory access, etc.) or restart of PostgreSQL, we may well be able to just advice the grandchildren to stop immediately with SIGINT/SIGTERM. However, for example, in the failover of shared-disk HA clustering, when the clustering software stops PostgreSQL with \"pg_ctl stop -m immediate\" and then tries to unmount the file systems for $PGDATA and archived WAL, the unmount may take time or fail due to the access from PostgreSQL's grandchildren.\n\n\nRegards\nTakayuki Tsunakawa\n\n\n\n\n", "msg_date": "Wed, 11 Sep 2019 02:34:59 +0000", "msg_from": "\"Tsunakawa, Takayuki\" <tsunakawa.takay@jp.fujitsu.com>", "msg_from_op": false, "msg_subject": "RE: SIGQUIT on archiver child processes maybe not such a hot idea?" }, { "msg_contents": "At Wed, 11 Sep 2019 11:01:24 +0900 (Tokyo Standard Time), Kyotaro Horiguchi <horikyota.ntt@gmail.com> wrote in <20190911.110124.96874741.horikyota.ntt@gmail.com>\n> At Wed, 11 Sep 2019 01:36:15 +0000, \"Tsunakawa, Takayuki\" <tsunakawa.takay@jp.fujitsu.com> wrote in <0A3221C70F24FB45833433255569204D1FD33579@G01JPEXMBYT05>\n> > From: Tom Lane [mailto:tgl@sss.pgh.pa.us]\n> > > SIGTERM, which needs to be adjusted. For another, its\n> > > SIGQUIT handler does exit(1) not _exit(2), which seems rather\n> > > dubious ... should we make it more like the rest? I think\n> > > the reasoning there might've been that if some DBA decides to\n> > > SIGQUIT the archiver, we don't need to force a database-wide\n> > > reset; but why exactly should we tolerate that?\n> > \n> > postmaster doesn't distinguish return codes other than 0 for the archiver, and just starts the archiver unless postmaster is shutting down. So we can use _exit(2) like the other children.\n> > \n> > Can't we use SIGKILL instead of SIGINT/SIGTERM to stop the grandchildren, just in case they are slow to respond to or ignore SIGINT/SIGTERM? That matches the idea of pg_ctl's immediate shutdown.\n> \n> Perhaps +1.. immediate -> SIGKILL fast -> SIGTERM?\n\nWe send SIGUSR2 to archive while fast shutdown. It would be\nenough for pg_system to do signal(SNGINT, DIG_DFL) andsignal\nsignal(SIGQUIT, SIG_IGN) then remember the child's pid somewhere.\nThen each process send SIGKILL to the remembered process in\nsigquit handler. (I'm not sure what happens if kill(0,\nSIGKILL)).\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Wed, 11 Sep 2019 14:32:56 +0900 (Tokyo Standard Time)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: SIGQUIT on archiver child processes maybe not such a hot idea?" } ]
[ { "msg_contents": "Hi all,\n\nBased on the current clock we are going to be the 1st of September\nanywhere on Earth in approximately 7 hours:\nhttps://www.timeanddate.com/time/zones/aoe\n\nOnce this happens, I will switch the commit fest as in progress and it\nwill not be possible to add any new patches.\n\nI am not sure if somebody would like to volunteer, but I propose\nmyself as commit fest manager for the next session. Feel free to\nreply to this thread if you feel that you could help out as manager\nfor this time.\n\nThanks, and happy hacking!\n--\nMichael", "msg_date": "Sun, 1 Sep 2019 14:15:10 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Commit fest 2019-09" }, { "msg_contents": "On 2019-Sep-01, Michael Paquier wrote:\n\n> I am not sure if somebody would like to volunteer, but I propose\n> myself as commit fest manager for the next session. Feel free to\n> reply to this thread if you feel that you could help out as manager\n> for this time.\n\nHello,\n\nThanks Michael for handling these tasks over the weekend.\n\nI had offered myself as CFM for this one when the cycle started, so I'm\nhappy to do it.\n\nAt this time, the commitfest starts with:\n\n status │ count \n────────────────────────┼───────\n Needs review │ 165\n Waiting on Author │ 30\n Ready for Committer │ 11\n Returned with Feedback │ 1\n Moved to next CF │ 2\n Committed │ 14\n Rejected │ 1\n Withdrawn │ 4\n\nThere's an embarrasingly large number of patches in the \"Bug Fixes\"\nsection. I encourage reviewers to look at those that \"Need Review\" so\nthat they can set \"Ready for Committer\" and get a committer to finish\nthem up:\n status │ count \n─────────────────────┼───────\n Committed │ 2\n Needs review │ 20\n Ready for Committer │ 2\n Waiting on Author │ 4\n Withdrawn │ 1\n\nThanks,\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 2 Sep 2019 09:39:12 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "Hi Alvaro,\n\n\n\n\nOn Mon, Sep 2, 2019 at 6:47 PM Alvaro Herrera <alvherre@2ndquadrant.com>\nwrote:\n\n> On 2019-Sep-01, Michael Paquier wrote:\n>\n> > I am not sure if somebody would like to volunteer, but I propose\n> > myself as commit fest manager for the next session. Feel free to\n> > reply to this thread if you feel that you could help out as manager\n> > for this time.\n>\n> Hello,\n>\n> Thanks Michael for handling these tasks over the weekend.\n>\n> I had offered myself as CFM for this one when the cycle started, so I'm\n> happy to do it.\n>\n> At this time, the commitfest starts with:\n>\n> status │ count\n> ────────────────────────┼───────\n> Needs review │ 165\n> Waiting on Author │ 30\n> Ready for Committer │ 11\n> Returned with Feedback │ 1\n> Moved to next CF │ 2\n> Committed │ 14\n> Rejected │ 1\n> Withdrawn │ 4\n>\n> There's an embarrasingly large number of patches in the \"Bug Fixes\"\n> section. I encourage reviewers to look at those that \"Need Review\" so\n> that they can set \"Ready for Committer\" and get a committer to finish\n> them up:\n> status │ count\n> ─────────────────────┼───────\n> Committed │ 2\n> Needs review │ 20\n> Ready for Committer │ 2\n> Waiting on Author │ 4\n> Withdrawn │ 1\n>\n> Thanks,\n>\n> I think it is a lot of work if you want I can help with that. (Just start\ngetting your messages on threads)\n\n> --\n> Álvaro Herrera https://www.2ndQuadrant.com/\n> PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n>\n>\n>\n\n-- \nIbrar Ahmed\n\nHi Alvaro,On Mon, Sep 2, 2019 at 6:47 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:On 2019-Sep-01, Michael Paquier wrote:\n\n> I am not sure if somebody would like to volunteer, but I propose\n> myself as commit fest manager for the next session.  Feel free to\n> reply to this thread if you feel that you could help out as manager\n> for this time.\n\nHello,\n\nThanks Michael for handling these tasks over the weekend.\n\nI had offered myself as CFM for this one when the cycle started, so I'm\nhappy to do it.\n\nAt this time, the commitfest starts with:\n\n         status         │ count \n────────────────────────┼───────\n Needs review           │   165\n Waiting on Author      │    30\n Ready for Committer    │    11\n Returned with Feedback │     1\n Moved to next CF       │     2\n Committed              │    14\n Rejected               │     1\n Withdrawn              │     4\n\nThere's an embarrasingly large number of patches in the \"Bug Fixes\"\nsection.  I encourage reviewers to look at those that \"Need Review\" so\nthat they can set \"Ready for Committer\" and get a committer to finish\nthem up:\n       status        │ count \n─────────────────────┼───────\n Committed           │     2\n Needs review        │    20\n Ready for Committer │     2\n Waiting on Author   │     4\n Withdrawn           │     1\n\nThanks,\nI think it is a lot of work if you want I can help with that. (Just start getting your messages on threads) \n-- \nÁlvaro Herrera                https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n-- Ibrar Ahmed", "msg_date": "Wed, 4 Sep 2019 02:16:54 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "Hi Ibrar\n\nOn 2019-Sep-04, Ibrar Ahmed wrote:\n\n> On Mon, Sep 2, 2019 at 6:47 PM Alvaro Herrera <alvherre@2ndquadrant.com>\n> wrote:\n\n> > There's an embarrasingly large number of patches in the \"Bug Fixes\"\n> > section. I encourage reviewers to look at those that \"Need Review\" so\n> > that they can set \"Ready for Committer\" and get a committer to finish\n> > them up:\n> > status │ count\n> > ─────────────────────┼───────\n> > Committed │ 2\n> > Needs review │ 20\n> > Ready for Committer │ 2\n> > Waiting on Author │ 4\n> > Withdrawn │ 1\n\n> I think it is a lot of work if you want I can help with that. (Just start\n> getting your messages on threads)\n\nIf you can review bugfix patches, that would certainly be welcome.\n\nThanks,\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 3 Sep 2019 17:35:05 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "On this CF's second week, numbers are:\n\n statusstring │ week1 │ week2\n────────────────────────┼───────┼───────\n Needs review │ 165 │ 138\n Waiting on Author │ 30 │ 44\n Ready for Committer │ 11 │ 5\n Returned with Feedback │ 1 │ 4\n Moved to next CF │ 2 │ 4\n Committed │ 14 │ 23\n Rejected │ 1 │ 1\n Withdrawn │ 4 │ 9\n(8 filas)\n\nOne of the \"withdrawn\" ones was a duplicate entry (2087) for a bugfix patch\n(1970).\n\nWe cleared a large fraction of the patches that were waiting on\ncommitters. It seems that we now need people (including committers) to\nfocus on patches that are \"Needs Review\". I marked a bunch of those as\nWaiting-on-Author; patch authors have a lot of pending work.\n\nHere's the set of patches Ready-for-Committer. Note the majority is\npgbench-related:\n\n patch_id │ name \n──────────┼───────────────────────────────────────────────────────────────\n 2217 │ pgbench - allow to create partitioned \"account\" tables\n 2069 │ Expose queryid in pg_stat_activity in log_line_prefix\n 2086 │ pgbench - extend initialization phase control\n 1736 │ pgbench - add pseudo-random permutation function\n 2091 │ pgbench - add \\aset to store results of combined queries (\\;)\n\nI am inclined to think that 2217 is clearly something we want; 1736 is\nsomething we probably want; and 2086 and 2091 are on the verge of being\nunwanted things.\n\nWe have a number of apparently actionable bugfixes still:\n\n patch_id │ statusstring │ name \n──────────┼───────────────────┼────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n 2224 │ Needs review │ Race condition in logical walsender causes long postgresql shutdown delay\n 2026 │ Needs review │ Spurious \"apparent wraparound\" via SimpleLruTruncate() rounding (data loss)\n 2179 │ Needs review │ Fix support for hypothetical indexes using BRIN access method\n 2187 │ Needs review │ Duplicated LSN in ReorderBuffer\n 2221 │ Needs review │ Add mandatory access control for TRUNCATE\n 2044 │ Needs review │ propagating replica identity to partitions\n 528 │ Needs review │ Fix the optimization to skip WAL-logging on table created in same transaction\n 2025 │ Needs review │ SimpleLruTruncate() mutual exclusion (data loss from lack thereof)\n 1995 │ Needs review │ Replica with large recovery_min_apply_delay is not receiving changes from master after restart until this delay is expired\n 2215 │ Needs review │ pg_upgrade fails with non-standard ACL\n 2266 │ Needs review │ Fix up partitionwise join on how equi-join conditions between the partition keys are identified\n 2050 │ Needs review │ Fix unique join costings\n 2062 │ Needs review │ Unaccent extension python script Issue in Windows\n 2205 │ Needs review │ CVE-2017-7484-induced bugs, or, btree cmp functions are not leakproof?\n 2054 │ Needs review │ fix for BUG #3720: wrong results at using ltree\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 9 Sep 2019 10:37:35 -0300", "msg_from": "Alvaro Herrera from 2ndQuadrant <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "The third week for this commitfest starts. The numbers now:\n\n statusstring │ week1 │ week2 │ week3\n────────────────────────┼───────┼───────┼───────\n Needs review │ 165 │ 138 │ 116\n Waiting on Author │ 30 │ 44 │ 51\n Ready for Committer │ 11 │ 5 │ 8\n Returned with Feedback │ 1 │ 4 │ 5\n Moved to next CF │ 2 │ 4 │ 4\n Committed │ 14 │ 23 │ 32\n Rejected │ 1 │ 1 │ 1\n Withdrawn │ 4 │ 9 │ 11\n(8 filas)\n\nIt seems to me that we're moving forward at a decent pace, if not super\nfast. At least, we're keeping patch authors busy! The number of\npatches waiting on committers are steadily low, which seems to be saying\nthat committers are making a pretty decent job at the final instance for\npatches. Still, there's a lot of stuff that just sits there ... and of\ncourse committers could help with that also.\n\nThat said, we do need non-committer contributors to review other\npeople's patches. Please do your part and review patches of at least\nequivalent complexity to the patches you're submitting!\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 16 Sep 2019 11:24:46 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "On 2019-Sep-16, Alvaro Herrera wrote:\n\n> The third week for this commitfest starts. The numbers now:\n> \n> statusstring │ week1 │ week2 │ week3\n> ────────────────────────┼───────┼───────┼───────\n> Needs review │ 165 │ 138 │ 116\n> Waiting on Author │ 30 │ 44 │ 51\n\nFWIW I have just went over all the waiting-on-author patches and marked\na few as needs-review in cases where new versions had been posted and CF\napp had not been updated. So now we have NR: 127, WoA: 40.\n\nPatch authors, please make sure to update the status of your patch in\nthe CF app when posting new versions!\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 18 Sep 2019 12:31:18 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "Hello\n\nThe fourth week of this commitfest begins with these numbers:\n\n statusstring │ week1 │ week2 │ week3 │ week4\n────────────────────────┼───────┼───────┼───────┼───────\n Needs review │ 165 │ 138 │ 116 │ 118\n Waiting on Author │ 30 │ 44 │ 51 │ 44\n Ready for Committer │ 11 │ 5 │ 8 │ 11\n Returned with Feedback │ 1 │ 4 │ 5 │ 5\n Moved to next CF │ 2 │ 4 │ 4 │ 4\n Committed │ 14 │ 23 │ 32 │ 34\n Rejected │ 1 │ 1 │ 1 │ 1\n Withdrawn │ 4 │ 9 │ 11 │ 11\n\nProgress last week is disappointing. I hope we manage to get more patches\nclosed this week.\n\nIn terms of bugfixes, this is how we started the month:\n\n status │ week1 │ week4 \n────────────────────────┼───────┼───────\n Needs review │ 20 │ 10\n Waiting on Author │ 4 │ 6\n Ready for Committer │ 2 │ 1\n Returned with Feedback │ 0 │ 1\n Moved to next CF │ 0 │ 1\n Committed │ 2 │ 6\n Withdrawn │ 1 │ 2\n\nWe've not made a lot of progress here either, only four bugfix patches\ncommitted in three weeks :-(\n\nIn terms of patch author participation in reviewing other people's\npatches, the metrics are decidedly disappointing. Strongest reviewers,\ncounting replies on threads for patches other than one's own:\n\n* Michael Paquier\n* Álvaro Herrera (discounting \"please rebase\" / \"marked WoA\" pings)\n* Amit Kapila\n* Tom Lane\n\nEveryone is welcome to join the party!\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 23 Sep 2019 12:12:13 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "Pencils down!\n\nCommitfest now has officially ended, and here are some numbers:\n\n statusstring │ week1 │ week2 │ week3 │ week4 │ count \n────────────────────────┼───────┼───────┼───────┼───────┼───────\n Needs review │ 165 │ 138 │ 116 │ 118 │ 117\n Waiting on Author │ 30 │ 44 │ 51 │ 44 │ 39\n Ready for Committer │ 11 │ 5 │ 8 │ 11 │ 9\n Returned with Feedback │ 1 │ 4 │ 5 │ 5 │ 8\n Moved to next CF │ 2 │ 4 │ 4 │ 4 │ 5\n Committed │ 14 │ 23 │ 32 │ 34 │ 38\n Rejected │ 1 │ 1 │ 1 │ 1 │ 1\n Withdrawn │ 4 │ 9 │ 11 │ 11 │ 11\n\nThis fourth week was almost as disappointing as the previous one; only\nfour CF entries got marked committed. I attribute that to the fact that\nwe have one of our most active committers busy with the pg12 release,\nand most of the other committers are not paying any attention to the\ncommitfest, instead spending their time developing other patches (I\nsuppose that means our future still looks bright, but in CF terms it's\nstill sad.)\n\nWe made no progress at all on bugfixes this week -- numbers are\nidentical to the past one.\n\nOn the bright side, a lot of non-committer reviewers seem to have become\nmore active -- in a subjective look, quite a few patches look better now\nthan they did a week ago. Also, patch authors seem to have become more\nengaged, so there aren't as many patches that don't even apply.\n\nI will be spending some time today marking patches that weren't updated\nin time as returned-with-feedback, and moving others to the next\ncommitfest, and then I'll close this commitfest. I'll be also trying to\ncommit a couple of pending patches, so I may yet provide one last\nupdate.\n\nThanks everyone,\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 30 Sep 2019 11:50:31 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "I've closed the following items as Returned with Feedback. These were\nall Waiting-on-Author for a long time, with no new versions posted. In\nmost cases these are still patches that appear to be useful ... but if\nthey're not kept updated to feedback, they're clutter in the CF system.\n\n patch_id │ author │ name \n──────────┼────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────\n 1854 │ Aya Iwata │ libpq trace log\n 2268 │ Ian Barwick │ psql: add tab completion for \\df slash command suffixes\n 1796 │ Chris Travers │ documenting signal handling with readme\n 2051 │ Karl Pinc │ DOC: Document encode() and decode() base64 encoding\n 2060 │ takuma hoshiai │ suppress errors thrown by to_reg*()\n 2082 │ Sandro Mani │ Mingw: Fix import library extension, build actual static libraries\n 2095 │ Daniel Gustafsson │ pg_upgrade version and path checking\n 2148 │ Timur Birsh │ vacuumlo: report the number of large objects going to be removed\n 2223 │ Daniel Migowski │ Adding column \"mem_usage\" to view pg_prepared_statements\n 2028 │ Mike Palmiotto │ Flexible partition pruning hook\n 2108 │ Thomas Munro │ Parallel-aware file_fdw\n 944 │ Nikhil Sontakke │ Logical decoding of two-phase transactions\n 1961 │ Petr Jelínek │ Synchronizing slots from primary to standby\n 2167 │ Peter Eisentraut │ unlogged sequences\n 2124 │ Matwey V. Kornilov │ Introduce spgist quadtree @<(point,circle) operator\n 1533 │ Matheus Oliveira │ Add support for ON UPDATE/DELETE actions on ALTER CONSTRAINT\n 2034 │ Takamichi Osumi │ extension patch of CREATE OR REPLACE TRIGGER\n\nIf somebody wants co-authorship for a patch whose author seems\nunresponsive, I suggest to ping them about that and run with it if they\ndon't respond in a reasonable timeframe.\n\n(There were a few others patches Waiting-on-Author, but these didn't\nlook as stale. I didn't touch anything in the bugfixes section either.)\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 30 Sep 2019 15:28:18 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "On 2019-Sep-30, Alvaro Herrera wrote:\n\n> I've closed the following items as Returned with Feedback. These were\n> all Waiting-on-Author for a long time, with no new versions posted. In\n> most cases these are still patches that appear to be useful ... but if\n> they're not kept updated to feedback, they're clutter in the CF system.\n\nSome more returned with feedback:\n\n patch_id │ author │ name \n──────────┼────────────────────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────\n 1294 │ Ildus Kurbangaliev │ Custom compression methods\n 1695 │ Takeshi Ideriha │ Global shared meta cache\n 2166 │ Takeshi Ideriha │ Shared memory context\n 2043 │ Jeff Janes │ Bloom index cost model\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 30 Sep 2019 16:12:38 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "Hello,\n\nAfter closing a few patches that have been dead for months, and moving\nthe rest to the next commitfest, here's the results:\n\n statusstring │ week1 │ week2 │ week3 │ week4 │ final \n────────────────────────┼───────┼───────┼───────┼───────┼───────\n Needs review │ 165 │ 138 │ 116 │ 118 │ 0\n Waiting on Author │ 30 │ 44 │ 51 │ 44 │ 0\n Ready for Committer │ 11 │ 5 │ 8 │ 11 │ 0\n Returned with Feedback │ 1 │ 4 │ 5 │ 5 │ 28\n Moved to next CF │ 2 │ 4 │ 4 │ 4 │ 191\n Committed │ 14 │ 23 │ 32 │ 34 │ 42\n Rejected │ 1 │ 1 │ 1 │ 1 │ 1\n Withdrawn │ 4 │ 9 │ 11 │ 11 │ 12\n\nThis means we got 28 patches committed during this month ... which is\na rather concerningly low figure. I really hope we can do much better\nin the upcoming three commitfests -- at least, we're not going to have\na stable release at the same time.\n\nAnd with that, I've closed the commitfest. I know there's still\ntechnically a few hours left ... but if anyone wants to commit one more\npatch, they can mark it committed in the next commitfest without\nremorse.\n\nThanks everyone,\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 30 Sep 2019 16:24:15 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "On Mon, Sep 30, 2019 at 04:24:15PM -0300, Alvaro Herrera wrote:\n> Hello,\n> \n> After closing a few patches that have been dead for months, and moving\n> the rest to the next commitfest, here's the results:\n> \n> statusstring │ week1 │ week2 │ week3 │ week4 │ final \n> ────────────────────────┼───────┼───────┼───────┼───────┼───────\n> Needs review │ 165 │ 138 │ 116 │ 118 │ 0\n> Waiting on Author │ 30 │ 44 │ 51 │ 44 │ 0\n> Ready for Committer │ 11 │ 5 │ 8 │ 11 │ 0\n> Returned with Feedback │ 1 │ 4 │ 5 │ 5 │ 28\n> Moved to next CF │ 2 │ 4 │ 4 │ 4 │ 191\n> Committed │ 14 │ 23 │ 32 │ 34 │ 42\n> Rejected │ 1 │ 1 │ 1 │ 1 │ 1\n> Withdrawn │ 4 │ 9 │ 11 │ 11 │ 12\n> \n> This means we got 28 patches committed during this month ... which is\n> a rather concerningly low figure. I really hope we can do much better\n> in the upcoming three commitfests -- at least, we're not going to have\n> a stable release at the same time.\n> \n> And with that, I've closed the commitfest. I know there's still\n> technically a few hours left ... but if anyone wants to commit one more\n> patch, they can mark it committed in the next commitfest without\n> remorse.\n> \n> Thanks everyone,\n\nThanks for doing all this work!\n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate\n\n\n", "msg_date": "Mon, 30 Sep 2019 23:26:58 +0200", "msg_from": "David Fetter <david@fetter.org>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "On 9/30/19 5:26 PM, David Fetter wrote:\n> \n> Thanks for doing all this work!\n\n+1!\n\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Mon, 30 Sep 2019 18:20:31 -0400", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "On Tue, Oct 1, 2019 at 12:54 AM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\r\n>\r\n> Hello,\r\n>\r\n> After closing a few patches that have been dead for months, and moving\r\n> the rest to the next commitfest, here's the results:\r\n>\r\n> statusstring │ week1 │ week2 │ week3 │ week4 │ final\r\n> ────────────────────────┼───────┼───────┼───────┼───────┼───────\r\n> Needs review │ 165 │ 138 │ 116 │ 118 │ 0\r\n> Waiting on Author │ 30 │ 44 │ 51 │ 44 │ 0\r\n> Ready for Committer │ 11 │ 5 │ 8 │ 11 │ 0\r\n> Returned with Feedback │ 1 │ 4 │ 5 │ 5 │ 28\r\n> Moved to next CF │ 2 │ 4 │ 4 │ 4 │ 191\r\n> Committed │ 14 │ 23 │ 32 │ 34 │ 42\r\n> Rejected │ 1 │ 1 │ 1 │ 1 │ 1\r\n> Withdrawn │ 4 │ 9 │ 11 │ 11 │ 12\r\n>\r\n> This means we got 28 patches committed during this month ... which is\r\n> a rather concerningly low figure.\r\n>\r\n\r\nYes, I agree that we can improve these numbers. However, like others,\r\nI would also like to thank you for sincere and dedicated efforts in\r\nthis CF. It really helps in moving things forward.\r\n\r\n-- \r\nWith Regards,\r\nAmit Kapila.\r\nEnterpriseDB: http://www.enterprisedb.com\r\n", "msg_date": "Tue, 1 Oct 2019 08:03:44 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Commit fest 2019-09" }, { "msg_contents": "On Mon, Sep 30, 2019 at 06:20:31PM -0400, David Steele wrote:\n> On 9/30/19 5:26 PM, David Fetter wrote:\n>> \n>> Thanks for doing all this work!\n> \n> +1!\n\nThanks, Alvaro!\n--\nMichael", "msg_date": "Tue, 1 Oct 2019 16:15:29 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": true, "msg_subject": "Re: Commit fest 2019-09" } ]
[ { "msg_contents": "Hi!\n\nI found it weird that CLUSTER/VACUUM FULL don't write visibility map.\nAttached patch implements writing visibility map in\nheapam_relation_copy_for_cluster().\n\nI've studied previous attempt to implement this [1]. The main problem\nof that attempt was usage of existing heap_page_is_all_visible() and\nvisibilitymap_set() functions. These functions works through buffer\nmanager, while heap rewriting is made bypass buffer manager.\n\nIn my patch visibility map pages are handled in the same way as heap\npages are. RewriteStateData holds contents of single VM page. Once\nheap page is finished, corresponding bits are set to VM page etc. VM\npages are flushed one-by-one to smgr.\n\nThis patch have to implement its own check if tuple is allvisible.\nBut it appears to be possible to simplify this check assuming that all\ntuples already past HeapTupleSatisfiesVacuum(), which sets hint bits.\n\nLinks\n1. https://www.postgresql.org/message-id/flat/20131203162556.GC27105%40momjian.us#90e4a6e77d92076650dcf1d96b32ba38\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Sun, 1 Sep 2019 11:07:31 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "On Sun, Sep 1, 2019 at 11:07 AM Alexander Korotkov\n<a.korotkov@postgrespro.ru> wrote:\n> This patch have to implement its own check if tuple is allvisible.\n> But it appears to be possible to simplify this check assuming that all\n> tuples already past HeapTupleSatisfiesVacuum(), which sets hint bits.\n\nForgot to check tuple xmin against oldest xmin. Fixed.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Sun, 1 Sep 2019 20:05:42 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "On Sun, Sep 1, 2019 at 1:37 PM Alexander Korotkov\n<a.korotkov@postgrespro.ru> wrote:\n>\n> Hi!\n>\n> I found it weird that CLUSTER/VACUUM FULL don't write visibility map.\n> Attached patch implements writing visibility map in\n> heapam_relation_copy_for_cluster().\n>\n> I've studied previous attempt to implement this [1]. The main problem\n> of that attempt was usage of existing heap_page_is_all_visible() and\n> visibilitymap_set() functions. These functions works through buffer\n> manager, while heap rewriting is made bypass buffer manager.\n>\n> In my patch visibility map pages are handled in the same way as heap\n> pages are.\n>\n\nI haven't studied this patch in detail, but while glancing I observed\nthat this doesn't try to sync the vm pages as we do for heap pages in\nthe end (during end_heap_rewrite). Am I missing something?\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Wed, 11 Sep 2019 18:00:09 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "On Wed, Sep 11, 2019 at 3:30 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> On Sun, Sep 1, 2019 at 1:37 PM Alexander Korotkov\n> <a.korotkov@postgrespro.ru> wrote:\n> > I found it weird that CLUSTER/VACUUM FULL don't write visibility map.\n> > Attached patch implements writing visibility map in\n> > heapam_relation_copy_for_cluster().\n> >\n> > I've studied previous attempt to implement this [1]. The main problem\n> > of that attempt was usage of existing heap_page_is_all_visible() and\n> > visibilitymap_set() functions. These functions works through buffer\n> > manager, while heap rewriting is made bypass buffer manager.\n> >\n> > In my patch visibility map pages are handled in the same way as heap\n> > pages are.\n> >\n>\n> I haven't studied this patch in detail, but while glancing I observed\n> that this doesn't try to sync the vm pages as we do for heap pages in\n> the end (during end_heap_rewrite). Am I missing something?\n\nYou're not missed anything. Yes, VM need sync. Will fix this. And I\njust noticed I need a closer look to what is going on with TOAST.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Thu, 12 Sep 2019 16:55:04 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "On Thu, Sep 12, 2019 at 4:55 PM Alexander Korotkov\n<a.korotkov@postgrespro.ru> wrote:\n> On Wed, Sep 11, 2019 at 3:30 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > On Sun, Sep 1, 2019 at 1:37 PM Alexander Korotkov\n> > <a.korotkov@postgrespro.ru> wrote:\n> > > I found it weird that CLUSTER/VACUUM FULL don't write visibility map.\n> > > Attached patch implements writing visibility map in\n> > > heapam_relation_copy_for_cluster().\n> > >\n> > > I've studied previous attempt to implement this [1]. The main problem\n> > > of that attempt was usage of existing heap_page_is_all_visible() and\n> > > visibilitymap_set() functions. These functions works through buffer\n> > > manager, while heap rewriting is made bypass buffer manager.\n> > >\n> > > In my patch visibility map pages are handled in the same way as heap\n> > > pages are.\n> > >\n> >\n> > I haven't studied this patch in detail, but while glancing I observed\n> > that this doesn't try to sync the vm pages as we do for heap pages in\n> > the end (during end_heap_rewrite). Am I missing something?\n>\n> You're not missed anything. Yes, VM need sync. Will fix this. And I\n> just noticed I need a closer look to what is going on with TOAST.\n\nAttached patch syncs VM during end_heap_rewrite().\n\nHowever, VM for TOAST still isn't read. It appear to be much more\ndifficult to write VM for TOAST, because it's written by insertion\ntuples one-by-one. Despite it seems to fill TOAST heap pages\nsequentially (assuming no FSM exists yet), it's quite hard to handle\npage-switching event with reasonable level of abstraction.\nNevertheless, I find this patch useful in current shape. Even if we\ndon't write VM for TOAST, it's still useful to do for regular heap.\nAdditionally, one of key advantages of having VM is index-only scan,\nwhich don't work for TOAST anyway.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 13 Sep 2019 22:22:50 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "Hi,\n\nOn 2019-09-13 22:22:50 +0300, Alexander Korotkov wrote:\n> On Thu, Sep 12, 2019 at 4:55 PM Alexander Korotkov\n> <a.korotkov@postgrespro.ru> wrote:\n> > On Wed, Sep 11, 2019 at 3:30 PM Amit Kapila <amit.kapila16@gmail.com> wrote:\n> > > On Sun, Sep 1, 2019 at 1:37 PM Alexander Korotkov\n> > > <a.korotkov@postgrespro.ru> wrote:\n> > > > I found it weird that CLUSTER/VACUUM FULL don't write visibility map.\n> > > > Attached patch implements writing visibility map in\n> > > > heapam_relation_copy_for_cluster().\n> > > >\n> > > > I've studied previous attempt to implement this [1]. The main problem\n> > > > of that attempt was usage of existing heap_page_is_all_visible() and\n> > > > visibilitymap_set() functions. These functions works through buffer\n> > > > manager, while heap rewriting is made bypass buffer manager.\n> > > >\n> > > > In my patch visibility map pages are handled in the same way as heap\n> > > > pages are.\n\nWhy do you want to do that? To me that doesn't immediately seems like a\ngood idea, and I've not seen justification for it in this thread. Did I\nmiss something?\n\n\n> > > I haven't studied this patch in detail, but while glancing I observed\n> > > that this doesn't try to sync the vm pages as we do for heap pages in\n> > > the end (during end_heap_rewrite). Am I missing something?\n> >\n> > You're not missed anything. Yes, VM need sync. Will fix this. And I\n> > just noticed I need a closer look to what is going on with TOAST.\n> \n> Attached patch syncs VM during end_heap_rewrite().\n> \n> However, VM for TOAST still isn't read. It appear to be much more\n> difficult to write VM for TOAST, because it's written by insertion\n> tuples one-by-one. Despite it seems to fill TOAST heap pages\n> sequentially (assuming no FSM exists yet), it's quite hard to handle\n> page-switching event with reasonable level of abstraction.\n> Nevertheless, I find this patch useful in current shape. Even if we\n> don't write VM for TOAST, it's still useful to do for regular heap.\n> Additionally, one of key advantages of having VM is index-only scan,\n> which don't work for TOAST anyway.\n\nHave you looked at the discussion around\nhttps://www.postgresql.org/message-id/20190408010427.4l63qr7h2fjcyp77%40alap3.anarazel.de\n?\n\nThat's not quite the same thing as you're tackling here, but I wonder if\nsome of the logic could be the same. Especially for toast.\n\n\n> +/* Write contents of VM page */\n> +static void\n> +rewrite_flush_vm_page(RewriteState state)\n> +{\n> +\tAssert(state->rs_vm_buffer_valid);\n> +\n> +\tif (state->rs_use_wal)\n> +\t\tlog_newpage(&state->rs_new_rel->rd_node,\n> +\t\t\t\t\tVISIBILITYMAP_FORKNUM,\n> +\t\t\t\t\tstate->rs_vm_blockno,\n> +\t\t\t\t\tstate->rs_vm_buffer,\n> +\t\t\t\t\ttrue);\n> +\tRelationOpenSmgr(state->rs_new_rel);\n> +\n> +\tPageSetChecksumInplace(state->rs_vm_buffer, state->rs_vm_blockno);\n> +\n> +\tsmgrextend(state->rs_new_rel->rd_smgr, VISIBILITYMAP_FORKNUM,\n> +\t\t\t state->rs_vm_blockno, (char *) state->rs_vm_buffer, true);\n> +\n> +\tstate->rs_vm_buffer_valid = false;\n> +}\n> +\n> +/* Set VM flags to the VM page */\n> +static void\n> +rewrite_set_vm_flags(RewriteState state)\n> +{\n> +\tBlockNumber mapBlock = HEAPBLK_TO_MAPBLOCK(state->rs_blockno);\n> +\tuint32\t\tmapByte = HEAPBLK_TO_MAPBYTE(state->rs_blockno);\n> +\tuint8\t\tmapOffset = HEAPBLK_TO_OFFSET(state->rs_blockno);\n> +\tchar\t *map;\n> +\tuint8\t\tflags;\n> +\n> +\tif (mapBlock != state->rs_vm_blockno && state->rs_vm_buffer_valid)\n> +\t\trewrite_flush_vm_page(state);\n> +\n> +\tif (!state->rs_vm_buffer_valid)\n> +\t{\n> +\t\tPageInit(state->rs_vm_buffer, BLCKSZ, 0);\n> +\t\tstate->rs_vm_blockno = mapBlock;\n> +\t\tstate->rs_vm_buffer_valid = true;\n> +\t}\n> +\n> +\tflags = (state->rs_all_visible ? VISIBILITYMAP_ALL_VISIBLE : 0) |\n> +\t\t\t(state->rs_all_frozen ? VISIBILITYMAP_ALL_FROZEN : 0);\n> +\n> +\tmap = PageGetContents(state->rs_vm_buffer);\n> +\tmap[mapByte] |= (flags << mapOffset);\n> +}\n\nI think it's a bad idea to copy this many VM implementation details into\nrewriteheap.c.\n\n\n> +/*\n> + * Update rs_all_visible and rs_all_frozen flags according to the tuple. We\n> + * use simplified check assuming that HeapTupleSatisfiesVacuum() should already\n> + * set tuple hint bits.\n> + */\n> +static void\n> +rewrite_update_vm_flags(RewriteState state, HeapTuple tuple)\n> +{\n> +\tTransactionId\txmin;\n> +\n> +\tif (!state->rs_all_visible)\n> +\t\treturn;\n> +\n> +\tif (!HeapTupleHeaderXminCommitted(tuple->t_data))\n> +\t{\n> +\t\tstate->rs_all_visible = false;\n> +\t\tstate->rs_all_frozen = false;\n> +\t\treturn;\n> +\t}\n> +\n> +\txmin = HeapTupleHeaderGetXmin(tuple->t_data);\n> +\tif (!TransactionIdPrecedes(xmin, state->rs_oldest_xmin))\n> +\t{\n> +\t\tstate->rs_all_visible = false;\n> +\t\tstate->rs_all_frozen = false;\n> +\t\treturn;\n> +\t}\n> +\n> +\tif (!(tuple->t_data->t_infomask & HEAP_XMAX_INVALID) &&\n> +\t\t!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask))\n> +\t{\n> +\t\tstate->rs_all_visible = false;\n> +\t\tstate->rs_all_frozen = false;\n> +\t\treturn;\n> +\t}\n> +\n> +\tif (!state->rs_all_frozen)\n> +\t\treturn;\n> +\n> +\tif (heap_tuple_needs_eventual_freeze(tuple->t_data))\n> +\t\tstate->rs_all_frozen = false;\n> +}\n\nI don't think we should have yet another copy of logic determining\nvisibility. It has repeatedly proven hard to get right in the past, and\nit'll not get better by having yet another copy. Especially not because\nwe've basically already done a HTSV (via\nheapam_relation_copy_for_cluster), and we're now redoing a poor man's\nversion of it.\n\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Fri, 20 Sep 2019 13:05:06 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "On Fri, Sep 20, 2019 at 01:05:06PM -0700, Andres Freund wrote:\n> I don't think we should have yet another copy of logic determining\n> visibility. It has repeatedly proven hard to get right in the past, and\n> it'll not get better by having yet another copy. Especially not because\n> we've basically already done a HTSV (via\n> heapam_relation_copy_for_cluster), and we're now redoing a poor man's\n> version of it.\n\nThese comments are unanswered for more than 2 months, so I am marking\nthis entry as returned with feedback. Please feel free to change if\nyou think that's not adapted.\n--\nMichael", "msg_date": "Fri, 29 Nov 2019 11:32:15 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "On 2019-11-29 05:32, Michael Paquier wrote:\n> These comments are unanswered for more than 2 months, so I am marking\n> this entry as returned with feedback.\n\nI'd like to revive this patch. To make further work easier, attaching a \nrebased version of the latest patch by Alexander.\n\nAs for having yet another copy of logic determining visibility: the \nvisibility check was mainly taken from heap_page_is_all_visible(), so I \nrefactored the code to make sure that logic is not duplicated. The \nupdated patch is attached too.\n\n-- \nAnna Akenteva\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Mon, 28 Jun 2021 11:22:01 +0300", "msg_from": "Anna Akenteva <a.akenteva@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "On Mon, Jun 28, 2021 at 1:52 PM Anna Akenteva <a.akenteva@postgrespro.ru> wrote:\n>\n> On 2019-11-29 05:32, Michael Paquier wrote:\n> > These comments are unanswered for more than 2 months, so I am marking\n> > this entry as returned with feedback.\n>\n> I'd like to revive this patch. To make further work easier, attaching a\n> rebased version of the latest patch by Alexander.\n>\n> As for having yet another copy of logic determining visibility: the\n> visibility check was mainly taken from heap_page_is_all_visible(), so I\n> refactored the code to make sure that logic is not duplicated. The\n> updated patch is attached too.\n\nThe patch does not apply on Head anymore, could you rebase and post a\npatch. I'm changing the status to \"Waiting for Author\".\n\nRegards,\nVignesh\n\n\n", "msg_date": "Wed, 14 Jul 2021 17:16:31 +0530", "msg_from": "vignesh C <vignesh21@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "On Mon, Jun 28, 2021 at 11:22:01AM +0300, Anna Akenteva wrote:\n> On 2019-11-29 05:32, Michael Paquier wrote:\n> > These comments are unanswered for more than 2 months, so I am marking\n> > this entry as returned with feedback.\n> \n> I'd like to revive this patch. To make further work easier, attaching a\n> rebased version of the latest patch by Alexander.\n> \n> As for having yet another copy of logic determining visibility: the\n> visibility check was mainly taken from heap_page_is_all_visible(), so I\n> refactored the code to make sure that logic is not duplicated. The updated\n> patch is attached too.\n\nI agree that it's strange that VACUUM(FREEZE) freezes tuples but not VM bits,\nnor page-level PD_ALL_VISIBLE (which is implied by all frozen). After FULL\nruns (taking an exclusive lock on the table), it's necessary to then vacuum the\ntable again to get what's intended.\n\nRebased on f10f0ae420ee62400876ab34dca2c09c20dcd030.\n\nAnd rephrased Anna's two independent/alternate patches as a 2nd patch on top of\nthe 1st, as that helps me to read it and reduces its total size.\n\nI noticed in testing the patch that autovacuum is still hitting the relation\nshortly after vacuum full. This is due to n_ins_since_autovacuum, which is new\nin pg13. I don't know how to address that (or even if it should be addressed\nat all).\n\nAlso, pg_class.relallvisible is not set unless vacuum/analyze is run again\n(which is mitigated by the n_ins behavior above). It seems like this might be\nimportant: an plan which uses index-only scan might be missed in favour of\nsomething else until autovacuum runs (it will use cost-based delay, and might\nnot be scheduled immediately, could be interrupted, or even diasbled).\n\nI'm testing like this:\nCREATE EXTENSION IF NOT EXISTS pg_visibility ; DROP TABLE t; CREATE TABLE t AS SELECT generate_series(1,99999); VACUUM FULL t; ANALYZE t; SELECT n_ins_since_vacuum, n_tup_upd, n_tup_del, n_tup_hot_upd FROM pg_stat_all_tables WHERE relname='t'; SELECT relpages, relallvisible FROM pg_class WHERE oid='t'::regclass; SELECT COUNT(1), COUNT(1)FILTER(WHERE all_visible='t') allvis, COUNT(1)FILTER(WHERE all_frozen='t') allfrz, COUNT(1)FILTER(WHERE pd_all_visible='t') allvispd FROM pg_visibility('t');\n\n-- \nJustin", "msg_date": "Sun, 29 Aug 2021 19:26:42 -0500", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "> On 30 Aug 2021, at 02:26, Justin Pryzby <pryzby@telsasoft.com> wrote:\n\n> Rebased on f10f0ae420ee62400876ab34dca2c09c20dcd030.\n\nThis patch no longer applies, please submit a rebased version.\n\n--\nDaniel Gustafsson\t\thttps://vmware.com/\n\n\n\n", "msg_date": "Mon, 15 Nov 2021 10:27:55 +0100", "msg_from": "Daniel Gustafsson <daniel@yesql.se>", "msg_from_op": false, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "On Sun, Aug 29, 2021 at 07:26:42PM -0500, Justin Pryzby wrote:\n> On Mon, Jun 28, 2021 at 11:22:01AM +0300, Anna Akenteva wrote:\n> > On 2019-11-29 05:32, Michael Paquier wrote:\n> > > These comments are unanswered for more than 2 months, so I am marking\n> > > this entry as returned with feedback.\n> > \n> > I'd like to revive this patch. To make further work easier, attaching a\n> > rebased version of the latest patch by Alexander.\n> > \n> > As for having yet another copy of logic determining visibility: the\n> > visibility check was mainly taken from heap_page_is_all_visible(), so I\n> > refactored the code to make sure that logic is not duplicated. The updated\n> > patch is attached too.\n> \n> I agree that it's strange that VACUUM(FREEZE) freezes tuples but not VM bits,\n> nor page-level PD_ALL_VISIBLE (which is implied by all frozen). After FULL\n> runs (taking an exclusive lock on the table), it's necessary to then vacuum the\n> table again to get what's intended.\n> \n> Rebased on f10f0ae420ee62400876ab34dca2c09c20dcd030.\n\nRebased this patch again\n\nAlexander, are you planning on working on this patch ?\n\nOtherwise, Anna, would you want to \"own\" the patch ?\n\n> And rephrased Anna's two independent/alternate patches as a 2nd patch on top of\n> the 1st, as that helps me to read it and reduces its total size.\n> \n> I noticed in testing the patch that autovacuum is still hitting the relation\n> shortly after vacuum full. This is due to n_ins_since_autovacuum, which is new\n> in pg13. I don't know how to address that (or even if it should be addressed\n> at all).\n> \n> Also, pg_class.relallvisible is not set unless vacuum/analyze is run again\n> (which is mitigated by the n_ins behavior above). It seems like this might be\n> important: an plan which uses index-only scan might be missed in favour of\n> something else until autovacuum runs (it will use cost-based delay, and might\n> not be scheduled immediately, could be interrupted, or even diasbled).\n> \n> I'm testing like this:\n> CREATE EXTENSION IF NOT EXISTS pg_visibility ; DROP TABLE t; CREATE TABLE t AS SELECT generate_series(1,99999); VACUUM FULL t; ANALYZE t; SELECT n_ins_since_vacuum, n_tup_upd, n_tup_del, n_tup_hot_upd FROM pg_stat_all_tables WHERE relname='t'; SELECT relpages, relallvisible FROM pg_class WHERE oid='t'::regclass; SELECT COUNT(1), COUNT(1)FILTER(WHERE all_visible='t') allvis, COUNT(1)FILTER(WHERE all_frozen='t') allfrz, COUNT(1)FILTER(WHERE pd_all_visible='t') allvispd FROM pg_visibility('t');", "msg_date": "Mon, 15 Nov 2021 16:38:56 -0600", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "On Mon, Nov 15, 2021 at 04:38:56PM -0600, Justin Pryzby wrote:\n> On Sun, Aug 29, 2021 at 07:26:42PM -0500, Justin Pryzby wrote:\n> > On Mon, Jun 28, 2021 at 11:22:01AM +0300, Anna Akenteva wrote:\n> > > On 2019-11-29 05:32, Michael Paquier wrote:\n> > > > These comments are unanswered for more than 2 months, so I am marking\n> > > > this entry as returned with feedback.\n> > > \n> > > I'd like to revive this patch. To make further work easier, attaching a\n> > > rebased version of the latest patch by Alexander.\n> > > \n> > > As for having yet another copy of logic determining visibility: the\n> > > visibility check was mainly taken from heap_page_is_all_visible(), so I\n> > > refactored the code to make sure that logic is not duplicated. The updated\n> > > patch is attached too.\n> > \n> > I agree that it's strange that VACUUM(FREEZE) freezes tuples but not VM bits,\n> > nor page-level PD_ALL_VISIBLE (which is implied by all frozen). After FULL\n> > runs (taking an exclusive lock on the table), it's necessary to then vacuum the\n> > table again to get what's intended.\n> > \n> > Rebased on f10f0ae420ee62400876ab34dca2c09c20dcd030.\n> \n> Rebased this patch again\n> \n> Alexander, are you planning on working on this patch ?\n> \n> Otherwise, Anna, would you want to \"own\" the patch ?\n\nRebased on 8e1fae193864527c931a704bd7908e4fbc983f5c.\n\nWould someone step up to \"own\" this patch ?\n\nIf not, its CF entry may need to be closed (there's no status for \"needs\nauthor\").", "msg_date": "Sun, 26 Dec 2021 20:59:31 -0600", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "On Sun, Dec 26, 2021 at 08:59:31PM -0600, Justin Pryzby wrote:\n> Rebased on 8e1fae193864527c931a704bd7908e4fbc983f5c.\n> \n> Would someone step up to \"own\" this patch ?\n> \n> If not, its CF entry may need to be closed (there's no status for \"needs\n> author\").\n\nI'm planning to close this patch until someone can shepherd it.\n\n-- \nJustin\n\n\n", "msg_date": "Thu, 27 Jan 2022 15:58:27 -0600", "msg_from": "Justin Pryzby <pryzby@telsasoft.com>", "msg_from_op": false, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" }, { "msg_contents": "Justin Pryzby <pryzby@telsasoft.com> wrote:\n> I'm planning to close this patch until someone can shepherd it.\n\nI've marked it RwF for now.\n\n--Jacob\n\n\n", "msg_date": "Thu, 30 Jun 2022 11:25:39 -0700", "msg_from": "Jacob Champion <jchampion@timescale.com>", "msg_from_op": false, "msg_subject": "Re: Write visibility map during CLUSTER/VACUUM FULL" } ]
[ { "msg_contents": "Hello\n\npg_stat_statements is a great tool to track performance issue in live \ndatabases, especially when adding interfaces like PoWA on top of it.\nBut so far, tools like PoWA can not track the min_time, max_time, mean_time \nand sum_var_time of queries : these statistics are cumulated over time, \nfetching points in time would be of little to no use, especially when looking \nat the impact of a DDL change.\nThis patch thus introduces a simple pg_stat_statements_reset_computed_values \nfunction that reset the computed statistics, leaving all other information \nalive, thus allowing the aforementioned scenario.\n\nRegards\n\n Pierre Ducroquet", "msg_date": "Sun, 01 Sep 2019 11:04:36 +0200", "msg_from": "Pierre Ducroquet <p.psql@pinaraf.info>", "msg_from_op": true, "msg_subject": "[Patch] Add a reset_computed_values function in pg_stat_statements" }, { "msg_contents": "Em dom, 1 de set de 2019 às 06:04, Pierre Ducroquet\n<p.psql@pinaraf.info> escreveu:\n>\n> Hello\n>\n> pg_stat_statements is a great tool to track performance issue in live\n> databases, especially when adding interfaces like PoWA on top of it.\n> But so far, tools like PoWA can not track the min_time, max_time, mean_time\n> and sum_var_time of queries : these statistics are cumulated over time,\n> fetching points in time would be of little to no use, especially when looking\n> at the impact of a DDL change.\n> This patch thus introduces a simple pg_stat_statements_reset_computed_values\n> function that reset the computed statistics, leaving all other information\n> alive, thus allowing the aforementioned scenario.\n>\nPierre, I don't understand why you want to reset part of the statement\nstatistics. If you want the minimal query time every week, reset all\nstatistics of that statement (v12 or later). Postgres provides\nhistogram metrics (min, max, mean, stddev). AFAICS you want a metric\ntype called timer (combination of histogram and meter). For example,\ncalls, sum, min, max, mean, standard deviation will be calculated each\nhour. If I were to add a new metric to pg_stat_statements, it would be\nlast_time. Compare histogram metrics with the last statement time is\nuseful to check if a certain optimization was effective.\n\nTalking about your patch, math is wrong. If you don't reset\ntotal_time, all computed values will be incorrect. You are changing\nthe actual meaning of those metrics and I think it is unacceptable\nbecause it will break applications. Instead, you should provide (i)\nnew counters or (ii) add GUC to control this behavior. It is a\ntrade-off between incompatibility and too many metrics. Though I\nwouldn't like to break compatibility (as I said you can always reset\nall statement statistics). Why don't you provide a\npg_stat_statements_reset_computed_values(userid Oid, dbid Oid, queryid\nbigint)? You forgot to provide documentation for the new function. You\nshould revoke pg_stat_statements_reset_computed_values from PUBLIC.\n\nRegards,\n\n\n-- \n Euler Taveira Timbira -\nhttp://www.timbira.com.br/\n PostgreSQL: Consultoria, Desenvolvimento, Suporte 24x7 e Treinamento\n\n\n", "msg_date": "Sun, 1 Sep 2019 22:25:00 -0300", "msg_from": "Euler Taveira <euler@timbira.com.br>", "msg_from_op": false, "msg_subject": "Re: [Patch] Add a reset_computed_values function in\n pg_stat_statements" }, { "msg_contents": "On Monday, September 2, 2019 3:25:00 AM CEST Euler Taveira wrote:\n> Em dom, 1 de set de 2019 às 06:04, Pierre Ducroquet\n> \n> <p.psql@pinaraf.info> escreveu:\n> > Hello\n> > \n> > pg_stat_statements is a great tool to track performance issue in live\n> > databases, especially when adding interfaces like PoWA on top of it.\n> > But so far, tools like PoWA can not track the min_time, max_time,\n> > mean_time\n> > and sum_var_time of queries : these statistics are cumulated over time,\n> > fetching points in time would be of little to no use, especially when\n> > looking at the impact of a DDL change.\n> > This patch thus introduces a simple\n> > pg_stat_statements_reset_computed_values function that reset the computed\n> > statistics, leaving all other information alive, thus allowing the\n> > aforementioned scenario.\n> \n\nHello\n\nThank you for reviewing this patch.\n\n> Pierre, I don't understand why you want to reset part of the statement\n> statistics. If you want the minimal query time every week, reset all\n> statistics of that statement (v12 or later). Postgres provides\n> histogram metrics (min, max, mean, stddev). AFAICS you want a metric\n> type called timer (combination of histogram and meter). For example,\n> calls, sum, min, max, mean, standard deviation will be calculated each\n> hour. If I were to add a new metric to pg_stat_statements, it would be\n> last_time. Compare histogram metrics with the last statement time is\n> useful to check if a certain optimization was effective.\n\nmin/max/mean timing in pg_stat_statements are *computed* fields, not simple \ncumulative ones, hence the distinction I do here. For a tool like PoWA, that \n(to simplify) copies all the statistics every few minutes to do its own \ncomputation, it makes it impossible to get any sense out of them. The facility \nto reset all statistics is an option, but it feels like an heavy solution when \nonly some statistics are different from the others.\n\n> Talking about your patch, math is wrong. If you don't reset\n> total_time, all computed values will be incorrect. You are changing\n> the actual meaning of those metrics and I think it is unacceptable\n> because it will break applications. \n\nI think you misunderstood the way this patch is written.\ntotal_time, in this function, is not a global statistics: pgss_store receive \nthe total time of the current query. When the computed statistics are reset, \nwe simply drop them and start them fresh from the first query. There is \nabsolutely no compatibility impact here.\n\n> Instead, you should provide (i) new counters or (ii) add GUC to control this\n> behavior. It is a trade-off between incompatibility and too many metrics.\n> Though I wouldn't like to break compatibility (as I said you can always\n> reset all statement statistics). \n\nAs explained: it does not break compatibility, I don't see a need for a new \nGUC.\n\n> Why don't you provide a pg_stat_statements_reset_computed_values(userid Oid,\n> dbid Oid, queryid bigint)?\n\nBecause I did not need one, and with pg_stat_statements_reset(userid Oid, dbid \nOid, queryid bigint) being newly added, I did not think about it.\nI can add one in a new version of the patch of course.\n\n> You forgot to provide documentation for the new function.\n\nIndeed, I am not very used to SGML and first wanted a discussion about the \nfeature.\n\n> You should revoke pg_stat_statements_reset_computed_values from PUBLIC.\n\nIndeed, I missed that one.\n\nAttached to this mail is a new version fixing the revoke issue, and adding \ndocumentation.\n\n\nRegards\n\n Pierre", "msg_date": "Tue, 03 Sep 2019 22:38:06 +0200", "msg_from": "Pierre Ducroquet <p.psql@pinaraf.info>", "msg_from_op": true, "msg_subject": "Re: [Patch] Add a reset_computed_values function in\n pg_stat_statements" }, { "msg_contents": "This patch seems to be failing the contrib build. Please fix.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 25 Sep 2019 17:04:57 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: [Patch] Add a reset_computed_values function in\n pg_stat_statements" }, { "msg_contents": "On Thu, Sep 26, 2019 at 8:05 AM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n> This patch seems to be failing the contrib build. Please fix.\n\nHi Pierre,\n\nIn contrib/pg_stat_statements/pg_stat_statements.c, you need to\ndeclare or define entry_reset_computed() before you use it. I suppose\nyour compiler must be warning about that. I personally put\n\"COPT=-Wall -Werror\" into src/Makefile.custom to make sure that I\ndon't miss any warnings. That's also what http://cfbot.cputube.org/\ndoes (a thing that does a full check-world on all registered patches\nto look for such problems).\n\n\n", "msg_date": "Tue, 5 Nov 2019 11:03:58 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [Patch] Add a reset_computed_values function in\n pg_stat_statements" }, { "msg_contents": "On Tue, Nov 05, 2019 at 11:03:58AM +1300, Thomas Munro wrote:\n> In contrib/pg_stat_statements/pg_stat_statements.c, you need to\n> declare or define entry_reset_computed() before you use it. I suppose\n> your compiler must be warning about that. I personally put\n> \"COPT=-Wall -Werror\" into src/Makefile.custom to make sure that I\n> don't miss any warnings. That's also what http://cfbot.cputube.org/\n> does (a thing that does a full check-world on all registered patches\n> to look for such problems).\n\nStill the same problem which has not been addressed after a couple of\nweeks, so I am marking the entry as returned with feedback.\n--\nMichael", "msg_date": "Sun, 1 Dec 2019 10:13:06 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [Patch] Add a reset_computed_values function in\n pg_stat_statements" } ]
[ { "msg_contents": "Folks,\n\nI'd like to $Subject, on by default, with a switch to turn it off for\nthose really at the outer edges of performance. Some reasons include:\n\n- It's broadly useful.\n- Right now, the barrier for turning it on is quite high. In addition\n to being non-core, which is already a pretty high barrier at a lot\n of organizations, it requires a shared_preload_libraries setting,\n which is pretty close to untenable in a lot of use cases.\n- The overhead for most use cases is low compared to the benefit.\n\nBefore I go do the patch, I'd like to see whether there's anything\nlike a consensus as to the what and how of doing this.\n\nWhat say?\n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate\n\n\n", "msg_date": "Sun, 1 Sep 2019 20:00:26 +0200", "msg_from": "David Fetter <david@fetter.org>", "msg_from_op": true, "msg_subject": "Proposal: roll pg_stat_statements into core" }, { "msg_contents": "Hi\n\nne 1. 9. 2019 v 20:00 odesílatel David Fetter <david@fetter.org> napsal:\n\n> Folks,\n>\n> I'd like to $Subject, on by default, with a switch to turn it off for\n> those really at the outer edges of performance. Some reasons include:\n>\n> - It's broadly useful.\n> - Right now, the barrier for turning it on is quite high. In addition\n> to being non-core, which is already a pretty high barrier at a lot\n> of organizations, it requires a shared_preload_libraries setting,\n> which is pretty close to untenable in a lot of use cases.\n> - The overhead for most use cases is low compared to the benefit.\n>\n\nI have not a strong opinion about it. pg_stat_statements is really useful\nextenstion, on second hand\n\n1. the API is not stabilized yet - there are some patches related to this\nextension if I remember correctly\n2. there are not any numbers what is a overhead\n\nMaybe better solution can be some new API for shared memory, that doesn't\nneed to use shared_preload_library.\n\nIt can be useful for lot of other monitoring extensions, profilers,\ndebuggers,\n\nRegards\n\nPavel\n\n\n> Before I go do the patch, I'd like to see whether there's anything\n> like a consensus as to the what and how of doing this.\n>\n> What say?\n>\n> Best,\n> David.\n> --\n> David Fetter <david(at)fetter(dot)org> http://fetter.org/\n> Phone: +1 415 235 3778\n>\n> Remember to vote!\n> Consider donating to Postgres: http://www.postgresql.org/about/donate\n>\n>\n>\n\nHine 1. 9. 2019 v 20:00 odesílatel David Fetter <david@fetter.org> napsal:Folks,\n\nI'd like to $Subject, on by default, with a switch to turn it off for\nthose really at the outer edges of performance. Some reasons include:\n\n- It's broadly useful.\n- Right now, the barrier for turning it on is quite high. In addition\n  to being non-core, which is already a pretty high barrier at a lot\n  of organizations, it requires a shared_preload_libraries setting,\n  which is pretty close to untenable in a lot of use cases.\n- The overhead for most use cases is low compared to the benefit.I have not a strong opinion about it. pg_stat_statements is really useful extenstion, on second hand1. the API is not stabilized yet - there are some patches related to this extension if I remember correctly2. there are not any numbers what is a overheadMaybe better solution can be some new API for shared memory, that doesn't need to use shared_preload_library.It can be useful for lot of other monitoring extensions, profilers, debuggers, RegardsPavel\n\nBefore I go do the patch, I'd like to see whether there's anything\nlike a consensus as to the what and how of doing this.\n\nWhat say?\n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate", "msg_date": "Sun, 1 Sep 2019 20:12:15 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "On Sun, Sep 01, 2019 at 08:12:15PM +0200, Pavel Stehule wrote:\n> Hi\n> \n> ne 1. 9. 2019 v 20:00 odes�latel David Fetter <david@fetter.org> napsal:\n> \n> > Folks,\n> >\n> > I'd like to $Subject, on by default, with a switch to turn it off for\n> > those really at the outer edges of performance. Some reasons include:\n> >\n> > - It's broadly useful.\n> > - Right now, the barrier for turning it on is quite high. In addition\n> > to being non-core, which is already a pretty high barrier at a lot\n> > of organizations, it requires a shared_preload_libraries setting,\n> > which is pretty close to untenable in a lot of use cases.\n> > - The overhead for most use cases is low compared to the benefit.\n> >\n> \n> I have not a strong opinion about it. pg_stat_statements is really useful\n> extenstion, on second hand\n> \n> 1. the API is not stabilized yet - there are some patches related to this\n> extension if I remember correctly\n\nYou do.\n\n> 2. there are not any numbers what is a overhead\n\nWhat numbers would you suggest collecting? We could get some by\nrunning them with the extension loaded and not, although this goes to\nyour next proposal.\n\n> Maybe better solution can be some new API for shared memory, that doesn't\n> need to use shared_preload_library.\n\nWhat would such an API look like?\n\n> It can be useful for lot of other monitoring extensions, profilers,\n> debuggers,\n\nIt would indeed.\n\nDo you see this new API as a separate project, and if so, of\napproximately what size? Are we talking about something about the\nsize of DSM? Of JIT?\n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate\n\n\n", "msg_date": "Sun, 1 Sep 2019 20:48:29 +0200", "msg_from": "David Fetter <david@fetter.org>", "msg_from_op": true, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "David Fetter <david@fetter.org> writes:\n> - It's broadly useful.\n\nMaybe. Whether it can be argued that it's so broadly useful as\nto justify being on-by-default is not clear.\n\n> - Right now, the barrier for turning it on is quite high. In addition\n> to being non-core, which is already a pretty high barrier at a lot\n> of organizations, it requires a shared_preload_libraries setting,\n> which is pretty close to untenable in a lot of use cases.\n\nThat argument seems pretty weak. It's part of contrib and therefore\nmaintained by the same people as the \"core\" code. Also, I don't buy\nfor a minute that people who would need it don't also need a bunch of\nother changes in default GUC settings (shared_buffers etc).\n\n> - The overhead for most use cases is low compared to the benefit.\n\nPlease do not expect that we're going to accept such assertions\nunsupported by evidence. (As a very quick-n-dirty test, I tried\n\"pgbench -S\" and got somewhere around 4% TPS degradation with\npg_stat_statements loaded. That doesn't seem negligible.)\n\nI think also that we would need to consider the migration penalty\nfor people who already have the contrib version installed. To\njudge by previous cases (I'm thinking tsearch2) that could be\npretty painful. Admittedly, tsearch2 might not be a good comparison,\nbut points as simple as \"the views/functions won't be in the same\nschema as before\" are enough to cause trouble.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Sun, 01 Sep 2019 14:54:34 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "ne 1. 9. 2019 v 20:48 odesílatel David Fetter <david@fetter.org> napsal:\n\n> On Sun, Sep 01, 2019 at 08:12:15PM +0200, Pavel Stehule wrote:\n> > Hi\n> >\n> > ne 1. 9. 2019 v 20:00 odesílatel David Fetter <david@fetter.org> napsal:\n> >\n> > > Folks,\n> > >\n> > > I'd like to $Subject, on by default, with a switch to turn it off for\n> > > those really at the outer edges of performance. Some reasons include:\n> > >\n> > > - It's broadly useful.\n> > > - Right now, the barrier for turning it on is quite high. In addition\n> > > to being non-core, which is already a pretty high barrier at a lot\n> > > of organizations, it requires a shared_preload_libraries setting,\n> > > which is pretty close to untenable in a lot of use cases.\n> > > - The overhead for most use cases is low compared to the benefit.\n> > >\n> >\n> > I have not a strong opinion about it. pg_stat_statements is really useful\n> > extenstion, on second hand\n> >\n> > 1. the API is not stabilized yet - there are some patches related to this\n> > extension if I remember correctly\n>\n> You do.\n>\n> > 2. there are not any numbers what is a overhead\n>\n> What numbers would you suggest collecting? We could get some by\n> running them with the extension loaded and not, although this goes to\n> your next proposal.\n>\n\nI would to see some benchmarks (pg_bench - readonly, higher number of\nconnects)\n\n\n> > Maybe better solution can be some new API for shared memory, that doesn't\n> > need to use shared_preload_library.\n>\n> What would such an API look like?\n>\n\npossibility to allocate shared large blocks of shared memory without\nnecessity to do it at startup time\n\n\n> > It can be useful for lot of other monitoring extensions, profilers,\n> > debuggers,\n>\n> It would indeed.\n>\n> Do you see this new API as a separate project, and if so, of\n> approximately what size? Are we talking about something about the\n> size of DSM? Of JIT?\n>\n\nProbably about DSM, and about API how to other processes can connect to\nsome blocks of DSM. I rember similar request related to shared fulltext\ndictionaries\n\nIt can be part of some project \"enhancing pg_stat_statement - be possible\nload this extension without restart\"\n\n\n>\n> Best,\n> David.\n> --\n> David Fetter <david(at)fetter(dot)org> http://fetter.org/\n> Phone: +1 415 235 3778\n>\n> Remember to vote!\n> Consider donating to Postgres: http://www.postgresql.org/about/donate\n>\n\nne 1. 9. 2019 v 20:48 odesílatel David Fetter <david@fetter.org> napsal:On Sun, Sep 01, 2019 at 08:12:15PM +0200, Pavel Stehule wrote:\n> Hi\n> \n> ne 1. 9. 2019 v 20:00 odesílatel David Fetter <david@fetter.org> napsal:\n> \n> > Folks,\n> >\n> > I'd like to $Subject, on by default, with a switch to turn it off for\n> > those really at the outer edges of performance. Some reasons include:\n> >\n> > - It's broadly useful.\n> > - Right now, the barrier for turning it on is quite high. In addition\n> >   to being non-core, which is already a pretty high barrier at a lot\n> >   of organizations, it requires a shared_preload_libraries setting,\n> >   which is pretty close to untenable in a lot of use cases.\n> > - The overhead for most use cases is low compared to the benefit.\n> >\n> \n> I have not a strong opinion about it. pg_stat_statements is really useful\n> extenstion, on second hand\n> \n> 1. the API is not stabilized yet - there are some patches related to this\n> extension if I remember correctly\n\nYou do.\n\n> 2. there are not any numbers what is a overhead\n\nWhat numbers would you suggest collecting?  We could get some by\nrunning them with the extension loaded and not, although this goes to\nyour next proposal.I would to see some benchmarks (pg_bench - readonly, higher number of connects) \n\n> Maybe better solution can be some new API for shared memory, that doesn't\n> need to use shared_preload_library.\n\nWhat would such an API look like?possibility to allocate shared large blocks of shared memory without necessity to do it at startup time \n\n> It can be useful for lot of other monitoring extensions, profilers,\n> debuggers,\n\nIt would indeed.\n\nDo you see this new API as a separate project, and if so, of\napproximately what size?  Are we talking about something about the\nsize of DSM? Of JIT?Probably about DSM, and about API how to other processes can connect to some blocks of DSM. I rember similar request related to shared fulltext dictionaries It can be part of some project \"enhancing pg_stat_statement - be possible load this extension without restart\"  \n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate", "msg_date": "Sun, 1 Sep 2019 20:58:38 +0200", "msg_from": "Pavel Stehule <pavel.stehule@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "On 9/1/19 8:54 PM, Tom Lane wrote:\n>> - The overhead for most use cases is low compared to the benefit.\n> Please do not expect that we're going to accept such assertions\n> unsupported by evidence. (As a very quick-n-dirty test, I tried\n> \"pgbench -S\" and got somewhere around 4% TPS degradation with\n> pg_stat_statements loaded. That doesn't seem negligible.)\n\nAFAIR Andres pointed overhead could be much more when you have more queries than\npg_stat_statements.max [1]. Eviction can be costly.\n\n1: https://twitter.com/AndresFreundTec/status/1105585237772263424", "msg_date": "Mon, 2 Sep 2019 10:11:28 +0200", "msg_from": "Adrien Nayrat <adrien.nayrat@anayrat.info>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "Em seg, 2 de set de 2019 às 05:11, Adrien Nayrat\n<adrien.nayrat@anayrat.info> escreveu:\n>\n> On 9/1/19 8:54 PM, Tom Lane wrote:\n> >> - The overhead for most use cases is low compared to the benefit.\n> > Please do not expect that we're going to accept such assertions\n> > unsupported by evidence. (As a very quick-n-dirty test, I tried\n> > \"pgbench -S\" and got somewhere around 4% TPS degradation with\n> > pg_stat_statements loaded. That doesn't seem negligible.)\n>\n> AFAIR Andres pointed overhead could be much more when you have more queries than\n> pg_stat_statements.max [1]. Eviction can be costly.\n>\npg_stat_statements is important in a lot of query analysis. If you\nmake a comparison between pg_stat_statements and pgbadger, you can\ncapture queries for the latter changing log_min_duration_statement or\nlog_statement without restart the server, however, the former you\ncan't without restarting the server. At least if pg_stat_statements\nwas in core you could load it by default and have a GUC to turn it\non/off without restarting the server (that was Magnus proposal and\nAndres agreed). I support this idea. In v10 we changed some GUCs to\nperform replication out-of-box; we should do the same for query\nanalysis.\n\nRegards,\n\n\n-- \n Euler Taveira Timbira -\nhttp://www.timbira.com.br/\n PostgreSQL: Consultoria, Desenvolvimento, Suporte 24x7 e Treinamento\n\n\n", "msg_date": "Mon, 2 Sep 2019 10:31:20 -0300", "msg_from": "Euler Taveira <euler@timbira.com.br>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "Euler Taveira <euler@timbira.com.br> writes:\n> At least if pg_stat_statements\n> was in core you could load it by default and have a GUC to turn it\n> on/off without restarting the server (that was Magnus proposal and\n> Andres agreed).\n\nThat assertion is 100% bogus. To turn it on or off on-the-fly,\nyou'd need some way to acquire or release its shared memory\non-the-fly.\n\nIt's probably now possible to do something like that, using the\nDSM mechanisms, but the code for it hasn't been written (AFAIK).\nAnd it wouldn't have much to do with whether the module was\nin core or stayed where it is.\n\nAnother concern that I have about moving pg_stat_statements\ninto core is that doing so would effectively nail down\nQuery.queryId as belonging to pg_stat_statements, whereas\ncurrently it's possible for other plugins to commandeer that\nif they wish. This isn't academic, because of the fact that\nnot everybody is satisfied with the way pg_stat_statements\ndefines queryId [1].\n\n\t\t\tregards, tom lane\n\n[1] https://www.postgresql.org/message-id/flat/1553029215728-0.post%40n3.nabble.com\n\n\n", "msg_date": "Mon, 02 Sep 2019 12:07:17 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "grOn Mon, Sep 02, 2019 at 12:07:17PM -0400, Tom Lane wrote:\n> Euler Taveira <euler@timbira.com.br> writes:\n>> At least if pg_stat_statements\n>> was in core you could load it by default and have a GUC to turn it\n>> on/off without restarting the server (that was Magnus proposal and\n>> Andres agreed).\n> \n> That assertion is 100% bogus. To turn it on or off on-the-fly,\n> you'd need some way to acquire or release its shared memory\n> on-the-fly.\n> \n> It's probably now possible to do something like that, using the\n> DSM mechanisms, but the code for it hasn't been written (AFAIK).\n> And it wouldn't have much to do with whether the module was\n> in core or stayed where it is.\n\nIf we were to actually merge the module into core and switch to DSM\ninstead of the current fixed amout of shared memory defined at start\ntime, then that would be a two-step process: first push the functions\ninto code with a GUC_POSTMASTER as currently done, and secondly\nattempt to switch the GUC to be reloadable.\n\nFWIW, I am not sure that we should have the module into core.\n--\nMichael", "msg_date": "Tue, 3 Sep 2019 15:37:27 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "On Tue, Sep 3, 2019 at 11:37 AM Michael Paquier <michael@paquier.xyz> wrote:\n\n> grOn Mon, Sep 02, 2019 at 12:07:17PM -0400, Tom Lane wrote:\n> > Euler Taveira <euler@timbira.com.br> writes:\n> >> At least if pg_stat_statements\n> >> was in core you could load it by default and have a GUC to turn it\n> >> on/off without restarting the server (that was Magnus proposal and\n> >> Andres agreed).\n> >\n> > That assertion is 100% bogus. To turn it on or off on-the-fly,\n> > you'd need some way to acquire or release its shared memory\n> > on-the-fly.\n> >\n> > It's probably now possible to do something like that, using the\n> > DSM mechanisms, but the code for it hasn't been written (AFAIK).\n> > And it wouldn't have much to do with whether the module was\n> > in core or stayed where it is.\n>\n> If we were to actually merge the module into core and switch to DSM\n> instead of the current fixed amout of shared memory defined at start\n> time, then that would be a two-step process: first push the functions\n> into code with a GUC_POSTMASTER as currently done, and secondly\n> attempt to switch the GUC to be reloadable.\n>\n> FWIW, I am not sure that we should have the module into core.\n> --\n> Michael\n>\n\n- It's broadly useful.\nNo doubt it is very useful and most of the customer is using that.\n\n- Right now, the barrier for turning it on is quite high. In addition\n to being non-core, which is already a pretty high barrier at a lot\nof organizations,it requires a shared_preload_libraries setting,\n which is pretty close to untenable in a lot of use cases.\n\nWe are thinking to move a module in core just because of\n\"barrier for turning it on is quite high\" which is not a very compelling\nreason. I am just thinking\nwhy not have a system which makes that easy instead of adding to core.\n\n\n\n-- \nIbrar Ahmed\n\nOn Tue, Sep 3, 2019 at 11:37 AM Michael Paquier <michael@paquier.xyz> wrote:grOn Mon, Sep 02, 2019 at 12:07:17PM -0400, Tom Lane wrote:\n> Euler Taveira <euler@timbira.com.br> writes:\n>> At least if pg_stat_statements\n>> was in core you could load it by default and have a GUC to turn it\n>> on/off without restarting the server (that was Magnus proposal and\n>> Andres agreed).\n> \n> That assertion is 100% bogus.  To turn it on or off on-the-fly,\n> you'd need some way to acquire or release its shared memory\n> on-the-fly.\n> \n> It's probably now possible to do something like that, using the\n> DSM mechanisms, but the code for it hasn't been written (AFAIK).\n> And it wouldn't have much to do with whether the module was\n> in core or stayed where it is.\n\nIf we were to actually merge the module into core and switch to DSM\ninstead of the current fixed amout of shared memory defined at start\ntime, then that would be a two-step process: first push the functions\ninto code with a GUC_POSTMASTER as currently done, and secondly\nattempt to switch the GUC to be reloadable.\n\nFWIW, I am not sure that we should have the module into core.\n--\nMichael - It's broadly useful.No doubt it is very useful and most of the customer is using that.- Right now, the barrier for turning it on is quite high. In addition  to being non-core, which is already a pretty high barrier at a lot of organizations,it requires a shared_preload_libraries setting,  which is pretty close to untenable in a lot of use cases.We are thinking to move a module in core just because of\"barrier for turning it on is quite high\" which is not a very compelling reason. I am just thinkingwhy not have a system which makes that easy instead of adding to core.-- Ibrar Ahmed", "msg_date": "Tue, 3 Sep 2019 22:10:56 +0500", "msg_from": "Ibrar Ahmed <ibrar.ahmad@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "Greetings,\n\n* David Fetter (david@fetter.org) wrote:\n> I'd like to $Subject, on by default, with a switch to turn it off for\n> those really at the outer edges of performance. Some reasons include:\n\nSure, half of contrib should really be in core (amcheck, file_fdw,\npostgres_fdw, maybe dblink, pageinspect, pg_buffercache,\npg_freespacemap, pgstattuple, pg_visibility, sslinfo, maybe pgtrgm..)\nbut we simply haven't got great facilities for either migrating those\nthings into core (particularly during an upgrade..) or making them\navailable directly in a way that isn't intrusive (seems like maybe we\nshould have an independent schema from pg_catalog that's for things like\nthis... utility functions and views over them which are particularly\nuseful; harkins back to the ancient discussion about a new pg_catalog\nstructure... pg new sysviews, or something along those lines?).\n\nFigure out how to fix those issues and maybe there's something\ninteresting to discuss here, until then, a thread like this is likely to\nbe unproductive. A direct patch that just shoves pg_stat_statements\ninto core isn't going to cut it.\n\nThanks,\n\nStephen", "msg_date": "Tue, 3 Sep 2019 15:56:28 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "On Tue, Sep 03, 2019 at 03:56:28PM -0400, Stephen Frost wrote:\n> Greetings,\n> \n> * David Fetter (david@fetter.org) wrote:\n> > I'd like to $Subject, on by default, with a switch to turn it off for\n> > those really at the outer edges of performance. Some reasons include:\n> \n> Sure, half of contrib should really be in core (amcheck, file_fdw,\n> postgres_fdw, maybe dblink, pageinspect, pg_buffercache,\n> pg_freespacemap, pgstattuple, pg_visibility, sslinfo, maybe pgtrgm..)\n\nAgreed.\n\n> but we simply haven't got great facilities for either migrating those\n> things into core (particularly during an upgrade..)\n\nSo a process that makes transitioning from extension to core in a(n at\nleast largely) mechanical way sounds like a Useful Thing™.\n\nWould that be worth a separate thread once this CF is over?\n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate\n\n\n", "msg_date": "Wed, 4 Sep 2019 01:38:40 +0200", "msg_from": "David Fetter <david@fetter.org>", "msg_from_op": true, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "Greetings,\n\nOn Tue, Sep 3, 2019 at 19:38 David Fetter <david@fetter.org> wrote:\n\n> On Tue, Sep 03, 2019 at 03:56:28PM -0400, Stephen Frost wrote:\n> > Greetings,\n> >\n> > * David Fetter (david@fetter.org) wrote:\n> > > I'd like to $Subject, on by default, with a switch to turn it off for\n> > > those really at the outer edges of performance. Some reasons include:\n> >\n> > Sure, half of contrib should really be in core (amcheck, file_fdw,\n> > postgres_fdw, maybe dblink, pageinspect, pg_buffercache,\n> > pg_freespacemap, pgstattuple, pg_visibility, sslinfo, maybe pgtrgm..)\n>\n> Agreed.\n>\n> > but we simply haven't got great facilities for either migrating those\n> > things into core (particularly during an upgrade..)\n>\n> So a process that makes transitioning from extension to core in a(n at\n> least largely) mechanical way sounds like a Useful Thing™.\n>\n> Would that be worth a separate thread once this CF is over?\n\n\nA well considered proposal might be interesting. A “call to arms” asking\nsomeone to create same likely wouldn’t be.\n\nThanks,\n\nStephen\n\n>\n>\n\nGreetings,On Tue, Sep 3, 2019 at 19:38 David Fetter <david@fetter.org> wrote:On Tue, Sep 03, 2019 at 03:56:28PM -0400, Stephen Frost wrote:\n> Greetings,\n> \n> * David Fetter (david@fetter.org) wrote:\n> > I'd like to $Subject, on by default, with a switch to turn it off for\n> > those really at the outer edges of performance. Some reasons include:\n> \n> Sure, half of contrib should really be in core (amcheck, file_fdw,\n> postgres_fdw, maybe dblink, pageinspect, pg_buffercache,\n> pg_freespacemap, pgstattuple, pg_visibility, sslinfo, maybe pgtrgm..)\n\nAgreed.\n\n> but we simply haven't got great facilities for either migrating those\n> things into core (particularly during an upgrade..)\n\nSo a process that makes transitioning from extension to core in a(n at\nleast largely) mechanical way sounds like a Useful Thing™.\n\nWould that be worth a separate thread once this CF is over?A well considered proposal might be interesting. A “call to arms” asking someone to create same likely wouldn’t be.Thanks,Stephen", "msg_date": "Tue, 3 Sep 2019 19:41:00 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "On Tue, Sep 03, 2019 at 07:41:00PM -0400, Stephen Frost wrote:\n> Greetings,\n> \n> On Tue, Sep 3, 2019 at 19:38 David Fetter <david@fetter.org> wrote:\n> \n> > On Tue, Sep 03, 2019 at 03:56:28PM -0400, Stephen Frost wrote:\n> > > Greetings,\n> > >\n> > > * David Fetter (david@fetter.org) wrote:\n> > > > I'd like to $Subject, on by default, with a switch to turn it off for\n> > > > those really at the outer edges of performance. Some reasons include:\n> > >\n> > > Sure, half of contrib should really be in core (amcheck, file_fdw,\n> > > postgres_fdw, maybe dblink, pageinspect, pg_buffercache,\n> > > pg_freespacemap, pgstattuple, pg_visibility, sslinfo, maybe pgtrgm..)\n> >\n> > Agreed.\n> >\n> > > but we simply haven't got great facilities for either migrating those\n> > > things into core (particularly during an upgrade..)\n> >\n> > So a process that makes transitioning from extension to core in a(n at\n> > least largely) mechanical way sounds like a Useful Thing™.\n> >\n> > Would that be worth a separate thread once this CF is over?\n> \n> A well considered proposal might be interesting. A “call to arms” asking\n> someone to create same likely wouldn’t be.\n\nI was thinking of a PoC (or, ideally, better) for such a system. The\ncurrent CF having already started, after it's over seems like a better\ntime to do it.\n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate\n\n\n", "msg_date": "Wed, 4 Sep 2019 01:44:46 +0200", "msg_from": "David Fetter <david@fetter.org>", "msg_from_op": true, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "On 2019-Sep-03, Stephen Frost wrote:\n\n> Greetings,\n> \n> * David Fetter (david@fetter.org) wrote:\n> > I'd like to $Subject, on by default, with a switch to turn it off for\n> > those really at the outer edges of performance. Some reasons include:\n> \n> Sure, half of contrib should really be in core (amcheck, file_fdw,\n> postgres_fdw, maybe dblink, pageinspect, pg_buffercache,\n> pg_freespacemap, pgstattuple, pg_visibility, sslinfo, maybe pgtrgm..)\n> but we simply haven't got great facilities for either migrating those\n> things into core (particularly during an upgrade..)\n\nI think there is a false dichotomy here. Migrating an extension out of\ncontrib doesn't have to equate making it no longer an extension. We\ncould, instead, keep it being an extension, but move it out of contrib\nand into (say) src/extensions/ so that it becomes installed and\navailable by default, but still an extension. Users won't have to\ninstall a separate contrib package, but they would still have to run\nCREATE EXTENSION.\n\nWe don't incur the upgrade pain if we do that, for one thing. Also, we\ndon't force everybody to have it; and we don't have to invent this\nhypothetical switch to turn it off.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 3 Sep 2019 21:38:58 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "Greetings,\n\n* Alvaro Herrera (alvherre@2ndquadrant.com) wrote:\n> On 2019-Sep-03, Stephen Frost wrote:\n> > * David Fetter (david@fetter.org) wrote:\n> > > I'd like to $Subject, on by default, with a switch to turn it off for\n> > > those really at the outer edges of performance. Some reasons include:\n> > \n> > Sure, half of contrib should really be in core (amcheck, file_fdw,\n> > postgres_fdw, maybe dblink, pageinspect, pg_buffercache,\n> > pg_freespacemap, pgstattuple, pg_visibility, sslinfo, maybe pgtrgm..)\n> > but we simply haven't got great facilities for either migrating those\n> > things into core (particularly during an upgrade..)\n> \n> I think there is a false dichotomy here. Migrating an extension out of\n> contrib doesn't have to equate making it no longer an extension. We\n> could, instead, keep it being an extension, but move it out of contrib\n> and into (say) src/extensions/ so that it becomes installed and\n> available by default, but still an extension. Users won't have to\n> install a separate contrib package, but they would still have to run\n> CREATE EXTENSION.\n> \n> We don't incur the upgrade pain if we do that, for one thing. Also, we\n> don't force everybody to have it; and we don't have to invent this\n> hypothetical switch to turn it off.\n\nI don't agree that it's a false dichotomy- from a user experience, you\naren't really changing anything with this approach and the entire point\nis that most of these things should just be available in core. Yes,\nmaybe we need a way to turn on/off things like pg_stat_statements but\nthat should have been a runtime \"track_stat_statements\" or some such,\nsimilar to other things like \"track_io_timing\", not an \"independent\"\nextension that is actually developed, managed, and released just as core\nis.\n\nI also don't buy off, not in the *least*, that we can willy-nilly change\nthings that pg_stat_statements depends on, or the interface of\npg_stat_statements itself, any more than we can change catalog tables\n(which is to say- we can, and do, and people have to deal with it, but\nwe do get to listen to complaints about it and at times consider if a\nchange is worth it or not to make). Having it as an extension doesn't\nreally change any of that for us, imv.\n\nThese aren't external extensions and \"contrib\" hasn't been what it was\noriginally designed for in years (see pg_audit if you'd like a\nrelatively recent example of how contrib isn't really for things that\n\"address a limited audience or are too experimental to be part of the\nmain source tree\" anymore, despite our README in that directory claiming\notherwise).\n\nI wouldn't be against a proposal that moved contrib into a 'src/modules'\nor some such just for maintenance but if we aren't installing the ones\nthat I've suggested above by (and probably others) by default (and\nprobably sending the others to the bitbucket because they really aren't\ncore-ready) then there's really not much point in doing anything here.\n\nThe one *good* thing about having extensions is really something that we\n*should* have a way to do in core- and that's the upgrade path and\nthe ability to run an upgrade script sanely. Maybe we can't get there\nfor all of our catalogs, but it'd sure be nice if we could figure out a\nway to do it for some things so that we break at least a few less things\nduring upgrades.\n\nThanks,\n\nStephen", "msg_date": "Tue, 3 Sep 2019 22:11:34 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> * Alvaro Herrera (alvherre@2ndquadrant.com) wrote:\n>> I think there is a false dichotomy here. Migrating an extension out of\n>> contrib doesn't have to equate making it no longer an extension. We\n>> could, instead, keep it being an extension, but move it out of contrib\n>> and into (say) src/extensions/ so that it becomes installed and\n>> available by default, but still an extension. Users won't have to\n>> install a separate contrib package, but they would still have to run\n>> CREATE EXTENSION.\n\n> I don't agree that it's a false dichotomy- from a user experience, you\n> aren't really changing anything with this approach and the entire point\n> is that most of these things should just be available in core.\n\nI don't think that auto-installing such things requires changing much\nof anything. See plpgsql, which is auto-installed now but still sits\nin src/pl/ alongside other PLs that are not auto-installed. Similarly,\nthere's nothing really stopping us from choosing to install some\nmodule of contrib by default; rearranging the source tree is not a\nprerequisite to that.\n\nThe situation with pg_stat_statements is more than that, since what\nDavid is requesting is not merely that we auto-install that extension\nbut that we automatically push it into shared_preload_libraries.\n\n> ...maybe we need a way to turn on/off things like pg_stat_statements but\n> that should have been a runtime \"track_stat_statements\" or some such,\n> similar to other things like \"track_io_timing\", not an \"independent\"\n> extension that is actually developed, managed, and released just as core\n> is.\n\nA key point that hasn't been highlighted in this discussion is that having\npg_stat_statements as an extension is proof-of-concept that such features\n*can* be implemented outside of core. Don't you think that there are\nprobably people maintaining private variants of that extension, who would\nbe really sad if we removed or broke APIs they need for it once\npg_stat_statements is part of core?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Wed, 04 Sep 2019 00:14:50 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "Greetings,\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> Stephen Frost <sfrost@snowman.net> writes:\n> > * Alvaro Herrera (alvherre@2ndquadrant.com) wrote:\n> >> I think there is a false dichotomy here. Migrating an extension out of\n> >> contrib doesn't have to equate making it no longer an extension. We\n> >> could, instead, keep it being an extension, but move it out of contrib\n> >> and into (say) src/extensions/ so that it becomes installed and\n> >> available by default, but still an extension. Users won't have to\n> >> install a separate contrib package, but they would still have to run\n> >> CREATE EXTENSION.\n> \n> > I don't agree that it's a false dichotomy- from a user experience, you\n> > aren't really changing anything with this approach and the entire point\n> > is that most of these things should just be available in core.\n> \n> I don't think that auto-installing such things requires changing much\n> of anything. See plpgsql, which is auto-installed now but still sits\n> in src/pl/ alongside other PLs that are not auto-installed. Similarly,\n> there's nothing really stopping us from choosing to install some\n> module of contrib by default; rearranging the source tree is not a\n> prerequisite to that.\n\nSure, I agree with you about all of that- I was just offering it as an\noption that if folks felt that rearranging the tree for these\nauto-installed things makes sense then, sure, we can do that.\n\n> The situation with pg_stat_statements is more than that, since what\n> David is requesting is not merely that we auto-install that extension\n> but that we automatically push it into shared_preload_libraries.\n\nNot sure that it'd actually operate in exactly that way, but yes, when\nenabled we'd allocate memory the same as if it was in\nshared_preload_libraries and such.\n\n> > ...maybe we need a way to turn on/off things like pg_stat_statements but\n> > that should have been a runtime \"track_stat_statements\" or some such,\n> > similar to other things like \"track_io_timing\", not an \"independent\"\n> > extension that is actually developed, managed, and released just as core\n> > is.\n> \n> A key point that hasn't been highlighted in this discussion is that having\n> pg_stat_statements as an extension is proof-of-concept that such features\n> *can* be implemented outside of core. Don't you think that there are\n> probably people maintaining private variants of that extension, who would\n> be really sad if we removed or broke APIs they need for it once\n> pg_stat_statements is part of core?\n\nDo I feel that out-of-core private extensions are more valuable than the\nrun-of-the-mill user who just wants to be able to see what queries are\ntaking time in their running system? Perhaps it's a but cut-throat,\nbut, uh, no, not in the least. I, at least, don't hack on PostgreSQL\nbecause it's a fantastic platform for closed source/proprietary/third\nparty solutions to be built upon but rather because it's damn good\nopen source software that I enjoy working with. That's part of what\nfrustrates me about contrib- it was once thing X and it's now quite\nclearly thing Y but we are refusing to call it that, and that's just not\nhow I've become accustomed to this open source project working. Let's\ncall a spade a spade.\n\nThat said, I do understand the point that integrating these things into\ncore *might* lead us down a road where we break extension APIs in ways\nthat maybe we wouldn't have if they were kept as extensions, but really,\nanyone who runs into that issue who really cares to be heard should be\nas vocal and active as the PostGIS folks are- we hear from them\nregularly on our lists and that's how it should be. I'm not going to be\nconvinced of the silent-majority argument in this case, given the pain\nit causes a great many of our regular users.\n\n... we also have a way to test these hooks/modules in our regression\ntests, which we should probably do so that we at least know when we\nbreak them.\n\nLet's put pg_stat_statements aside for a minute- what's the reasoning\nbehind requireing users to run CREATE EXTENTION to utilize the functions\noffered by amcheck? pgstattuple? pg_buffercache? At least with\npg_stat_statements there's good justification, based on performance, for\nwanting an on/off switch, but for just about all the other ones, all it\nis is a few entries in a catalog table that we're talking about...\n\nThanks,\n\nStephen", "msg_date": "Wed, 4 Sep 2019 01:25:25 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "On Wed, Sep 04, 2019 at 12:14:50AM -0400, Tom Lane wrote:\n> Stephen Frost <sfrost@snowman.net> writes:\n> > * Alvaro Herrera (alvherre@2ndquadrant.com) wrote:\n> >> I think there is a false dichotomy here. Migrating an extension out of\n> >> contrib doesn't have to equate making it no longer an extension. We\n> >> could, instead, keep it being an extension, but move it out of contrib\n> >> and into (say) src/extensions/ so that it becomes installed and\n> >> available by default, but still an extension. Users won't have to\n> >> install a separate contrib package, but they would still have to run\n> >> CREATE EXTENSION.\n> \n> > I don't agree that it's a false dichotomy- from a user experience, you\n> > aren't really changing anything with this approach and the entire point\n> > is that most of these things should just be available in core.\n> \n> I don't think that auto-installing such things requires changing much\n> of anything. See plpgsql, which is auto-installed now but still sits\n> in src/pl/ alongside other PLs that are not auto-installed. Similarly,\n> there's nothing really stopping us from choosing to install some\n> module of contrib by default; rearranging the source tree is not a\n> prerequisite to that.\n> \n> The situation with pg_stat_statements is more than that, since what\n> David is requesting is not merely that we auto-install that extension\n> but that we automatically push it into shared_preload_libraries.\n\nWhat I am actually suggesting is that it not be a separate library at\nall, i.e. that all its parts live in PostgreSQL proper.\n\n> > ...maybe we need a way to turn on/off things like pg_stat_statements but\n> > that should have been a runtime \"track_stat_statements\" or some such,\n> > similar to other things like \"track_io_timing\", not an \"independent\"\n> > extension that is actually developed, managed, and released just as core\n> > is.\n> \n> A key point that hasn't been highlighted in this discussion is that having\n> pg_stat_statements as an extension is proof-of-concept that such features\n> *can* be implemented outside of core. Don't you think that there are\n> probably people maintaining private variants of that extension, who would\n> be really sad if we removed or broke APIs they need for it once\n> pg_stat_statements is part of core?\n\nNowhere near the number of people who are inconvenienced, at a\nminimum, by the high barriers needed in order to install and use it in\nits current form.\n\nBest,\nDavid.\n-- \nDavid Fetter <david(at)fetter(dot)org> http://fetter.org/\nPhone: +1 415 235 3778\n\nRemember to vote!\nConsider donating to Postgres: http://www.postgresql.org/about/donate\n\n\n", "msg_date": "Wed, 4 Sep 2019 08:16:36 +0200", "msg_from": "David Fetter <david@fetter.org>", "msg_from_op": true, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "Hi,\n\nOn 2019-09-02 12:07:17 -0400, Tom Lane wrote:\n> Euler Taveira <euler@timbira.com.br> writes:\n> > At least if pg_stat_statements\n> > was in core you could load it by default and have a GUC to turn it\n> > on/off without restarting the server (that was Magnus proposal and\n> > Andres agreed).\n> \n> That assertion is 100% bogus. To turn it on or off on-the-fly,\n> you'd need some way to acquire or release its shared memory\n> on-the-fly.\n\nNot necessarily - in practice the issue of pg_stat_statements having\noverhead isn't about the memory overhead, but the CPU overhead. And that\nwe can nearly entirely disable/enable without acquiring / releasing\nshared memory already, by setting pg_stat_statements.track to NONE.\n\n\nThere's still the overhead of being indirected through the pgss_* hooks,\nwhich then have to figure out that pgss is disabled. But that's\nobviously much smaller than the overhead of pgss itself. Although I do\nwonder if it's time that we make hook registration/unregistration a bit\nmore flexible - it's basically impossible to unregister hooks right now\nbecause the chain of hooks is distributed over multiple files. If we\ninstead provided a few helper functions to register hooks we could allow\nderegistering as well.\n\n\n> It's probably now possible to do something like that, using the\n> DSM mechanisms, but the code for it hasn't been written (AFAIK).\n> And it wouldn't have much to do with whether the module was\n> in core or stayed where it is.\n\nI think it'd be good to add DSM support for pg_stat_statements - but as\nyou say that's largely independent of it being mainlined.\n\n\n> Another concern that I have about moving pg_stat_statements\n> into core is that doing so would effectively nail down\n> Query.queryId as belonging to pg_stat_statements, whereas\n> currently it's possible for other plugins to commandeer that\n> if they wish. This isn't academic, because of the fact that\n> not everybody is satisfied with the way pg_stat_statements\n> defines queryId [1].\n\nI'm not sure I see this as that big an issue - we could have a few\ndifferent query ids for each query. If it's a problem that there's\npotentially different desirable semantics for queryId, then it's also an\nissue that we can have only one.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 4 Sep 2019 02:34:03 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" }, { "msg_contents": "On 2019-Sep-02, Euler Taveira wrote:\n\n> At least if pg_stat_statements\n> was in core you could load it by default and have a GUC to turn it\n> on/off without restarting the server (that was Magnus proposal and\n> Andres agreed). I support this idea.\n\nActually this is possible without moving to part of core, too -- change\nthings so that putting it in shared_preload_libraries reserves the shmem\narea but does not enable collection, then have a separate GUC that\nenables/disables collection. A bit like archive_mode=on,\narchive_command=/bin/true, which allows to change archive_command\nwithout restarting.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 5 Sep 2019 12:07:55 -0400", "msg_from": "Alvaro Herrera from 2ndQuadrant <alvherre@alvh.no-ip.org>", "msg_from_op": false, "msg_subject": "Re: Proposal: roll pg_stat_statements into core" } ]
[ { "msg_contents": "Hi,\n\nI don't mean \"overload objectSubId\" in any ObjectAddress that PG code\nwould ever see. I am only thinking of a data structure of my own that\nis ObjectAddress-like and has all three components available all the\ntime, and for an object that's a type, I would find it handy to stash\na typmod there, and not have to carry those around separately.\n\nAs far as I can tell, most objects (maybe all, except attributes\nand attribute defaults?) have the objectSubId unused. But I would not\nwant to paint myself into a corner if anyone anticipates making\nobjectSubId mean something for type objects somewhere down the road.\n\nThanks,\n-Chap\n\n\n", "msg_date": "Sun, 1 Sep 2019 22:19:24 -0400", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": true, "msg_subject": "safe to overload objectSubId for a type?" }, { "msg_contents": "Chapman Flack <chap@anastigmatix.net> writes:\n> I don't mean \"overload objectSubId\" in any ObjectAddress that PG code\n> would ever see. I am only thinking of a data structure of my own that\n> is ObjectAddress-like and has all three components available all the\n> time, and for an object that's a type, I would find it handy to stash\n> a typmod there, and not have to carry those around separately.\n\nIf this is totally independent of ObjectAddress, why are you even\nasking? I assume that what you mean is you'd like these values to\nbleed into ObjectAddresses or vice versa.\n\nIf we ever do make ObjectAddress.objectSubId mean something for types,\nI'd expect --- based on the precedent of relation columns --- that it'd\nspecify a column number for a column of a composite type. There are\nfairly obvious use-cases for that, such as allowing a DROP of a column\ntype to not propagate to the whole composite type. So I'd be pretty down\non allowing it to mean typmod instead.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 02 Sep 2019 00:29:55 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: safe to overload objectSubId for a type?" }, { "msg_contents": "On 09/02/19 00:29, Tom Lane wrote:\n\n> If this is totally independent of ObjectAddress, why are you even\n> asking? I assume that what you mean is you'd like these values to\n> bleed into ObjectAddresses or vice versa.\n\nOnly that I'm working on a data structure of my own to cache my own\nrepresentations for objects, which I can find by a simple hash lookup\non a key of three ints, given an ObjectAddress. But I'd like to have\ndistinct instances representing distinct typmods of a type, and if I\nhad a method to look up a type instance given an ObjectAddress and\ntypmod, and that method could simply use the typmod (or a trivially\ntransformed version, -1 <-> 0) as the third int of the key, then my\nsingle hash structure and one lookup serves for everything.\n\nOtherwise, I essentially need a second whole layer of the same machinery\nto track typmod-variants of types (and forget them when unreferenced,\ninvalidated, yada yada), or variable-length cache keys so type keys\nare four ints instead of three, or four-int keys for everything, just\nbecause types.\n\nAny of those alternatives would just be a SMOP if truly necessary,\nbut uglier and more complex.\n\n\n> If we ever do make ObjectAddress.objectSubId mean something for types,\n> I'd expect --- based on the precedent of relation columns --- that it'd\n> specify a column number for a column of a composite type. There are\n> fairly obvious use-cases for that, such as allowing a DROP of a column\n> type to not propagate to the whole composite type.\n\nCould you give an illustration to make sure I'm following? I tried to\ncreate my own example with:\n\nCREATE TYPE foo AS (bar int, baz int);\nCREATE TABLE quux (a foo);\nINSERT INTO quux (a.bar, a.baz) VALUES (12, 34);\nSELECT * FROM quux;\n a\n---------\n (12,34)\nALTER TYPE foo DROP ATTRIBUTE baz;\nSELECT * FROM quux;\n a\n------\n (12)\n\nbut I guess that must not exercise the case you had in mind.\n\n\nI could say my main reason for asking was to judge the imminence of\nany change. If there's a vague conceivable possibility of objectSubId\nmeaning something for types in the indefinite future, I might do my\nsimple implementation now, and some uglier SMOP alternative later\nwhen/if needed. If somebody has such a change in mind for the near\nterm, that'd be different.\n\nRegards,\n-Chap\n\n\n", "msg_date": "Mon, 2 Sep 2019 10:52:29 -0400", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": true, "msg_subject": "Re: safe to overload objectSubId for a type?" }, { "msg_contents": "Chapman Flack <chap@anastigmatix.net> writes:\n> On 09/02/19 00:29, Tom Lane wrote:\n>> If we ever do make ObjectAddress.objectSubId mean something for types,\n>> I'd expect --- based on the precedent of relation columns --- that it'd\n>> specify a column number for a column of a composite type. There are\n>> fairly obvious use-cases for that, such as allowing a DROP of a column\n>> type to not propagate to the whole composite type.\n\n> Could you give an illustration to make sure I'm following?\n\nHm, apparently we already do handle that in some way, because\nthis works:\n\nregression=# create type myenum as enum ('red', 'black');\nCREATE TYPE\nregression=# create type mycomposite as (f1 int, f2 myenum, f3 text);\nCREATE TYPE\nregression=# drop type myenum;\nERROR: cannot drop type myenum because other objects depend on it\nDETAIL: column f2 of composite type mycomposite depends on type myenum\nHINT: Use DROP ... CASCADE to drop the dependent objects too.\nregression=# drop type myenum cascade;\nNOTICE: drop cascades to column f2 of composite type mycomposite\nDROP TYPE\nregression=# \\d mycomposite\n Composite type \"public.mycomposite\"\n Column | Type | Collation | Nullable | Default \n--------+---------+-----------+----------+---------\n f1 | integer | | | \n f3 | text | | | \n\nI'm too lazy to go check, but I suspect that the representation\nof this situation in pg_depend makes use of a dependency for a\ncolumn of the relation associated with the mycomposite type,\nso that the entry having nonzero objsubid has classid pg_class\nnot classid pg_type.\n\nNonetheless, I'd be pretty hesitant to allow somebody to use\nobjsubid with some entirely different meaning for types. That\nseems certain to lead to confusion and bugs.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 02 Sep 2019 11:41:58 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: safe to overload objectSubId for a type?" }, { "msg_contents": "On 09/02/19 11:41, Tom Lane wrote:\n> Hm, apparently we already do handle that in some way, because\n> this works:\n> ...\n> Nonetheless, I'd be pretty hesitant to allow somebody to use\n> objsubid with some entirely different meaning for types.\n\nAs long as it stays an internal detail of a caching scheme used by me\nand will be masked back to 0 before anything escapes to elsewhere, so it\nreally only exploits the current fact that objSubId for types carries\nno information at all ... and no one seems to be chiming in with a pressing\ncase for changing that ... I think I can get away with the simple scheme,\nadmitting the possibility of having to revisit it down the road.\n\nRegards,\n-Chap\n\n\n", "msg_date": "Mon, 2 Sep 2019 12:57:31 -0400", "msg_from": "Chapman Flack <chap@anastigmatix.net>", "msg_from_op": true, "msg_subject": "Re: safe to overload objectSubId for a type?" } ]
[ { "msg_contents": "Hi,\n\nNews from Fabien's bleeding edge compiler zoo: apparently GCC 10\n20190831 thinks the tsearch test should produce different output than\n20190824 did. It looks like the parsing of question marks change...\nI can't wait for next week's installment.\n\n--\nThomas Munro\nhttps://enterprisedb.com\n\n\n", "msg_date": "Mon, 2 Sep 2019 15:56:46 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "moonjelly vs tsearch" }, { "msg_contents": "\n> News from Fabien's bleeding edge compiler zoo: apparently GCC 10 \n> 20190831 thinks the tsearch test should produce different output than \n> 20190824 did. It looks like the parsing of question marks change...\n\nIndeed, that looks pretty strange.\n\n> I can't wait for next week's installment.\n\nI'll relaunch gcc trunk compilation before the end of the week.\n\n-- \nFabien.\n\n\n", "msg_date": "Mon, 2 Sep 2019 06:58:42 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: moonjelly vs tsearch" }, { "msg_contents": "\n>> News from Fabien's bleeding edge compiler zoo: apparently GCC 10 \n>> 20190831 thinks the tsearch test should produce different output than \n>> 20190824 did. It looks like the parsing of question marks change...\n>\n> Indeed, that looks pretty strange.\n>\n>> I can't wait for next week's installment.\n>\n> I'll relaunch gcc trunk compilation before the end of the week.\n\nIt did not do anything then, but this Saturday update fixed the issue.\n\n-- \nFabien.\n\n\n", "msg_date": "Sun, 8 Sep 2019 06:35:41 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: moonjelly vs tsearch" } ]
[ { "msg_contents": "Hi\n\n\npg_basebackup -F t fails when fsync spends more time than tcp_user_timeout in following environment.\n\n[Environment]\nPostgres 13dev (master branch)\nRed Hat Enterprise Postgres 7.4\n\n[Error]\n$ pg_basebackup -F t --progress --verbose -h <hostname> -D <directory>\npg_basebackup: initiating base backup, waiting for checkpoint to complete\npg_basebackup: checkpoint completed\npg_basebackup: write-ahead log start point: 0/5A000060 on timeline 1\npg_basebackup: starting background WAL receiver\npg_basebackup: created temporary replication slot \"pg_basebackup_15647\"\npg_basebackup: error: could not read COPY data: server closed the connection unexpectedly\n This probably means the server terminated abnormally\n before or while processing the request.\n\n[Analysis]\n- pg_basebackup -F t creates a tar file and does fsync() for each tablespace.\n (Otherwise, -F p does fsync() only once at the end.)\n- While doing fsync() for a tar file for one tablespace, wal sender sends the content of the next tablespace.\n When fsync() spends long time, the tcp socket of pg_basebackup returns \"zero window\" packets to wal sender.\n This means the tcp socket buffer of pg_basebackup is exhausted since pg_basebackup cannot receive during fsync().\n- The socket of wal sender retries to send the packet, but resets connection after tcp_user_timeout.\n After wal sender resets connection, pg_basebackup cannot receive data and fails with above error.\n\n[Solution]\nI think fsync() for each tablespace is not necessary.\nLike pg_basebackup -F p, I think fsync() is necessary only once at the end.\n\n\nCould you give me any comment?\n\n\nRegards,\nRyohei Takahashi\n\n\n\n", "msg_date": "Mon, 2 Sep 2019 04:42:55 +0000", "msg_from": "\"r.takahashi_2@fujitsu.com\" <r.takahashi_2@fujitsu.com>", "msg_from_op": true, "msg_subject": "pg_basebackup -F t fails when fsync spends more time than\n tcp_user_timeout" }, { "msg_contents": "On Mon, Sep 02, 2019 at 04:42:55AM +0000, r.takahashi_2@fujitsu.com wrote:\n> I think fsync() for each tablespace is not necessary.\n> Like pg_basebackup -F p, I think fsync() is necessary only once at the end.\n\nYes, I agree that we overlooked that part when introducing\ntcp_user_timeout. It is possible to sync all the contents of\npg_basebackup's tar format once at the end with fsync_dir_recurse().\n\nLooking at the original discussion that brought bc34223b, the proposed\npatches did what we have now on HEAD but we did not really exchange\nabout doing a fsync() just at the end with all the result base\ndirectory contents:\nhttps://www.postgresql.org/message-id/CAB7nPqQL0fCp0eDcVD6+3+Je24xeApU14vKz_pBpNA0sTPwLgQ@mail.gmail.com\n\nAttached is a patch to do that, which should go down to v12 where\ntcp_user_timeout has been introduced. Takahashi-san, what do you\nthink?\n--\nMichael", "msg_date": "Mon, 2 Sep 2019 15:40:57 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pg_basebackup -F t fails when fsync spends more time than\n tcp_user_timeout" }, { "msg_contents": "Hi Michael-san,\n\n\n> Attached is a patch to do that, which should go down to v12 where\n> tcp_user_timeout has been introduced. Takahashi-san, what do you\n> think?\n\nThank you for creating the patch.\nThis patch is what I expected.\n\nI'm not sure whether this patch should be applied to postgres below 11\nsince I'm not sure whether the OS parameters (ex. tcp_retries2) cause the same error.\n\nRegards,\nRyohei Takahashi\n\n\n\n", "msg_date": "Mon, 2 Sep 2019 08:06:22 +0000", "msg_from": "\"r.takahashi_2@fujitsu.com\" <r.takahashi_2@fujitsu.com>", "msg_from_op": true, "msg_subject": "RE: pg_basebackup -F t fails when fsync spends more time than\n tcp_user_timeout" }, { "msg_contents": "On Mon, Sep 02, 2019 at 08:06:22AM +0000, r.takahashi_2@fujitsu.com wrote:\n> I'm not sure whether this patch should be applied to postgres below 11\n> since I'm not sure whether the OS parameters (ex. tcp_retries2) cause the same error.\n\nThinking wider, don't we have the same problem with wal_sender_timeout\nin the case where a sync request takes longer than the time it would\ntake the backend to terminate the connection?\n--\nMichael", "msg_date": "Mon, 2 Sep 2019 17:38:56 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pg_basebackup -F t fails when fsync spends more time than\n tcp_user_timeout" }, { "msg_contents": "On Mon, Sep 02, 2019 at 05:38:56PM +0900, Michael Paquier wrote:\n> Thinking wider, don't we have the same problem with wal_sender_timeout\n> in the case where a sync request takes longer than the time it would\n> take the backend to terminate the connection?\n\nI have been able to work more on that, and that can indeed happen with\nwal_sender_timeout. While reviewing the code, I have noticed that\nthere is little point to enable do_sync when fetching WAL segments.\nThis actually led to too many fsyncs done for the plain format as each\nWAL segment is fsync'd first by walmethods.c, then fsync'd again by\nfsync_pgdata() in pg_wal/.\n\nAttached is an updated patch, which needs to go down to v10.\n--\nMichael", "msg_date": "Tue, 3 Sep 2019 10:58:18 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pg_basebackup -F t fails when fsync spends more time than\n tcp_user_timeout" }, { "msg_contents": "On Tue, Sep 03, 2019 at 10:58:18AM +0900, Michael Paquier wrote:\n> Attached is an updated patch, which needs to go down to v10.\n\nCommitted, after doing more double-checks on it. Thanks for the\nreport, Takahashi-san.\n--\nMichael", "msg_date": "Wed, 4 Sep 2019 13:27:40 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: pg_basebackup -F t fails when fsync spends more time than\n tcp_user_timeout" } ]
[ { "msg_contents": "Hi!\n\nAndrey Borodin noticed me that results of some KNN-GIST tests are\nobviously wrong and don't match results of sort node.\n\nSELECT * FROM point_tbl ORDER BY f1 <-> '0,1';\n f1\n-------------------\n (10,10)\n (NaN,NaN)\n (0,0)\n (1e-300,-1e-300)\n (-3,4)\n (-10,0)\n (-5,-12)\n (5.1,34.5)\n\n (1e+300,Infinity)\n(10 rows)\n\nIt appears to be related to implementation of comparison function in\npairing heap used as priority queue for KNN. It used plain float\ncomparison, which doesn't handle Inf and Nan values well. Attached\npatch replaced it with float8_cmp_internal().\n\nAlso, note that with patch KNN results still don't fully match results\nof sort node.\n\nSELECT * FROM point_tbl ORDER BY f1 <-> '0,1';\n f1\n-------------------\n (0,0)\n (1e-300,-1e-300)\n (-3,4)\n (-10,0)\n (10,10)\n (-5,-12)\n (5.1,34.5)\n (1e+300,Infinity)\n\n (NaN,NaN)\n(10 rows)\n\nNULL and '(NaN,NaN)' are swapped. It happens so, because we assume\ndistance to NULL to be Inf, while float8_cmp_internal() assumes NaN to\nbe greater than NULL. If even we would assume distance to NULL to be\nNan, it doesn't guarantee that NULLs would be last. It looks like we\ncan handle this only by introduction array of \"distance is null\" flags\nto GISTSearchItem. But does it worth it?\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Mon, 2 Sep 2019 07:54:11 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Bug in GiST paring heap comparator" }, { "msg_contents": "\n\n> 2 сент. 2019 г., в 9:54, Alexander Korotkov <a.korotkov@postgrespro.ru> написал(а):\n> \n> It appears to be related to implementation of comparison function in\n> pairing heap used as priority queue for KNN. It used plain float\n> comparison, which doesn't handle Inf and Nan values well. Attached\n> patch replaced it with float8_cmp_internal().\n\nThanks! This patch fixes tests of my new GiST build :)\n\nWhile patch looks good to me, I want to add that that there's a lot of <= and > comparisons in gistproc.c in function:\n\nstatic float8\ncomputeDistance(bool isLeaf, BOX *box, Point *point)\n\nShould we fix this too? Or add comment why current code is safe.\n\nThanks!\n\nBest regards, Andrey Borodin.\n\n", "msg_date": "Mon, 2 Sep 2019 10:11:42 +0500", "msg_from": "Andrey Borodin <x4mmm@yandex-team.ru>", "msg_from_op": false, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On 02/09/2019 07:54, Alexander Korotkov wrote:\n> Andrey Borodin noticed me that results of some KNN-GIST tests are\n> obviously wrong and don't match results of sort node.\n> \n> SELECT * FROM point_tbl ORDER BY f1 <-> '0,1';\n> f1\n> -------------------\n> (10,10)\n> (NaN,NaN)\n> (0,0)\n> (1e-300,-1e-300)\n> (-3,4)\n> (-10,0)\n> (-5,-12)\n> (5.1,34.5)\n> \n> (1e+300,Infinity)\n> (10 rows)\n\nSo we've memorized incorrect results in the expected output. Ouch!\n\n> It appears to be related to implementation of comparison function in\n> pairing heap used as priority queue for KNN. It used plain float\n> comparison, which doesn't handle Inf and Nan values well. Attached\n> patch replaced it with float8_cmp_internal().\n> \n> Also, note that with patch KNN results still don't fully match results\n> of sort node.\n> \n> SELECT * FROM point_tbl ORDER BY f1 <-> '0,1';\n> f1\n> -------------------\n> (0,0)\n> (1e-300,-1e-300)\n> (-3,4)\n> (-10,0)\n> (10,10)\n> (-5,-12)\n> (5.1,34.5)\n> (1e+300,Infinity)\n> \n> (NaN,NaN)\n> (10 rows)\n> \n> NULL and '(NaN,NaN)' are swapped. It happens so, because we assume\n> distance to NULL to be Inf, while float8_cmp_internal() assumes NaN to\n> be greater than NULL. If even we would assume distance to NULL to be\n> Nan, it doesn't guarantee that NULLs would be last. It looks like we\n> can handle this only by introduction array of \"distance is null\" flags\n> to GISTSearchItem. But does it worth it?\n\nI don't think we have much choice, returning wrong results is not an \noption. At first I thought we could set the \"recheck\" flag if we see \nNULLs or NaNs, but that won't work because rechecking is not supported \nwith Index-Only Scans.\n\nLooking at the corresponding SP-GiST code, \npairingheap_SpGistSearchItem_cmp() gets this right. I'd suggest \ncopy-pasting the implementation from there, so that they would be as \nsimilar as possible. (SP-GiST gets away with just one isNull flag, \nbecause it doesn't support multi-column indexes. In GiST, you need an \narray, as you said.)\n\n- Heikki\n\n\n", "msg_date": "Mon, 2 Sep 2019 09:28:02 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": false, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On Mon, Sep 2, 2019 at 9:28 AM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n> On 02/09/2019 07:54, Alexander Korotkov wrote:\n> > NULL and '(NaN,NaN)' are swapped. It happens so, because we assume\n> > distance to NULL to be Inf, while float8_cmp_internal() assumes NaN to\n> > be greater than NULL. If even we would assume distance to NULL to be\n> > Nan, it doesn't guarantee that NULLs would be last. It looks like we\n> > can handle this only by introduction array of \"distance is null\" flags\n> > to GISTSearchItem. But does it worth it?\n>\n> I don't think we have much choice, returning wrong results is not an\n> option. At first I thought we could set the \"recheck\" flag if we see\n> NULLs or NaNs, but that won't work because rechecking is not supported\n> with Index-Only Scans.\n>\n> Looking at the corresponding SP-GiST code,\n> pairingheap_SpGistSearchItem_cmp() gets this right. I'd suggest\n> copy-pasting the implementation from there, so that they would be as\n> similar as possible. (SP-GiST gets away with just one isNull flag,\n> because it doesn't support multi-column indexes. In GiST, you need an\n> array, as you said.)\n\nThank you for clarifying my doubts.\n\nSecond of attached patches solves this problem. In this patch\nGISTSearchItem have both array of distances and array of null flags at\nthe end. They are accessed by a bit cumbersome\nGISTSearchItemDistanceValues() and GISTSearchItemDistanceNulls()\nmacros. I came up to this, because I didn't like to allocate null\nflags or distances in separate chunk of memory. Also I had idea to\nwrap distance and null flag into struct, but I didn't like to change\nsignature of index_store_float8_orderby_distances() that much.\n\nI'm going to push both if no objections.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 6 Sep 2019 17:44:52 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On Fri, Sep 6, 2019 at 5:44 PM Alexander Korotkov\n<a.korotkov@postgrespro.ru> wrote:\n> I'm going to push both if no objections.\n\nSo, pushed!\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Sun, 8 Sep 2019 22:32:08 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On 08.09.2019 22:32, Alexander Korotkov wrote:\n\n> On Fri, Sep 6, 2019 at 5:44 PM Alexander Korotkov\n> <a.korotkov@postgrespro.ru> wrote:\n>> I'm going to push both if no objections.\n> So, pushed!\n\nTwo years ago there was a similar patch for this issue:\nhttps://www.postgresql.org/message-id/1499c9d0-075a-3014-d2aa-ba59121b3728%40postgrespro.ru\n\nSorry that I looked at this thread too late.\n\n-- \nNikita Glukhov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Mon, 9 Sep 2019 20:30:00 +0300", "msg_from": "Nikita Glukhov <n.gluhov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On Mon, Sep 9, 2019 at 8:32 PM Nikita Glukhov <n.gluhov@postgrespro.ru> wrote:\n> On 08.09.2019 22:32, Alexander Korotkov wrote:\n>\n> > On Fri, Sep 6, 2019 at 5:44 PM Alexander Korotkov\n> > <a.korotkov@postgrespro.ru> wrote:\n> >> I'm going to push both if no objections.\n> > So, pushed!\n>\n> Two years ago there was a similar patch for this issue:\n> https://www.postgresql.org/message-id/1499c9d0-075a-3014-d2aa-ba59121b3728%40postgrespro.ru\n>\n> Sorry that I looked at this thread too late.\n\nI see, thanks.\n\nYou patch seems a bit less cumbersome thanks to using GISTDistance\nstruct. You don't have to introduce separate array with null flags.\nBut it's harder too keep index_store_float8_orderby_distances() used\nby both GiST and SP-GiST.\n\nWhat do you think? You can rebase your patch can propose that as refactoring.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Mon, 9 Sep 2019 22:47:37 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On 09.09.2019 22:47, Alexander Korotkov wrote:\n> On Mon, Sep 9, 2019 at 8:32 PM Nikita Glukhov <n.gluhov@postgrespro.ru> wrote:\n>> On 08.09.2019 22:32, Alexander Korotkov wrote:\n>>\n>>> On Fri, Sep 6, 2019 at 5:44 PM Alexander Korotkov\n>>> <a.korotkov@postgrespro.ru> wrote:\n>>>> I'm going to push both if no objections.\n>>> So, pushed!\n>> Two years ago there was a similar patch for this issue:\n>> https://www.postgresql.org/message-id/1499c9d0-075a-3014-d2aa-ba59121b3728%40postgrespro.ru\n>>\n>> Sorry that I looked at this thread too late.\n> I see, thanks.\n>\n> You patch seems a bit less cumbersome thanks to using GISTDistance\n> struct. You don't have to introduce separate array with null flags.\n> But it's harder too keep index_store_float8_orderby_distances() used\n> by both GiST and SP-GiST.\n>\n> What do you think? You can rebase your patch can propose that as refactoring.\n\nRebased patch with refactoring is attached.\n\nDuring this rebase I found that SP-GiST code has similar problems with NULLs.\nAll SP-GiST functions do not check SK_ISNULL flag of ordering ScanKeys, and\nthat leads to segfaults. In the following test, index is searched with\nnon-NULL key first and then with NULL key, that leads to a crash:\n\nCREATE TABLE t AS SELECT point(x, y) p\nFROM generate_series(0, 100) x, generate_series(0, 100) y;\n\nCREATE INDEX ON t USING spgist (p);\n\n-- crash\nSELECT (SELECT p FROM t ORDER BY p <-> pt LIMIT 1)\nFROM (VALUES (point '1,2'), (NULL)) pts(pt);\n\n\nAfter adding SK_ISNULL checks and starting to produce NULL distances, we need to\nstore NULL flags for distance somewhere. Existing singleton flag for the whole\nSPGistSearchItem is not sufficient anymore.\n\n\nSo, I introduced structure IndexOrderByDistance and used it everywhere in the\nGiST and SP-GiST code instead of raw double distances.\n\n\nSP-GiST order-by-distance code can be further refactored so that user functions\ndo not have to worry about SK_ISNULL checks.\n\n\n-- \nNikita Glukhov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Wed, 11 Sep 2019 03:31:34 +0300", "msg_from": "Nikita Glukhov <n.gluhov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On Wed, Sep 11, 2019 at 3:34 AM Nikita Glukhov <n.gluhov@postgrespro.ru> wrote:\n> On 09.09.2019 22:47, Alexander Korotkov wrote:\n>\n> On Mon, Sep 9, 2019 at 8:32 PM Nikita Glukhov <n.gluhov@postgrespro.ru> wrote:\n>\n> On 08.09.2019 22:32, Alexander Korotkov wrote:\n>\n> On Fri, Sep 6, 2019 at 5:44 PM Alexander Korotkov\n> <a.korotkov@postgrespro.ru> wrote:\n>\n> I'm going to push both if no objections.\n>\n> So, pushed!\n>\n> Two years ago there was a similar patch for this issue:\n> https://www.postgresql.org/message-id/1499c9d0-075a-3014-d2aa-ba59121b3728%40postgrespro.ru\n>\n> Sorry that I looked at this thread too late.\n>\n> I see, thanks.\n>\n> You patch seems a bit less cumbersome thanks to using GISTDistance\n> struct. You don't have to introduce separate array with null flags.\n> But it's harder too keep index_store_float8_orderby_distances() used\n> by both GiST and SP-GiST.\n>\n> What do you think? You can rebase your patch can propose that as refactoring.\n>\n> Rebased patch with refactoring is attached.\n>\n> During this rebase I found that SP-GiST code has similar problems with NULLs.\n> All SP-GiST functions do not check SK_ISNULL flag of ordering ScanKeys, and\n> that leads to segfaults. In the following test, index is searched with\n> non-NULL key first and then with NULL key, that leads to a crash:\n>\n> CREATE TABLE t AS SELECT point(x, y) p\n> FROM generate_series(0, 100) x, generate_series(0, 100) y;\n>\n> CREATE INDEX ON t USING spgist (p);\n>\n> -- crash\n> SELECT (SELECT p FROM t ORDER BY p <-> pt LIMIT 1)\n> FROM (VALUES (point '1,2'), (NULL)) pts(pt);\n>\n>\n> After adding SK_ISNULL checks and starting to produce NULL distances, we need to\n> store NULL flags for distance somewhere. Existing singleton flag for the whole\n> SPGistSearchItem is not sufficient anymore.\n>\n>\n> So, I introduced structure IndexOrderByDistance and used it everywhere in the\n> GiST and SP-GiST code instead of raw double distances.\n>\n>\n> SP-GiST order-by-distance code can be further refactored so that user functions\n> do not have to worry about SK_ISNULL checks.\n\nIt doesn't seem SP-GiST inner_consistent and leaf_consistent functions\ncan handle NULL scan keys for now. So should we let them handle NULL\norderby keys? If we assume that NULL arguments produce NULL\ndistances, we can evade changing the code of opclasses.\n\nAlso, I've noticed IndexOrderByDistance is missed in typedefs.list.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Thu, 12 Sep 2019 16:45:19 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On 12.09.2019 16:45, Alexander Korotkov wrote:\n> On Wed, Sep 11, 2019 at 3:34 AM Nikita Glukhov <n.gluhov@postgrespro.ru> wrote:\n>> On 09.09.2019 22:47, Alexander Korotkov wrote:\n>>\n>> On Mon, Sep 9, 2019 at 8:32 PM Nikita Glukhov <n.gluhov@postgrespro.ru> wrote:\n>>\n>> On 08.09.2019 22:32, Alexander Korotkov wrote:\n>>\n>> On Fri, Sep 6, 2019 at 5:44 PM Alexander Korotkov\n>> <a.korotkov@postgrespro.ru> wrote:\n>>\n>> I'm going to push both if no objections.\n>>\n>> So, pushed!\n>>\n>> Two years ago there was a similar patch for this issue:\n>> https://www.postgresql.org/message-id/1499c9d0-075a-3014-d2aa-ba59121b3728%40postgrespro.ru\n>>\n>> Sorry that I looked at this thread too late.\n>>\n>> I see, thanks.\n>>\n>> You patch seems a bit less cumbersome thanks to using GISTDistance\n>> struct. You don't have to introduce separate array with null flags.\n>> But it's harder too keep index_store_float8_orderby_distances() used\n>> by both GiST and SP-GiST.\n>>\n>> What do you think? You can rebase your patch can propose that as refactoring.\n>>\n>> Rebased patch with refactoring is attached.\n>>\n>> During this rebase I found that SP-GiST code has similar problems with NULLs.\n>> All SP-GiST functions do not check SK_ISNULL flag of ordering ScanKeys, and\n>> that leads to segfaults. In the following test, index is searched with\n>> non-NULL key first and then with NULL key, that leads to a crash:\n>>\n>> CREATE TABLE t AS SELECT point(x, y) p\n>> FROM generate_series(0, 100) x, generate_series(0, 100) y;\n>>\n>> CREATE INDEX ON t USING spgist (p);\n>>\n>> -- crash\n>> SELECT (SELECT p FROM t ORDER BY p <-> pt LIMIT 1)\n>> FROM (VALUES (point '1,2'), (NULL)) pts(pt);\n>>\n>>\n>> After adding SK_ISNULL checks and starting to produce NULL distances, we need to\n>> store NULL flags for distance somewhere. Existing singleton flag for the whole\n>> SPGistSearchItem is not sufficient anymore.\n>>\n>>\n>> So, I introduced structure IndexOrderByDistance and used it everywhere in the\n>> GiST and SP-GiST code instead of raw double distances.\n>>\n>>\n>> SP-GiST order-by-distance code can be further refactored so that user functions\n>> do not have to worry about SK_ISNULL checks.\n> It doesn't seem SP-GiST inner_consistent and leaf_consistent functions\n> can handle NULL scan keys for now. So should we let them handle NULL\n> orderby keys? If we assume that NULL arguments produce NULL\n> distances, we can evade changing the code of opclasses.\nI have moved handling of NULL ordering keys from opclasses to the common\nSP-GiST code, but really I don't like how it is implemented now. Maybe it's\nworth to move handling of NULL order-by keys to the even more higher \nlevel so,\nthat AM don't have to worry about NULLs?\n\nAlso I leaved usages of IndexOrderByDistance in opclasses. I think, that \nmay\nhelp to minimize opclass changes in the future.\n\n> Also, I've noticed IndexOrderByDistance is missed in typedefs.list.\nFixed.\n\n-- \nNikita Glukhov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 13 Sep 2019 17:20:30 +0300", "msg_from": "Nikita Glukhov <n.gluhov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On Fri, Sep 13, 2019 at 5:23 PM Nikita Glukhov <n.gluhov@postgrespro.ru> wrote:\n> I have moved handling of NULL ordering keys from opclasses to the common\n> SP-GiST code, but really I don't like how it is implemented now. Maybe it's\n> worth to move handling of NULL order-by keys to the even more higher\n> level so,\n> that AM don't have to worry about NULLs?\n\nYes, optimizer could remove away \"col op NULL\" clauses from ORDER BY\nif op is strict operator. And then such clauses wouldn't be passed to\nAM. But I see this as future improvement. For backpatching we should\nsolve this at AM side.\n\n> Also I leaved usages of IndexOrderByDistance in opclasses. I think, that\n> may\n> help to minimize opclass changes in the future.\n\nCould you please extract this as a separate patch. We can consider\nthis for master, but we shouldn't backpatch this.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Fri, 13 Sep 2019 20:17:23 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On 13.09.2019 20:17, Alexander Korotkov wrote:\n\n> On Fri, Sep 13, 2019 at 5:23 PM Nikita Glukhov <n.gluhov@postgrespro.ru> wrote:\n>> I have moved handling of NULL ordering keys from opclasses to the common\n>> SP-GiST code, but really I don't like how it is implemented now. Maybe it's\n>> worth to move handling of NULL order-by keys to the even more higher\n>> level so,\n>> that AM don't have to worry about NULLs?\n> Yes, optimizer could remove away \"col op NULL\" clauses from ORDER BY\n> if op is strict operator. And then such clauses wouldn't be passed to\n> AM. But I see this as future improvement. For backpatching we should\n> solve this at AM side.\n>\n>> Also I leaved usages of IndexOrderByDistance in opclasses. I think, that\n>> may help to minimize opclass changes in the future.\n> Could you please extract this as a separate patch. We can consider\n> this for master, but we shouldn't backpatch this.\n\nPropagation of IndexOrderByDistance in SP-GiST was extracted into a separate\npatch #2.\n\n-- \nNikita Glukhov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Mon, 16 Sep 2019 15:44:07 +0300", "msg_from": "Nikita Glukhov <n.gluhov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On Mon, Sep 16, 2019 at 3:47 PM Nikita Glukhov <n.gluhov@postgrespro.ru> wrote:\n> On 13.09.2019 20:17, Alexander Korotkov wrote:\n>\n> On Fri, Sep 13, 2019 at 5:23 PM Nikita Glukhov <n.gluhov@postgrespro.ru> wrote:\n>\n> I have moved handling of NULL ordering keys from opclasses to the common\n> SP-GiST code, but really I don't like how it is implemented now. Maybe it's\n> worth to move handling of NULL order-by keys to the even more higher\n> level so,\n> that AM don't have to worry about NULLs?\n>\n> Yes, optimizer could remove away \"col op NULL\" clauses from ORDER BY\n> if op is strict operator. And then such clauses wouldn't be passed to\n> AM. But I see this as future improvement. For backpatching we should\n> solve this at AM side.\n>\n> Also I leaved usages of IndexOrderByDistance in opclasses. I think, that\n> may help to minimize opclass changes in the future.\n>\n> Could you please extract this as a separate patch. We can consider\n> this for master, but we shouldn't backpatch this.\n>\n> Propagation of IndexOrderByDistance in SP-GiST was extracted into a separate\n> patch #2.\n\nFirst patch is minor editing from me and commit message is attached.\nI'm going to push it if no objections.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Mon, 16 Sep 2019 22:30:38 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On Mon, Sep 16, 2019 at 10:30 PM Alexander Korotkov <\na.korotkov@postgrespro.ru> wrote:\n\n> On Mon, Sep 16, 2019 at 3:47 PM Nikita Glukhov <n.gluhov@postgrespro.ru>\n> wrote:\n> > On 13.09.2019 20:17, Alexander Korotkov wrote:\n> >\n> > On Fri, Sep 13, 2019 at 5:23 PM Nikita Glukhov <n.gluhov@postgrespro.ru>\n> wrote:\n> >\n> > I have moved handling of NULL ordering keys from opclasses to the common\n> > SP-GiST code, but really I don't like how it is implemented now. Maybe\n> it's\n> > worth to move handling of NULL order-by keys to the even more higher\n> > level so,\n> > that AM don't have to worry about NULLs?\n> >\n> > Yes, optimizer could remove away \"col op NULL\" clauses from ORDER BY\n> > if op is strict operator. And then such clauses wouldn't be passed to\n> > AM. But I see this as future improvement. For backpatching we should\n> > solve this at AM side.\n> >\n> > Also I leaved usages of IndexOrderByDistance in opclasses. I think, that\n> > may help to minimize opclass changes in the future.\n> >\n> > Could you please extract this as a separate patch. We can consider\n> > this for master, but we shouldn't backpatch this.\n> >\n> > Propagation of IndexOrderByDistance in SP-GiST was extracted into a\n> separate\n> > patch #2.\n>\n> First patch is minor editing from me and commit message is attached.\n> I'm going to push it if no objections.\n>\n\nPushed.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\nOn Mon, Sep 16, 2019 at 10:30 PM Alexander Korotkov <a.korotkov@postgrespro.ru> wrote:On Mon, Sep 16, 2019 at 3:47 PM Nikita Glukhov <n.gluhov@postgrespro.ru> wrote:\n> On 13.09.2019 20:17, Alexander Korotkov wrote:\n>\n> On Fri, Sep 13, 2019 at 5:23 PM Nikita Glukhov <n.gluhov@postgrespro.ru> wrote:\n>\n> I have moved handling of NULL ordering keys from opclasses to the common\n> SP-GiST code, but really I don't like how it is implemented now. Maybe it's\n> worth to move handling of NULL order-by keys to the even more higher\n> level so,\n> that AM don't have to worry about NULLs?\n>\n> Yes, optimizer could remove away \"col op NULL\" clauses from ORDER BY\n> if op is strict operator.  And then such clauses wouldn't be passed to\n> AM.  But I see this as future improvement.  For backpatching we should\n> solve this at AM side.\n>\n> Also I leaved usages of IndexOrderByDistance in opclasses. I think, that\n> may help to minimize opclass changes in the future.\n>\n> Could you please extract this as a separate patch.  We can consider\n> this for master, but we shouldn't backpatch this.\n>\n> Propagation of IndexOrderByDistance in SP-GiST was extracted into a separate\n> patch #2.\n\nFirst patch is minor editing from me and commit message is attached.\nI'm going to push it if no objections.Pushed.------Alexander KorotkovPostgres Professional: http://www.postgrespro.comThe Russian Postgres Company", "msg_date": "Thu, 19 Sep 2019 22:14:38 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On 19.09.2019 22:14, Alexander Korotkov wrote:\n> Pushed.\n\nAttached patch fixes premature xs_orderbynulls[] assignment.  The old value of\nNULL flag, not the new, should be checked before pfree()ing the old value.\n\n\n--\nNikita Glukhov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Fri, 20 Sep 2019 00:15:23 +0300", "msg_from": "Nikita Glukhov <n.gluhov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On 20.09.2019 0:15, Nikita Glukhov wrote:\n> On 19.09.2019 22:14, Alexander Korotkov wrote:\n>> Pushed.\n> Attached patch fixes premature xs_orderbynulls[] assignment.  The old value\n> of NULL flag, not the new, should be checked before pfree()ing the old value.\n\nAttached another one-line patch that fixes incorrect number of distances used\nin pairingheap_SpGistSearchItem_cmp():\n\n- for (i = 0; i < so->numberOfOrderBys; i++)\n+ for (i = 0; i < so->numberOfNonNullOrderBys; i++)\n\n\nThis change was present in my original commit, but it seems to have been\nmissed after the rebase. Sorry.\n\n--\nNikita Glukhov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company", "msg_date": "Wed, 25 Sep 2019 01:19:52 +0300", "msg_from": "Nikita Glukhov <n.gluhov@postgrespro.ru>", "msg_from_op": false, "msg_subject": "Re: Bug in GiST paring heap comparator" }, { "msg_contents": "On Wed, Sep 25, 2019 at 1:22 AM Nikita Glukhov <n.gluhov@postgrespro.ru> wrote:\n> Attached another one-line patch that fixes incorrect number of distances used\n> in pairingheap_SpGistSearchItem_cmp():\n>\n> - for (i = 0; i < so->numberOfOrderBys; i++)\n> + for (i = 0; i < so->numberOfNonNullOrderBys; i++)\n>\n>\n> This change was present in my original commit, but it seems to have been\n> missed after the rebase. Sorry.\n\nPushed, thanks.\n\n------\nAlexander Korotkov\nPostgres Professional: http://www.postgrespro.com\nThe Russian Postgres Company\n\n\n", "msg_date": "Wed, 25 Sep 2019 01:57:03 +0300", "msg_from": "Alexander Korotkov <a.korotkov@postgrespro.ru>", "msg_from_op": true, "msg_subject": "Re: Bug in GiST paring heap comparator" } ]
[ { "msg_contents": "We have the following options in pg_dump:\n\n--exclude-schema=schema\n--exclude-table=table\n--exclude-table-data=table\n\nand new in pg_dumpall:\n\n--exclude-database=pattern\n\nI was momentarily confused that the latter is documented as taking a\n\"pattern\" but the others are not. Of course they all take the same kind\nof pattern.\n\nShould we change the documentation of the old pg_dump options to also\ntake a \"pattern\", or change the documentation of the new pg_dumpall\noption to read \"database\"?\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 2 Sep 2019 08:32:22 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "pg_dump --exclude-* options documentation" }, { "msg_contents": "> We have the following options in pg_dump:\n>\n> --exclude-schema=schema\n> --exclude-table=table\n> --exclude-table-data=table\n>\n> and new in pg_dumpall:\n>\n> --exclude-database=pattern\n>\n> I was momentarily confused that the latter is documented as taking a\n> \"pattern\" but the others are not. Of course they all take the same kind\n> of pattern.\n>\n> Should we change the documentation of the old pg_dump options to also\n> take a \"pattern\", or change the documentation of the new pg_dumpall\n> option to read \"database\"?\n\nMy 0.02€: we should use the more general and precise, i.e. pattern.\n\n-- \nFabien.", "msg_date": "Mon, 2 Sep 2019 08:34:56 +0200 (CEST)", "msg_from": "Fabien COELHO <coelho@cri.ensmp.fr>", "msg_from_op": false, "msg_subject": "Re: pg_dump --exclude-* options documentation" }, { "msg_contents": "Fabien COELHO <coelho@cri.ensmp.fr> writes:\n>> Should we change the documentation of the old pg_dump options to also\n>> take a \"pattern\", or change the documentation of the new pg_dumpall\n>> option to read \"database\"?\n\n> My 0.02€: we should use the more general and precise, i.e. pattern.\n\n+1 ... it doesn't seem to me that \"--exclude-schema=schema\" conveys\nanything useful.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Mon, 02 Sep 2019 10:55:01 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: pg_dump --exclude-* options documentation" }, { "msg_contents": "On 2019-09-02 16:55, Tom Lane wrote:\n> Fabien COELHO <coelho@cri.ensmp.fr> writes:\n>>> Should we change the documentation of the old pg_dump options to also\n>>> take a \"pattern\", or change the documentation of the new pg_dumpall\n>>> option to read \"database\"?\n> \n>> My 0.02€: we should use the more general and precise, i.e. pattern.\n> \n> +1 ... it doesn't seem to me that \"--exclude-schema=schema\" conveys\n> anything useful.\n\ndone\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 3 Sep 2019 14:28:17 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": true, "msg_subject": "Re: pg_dump --exclude-* options documentation" } ]
[ { "msg_contents": "Hello all,\n\nI've been working on an extension that tightly integrates\npostgres with underlying filesystem . I need to customize\nhow postgres copies directories for new databases.\n\nI first looked at the ProcessUtility_hook. This would require\nme to copy or rewrite most of the createdb() function. This is\nless than ideal of course. Someone on the IRC channel\nsuggested I could add a hook for copydir().\n\nI implemented the hook similar to how the\nProcessUtility_hook is implemented. I couldn't find any tests\nfor any of the existing hooks. I've been looking at the regression\ntests, but I am not entirely sure how to proceed on that front.\n\nI tested my patch extensively against master and\nthe REL_12_STABLE branch. All tests pass and the patch has\nbeen working great with my extension.\n\nI attached a first draft of the patch against master.\n\n---\nSwen Kooij", "msg_date": "Mon, 2 Sep 2019 21:54:53 +0300", "msg_from": "Swen Kooij <swenkooij@gmail.com>", "msg_from_op": true, "msg_subject": "Patch to add hook to copydir()" }, { "msg_contents": "I just realized I completely borked the patch file.\n\nMy apologies. Attached a (hopefully) correct patch file.\n\n---\nSwen Kooij\n\nOn Mon, Sep 2, 2019 at 9:54 PM Swen Kooij <swenkooij@gmail.com> wrote:\n>\n> Hello all,\n>\n> I've been working on an extension that tightly integrates\n> postgres with underlying filesystem . I need to customize\n> how postgres copies directories for new databases.\n>\n> I first looked at the ProcessUtility_hook. This would require\n> me to copy or rewrite most of the createdb() function. This is\n> less than ideal of course. Someone on the IRC channel\n> suggested I could add a hook for copydir().\n>\n> I implemented the hook similar to how the\n> ProcessUtility_hook is implemented. I couldn't find any tests\n> for any of the existing hooks. I've been looking at the regression\n> tests, but I am not entirely sure how to proceed on that front.\n>\n> I tested my patch extensively against master and\n> the REL_12_STABLE branch. All tests pass and the patch has\n> been working great with my extension.\n>\n> I attached a first draft of the patch against master.\n>\n> ---\n> Swen Kooij", "msg_date": "Mon, 2 Sep 2019 22:04:40 +0300", "msg_from": "Swen Kooij <swenkooij@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Patch to add hook to copydir()" }, { "msg_contents": "On 2019-09-02 20:54, Swen Kooij wrote:\n> I've been working on an extension that tightly integrates\n> postgres with underlying filesystem . I need to customize\n> how postgres copies directories for new databases.\n\nCould you share some more details, so we can assess whether that is a\nsensible way to go about it, and what other hooks might be needed?\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 2 Sep 2019 21:18:38 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Patch to add hook to copydir()" }, { "msg_contents": "On 2019-Sep-02, Peter Eisentraut wrote:\n\n> On 2019-09-02 20:54, Swen Kooij wrote:\n> > I've been working on an extension that tightly integrates\n> > postgres with underlying filesystem . I need to customize\n> > how postgres copies directories for new databases.\n> \n> Could you share some more details, so we can assess whether that is a\n> sensible way to go about it, and what other hooks might be needed?\n\nIt seems either terribly high-level, or terribly low-level, depending on\nhow you look at it. I wonder to what extent it conflicts with the table\nAM work, and with the idea of allowing FDWs to have real relfilenodes.\nI wonder if this is just one missing piece that's needed to complete\nsomething of a layer for which other pieces are already satisfied by\nother hooks.\n\nAs is and pending further explanation, it seems a bad idea to me. If we\nwant pluggability here, maybe we need some new abstraction layer.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 2 Sep 2019 16:06:11 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Patch to add hook to copydir()" }, { "msg_contents": "Thank you both for the feedback. To give some background\non what I am trying to do. Mostly experimental work right now.\n\nI've built an extension that takes advantage of the copy-on-write\nproperties of ZFS and BTRFS. A tool transforms a data directory\ninto a set of datasets/sub volumes. When a new database is\ncreated and the directories are copied, the extension uses the\nfilesystem's ability to create a snapshot/clone of the source dataset/sub\nvolume.\n\nAs createdb() iterates over the template database's tablespaces\nand copies the directories to the new one, the copydir() gets invoked\n(from dbcommands.c). My extension hooks copydir() and instead\nsnapshots the source dir and clones it into the target dir (respecting the\nrecurse flag).\n\nIf the source dir is not a ZFS data set or BTRFS sub volume, the\nstandard implementation gets invoked and everything is business\nas usual.\n\nAs described in the first paragraph, I've built a small tool that transforms\nall base/* directories in the data directory into ZFS datasets or BTRFS\nsub volumes. New tablespaces that get created later would have to be\nZFS datasets or BTRFS sub volumes as well in order for the extension\nto work. As explained above, if they are not, the extension will just copy\nthe files.\n\nI also hook ProcessUtility in order to clean up the ZFS datasets and\nBTRFS subvolumes _after_ a database gets deleted. Postgres just\nhandles the deletion of the files and the extension cleans up any\ndangling ZFS/BTRFS resources.\n\nIs there anything that I am missing? My early experiments have been\nvery promising but my experience with Postgres internals is limited. Any\nhelp or feedback would be much appreciated.\n\nOn Mon, Sep 2, 2019 at 11:06 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n>\n> On 2019-Sep-02, Peter Eisentraut wrote:\n>\n> > On 2019-09-02 20:54, Swen Kooij wrote:\n> > > I've been working on an extension that tightly integrates\n> > > postgres with underlying filesystem . I need to customize\n> > > how postgres copies directories for new databases.\n> >\n> > Could you share some more details, so we can assess whether that is a\n> > sensible way to go about it, and what other hooks might be needed?\n>\n> It seems either terribly high-level, or terribly low-level, depending on\n> how you look at it. I wonder to what extent it conflicts with the table\n> AM work, and with the idea of allowing FDWs to have real relfilenodes.\n> I wonder if this is just one missing piece that's needed to complete\n> something of a layer for which other pieces are already satisfied by\n> other hooks.\n>\n> As is and pending further explanation, it seems a bad idea to me. If we\n> want pluggability here, maybe we need some new abstraction layer.\n>\n> --\n> Álvaro Herrera https://www.2ndQuadrant.com/\n> PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Mon, 2 Sep 2019 23:16:00 +0300", "msg_from": "Swen Kooij <swenkooij@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Patch to add hook to copydir()" }, { "msg_contents": "On 2019-09-02 22:16, Swen Kooij wrote:\n> Is there anything that I am missing? My early experiments have been\n> very promising but my experience with Postgres internals is limited. Any\n> help or feedback would be much appreciated.\n\nYou might want to review several previous threads that were\ncontemplating doing some reflink stuff with btrfs during database\ncreation. Not exactly what you are doing, but related.\n\nAlso, wouldn't it work if your extension just defined its own copydir()\nin the .so? That should then be used over the built-in one -- maybe.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 3 Sep 2019 08:48:29 +0200", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: Patch to add hook to copydir()" }, { "msg_contents": "I read two previous proposals for something similar.\n\nFirst one is from 2013 [0]. It proposed a OS and filesystem specific\nimplementation. Which was then changed to a patch that adds a\nconfig option to specify shell commands that postgres should use\nfor copying files and dirs. This was after commentary that such a\nfeature is better suited for an extension. Which is what I am trying to do.\n\nWhat was true in 2013 (when the other patch was proposed) is still\ntrue. There's no good way at the moment to hook into how postgres\ncopies files and directories.\n\nThe second thread I found from 2018 [1] proposes filesystem specific\nchanges (BTRFS, APFS and XFS) that operate on a file level. Really\nnice patch actually, but much more invasive than what I am proposing.\n\n\nBoth patches make rather invasive and significant changes specific\nto the features they're trying to build. The general sentiment I got\nfrom reading those two threads is that building in support for these\nkind of features is hard and is probably better first done as an extension.\n\nI understand that the patch I proposed is not an ideal interface,\nbut it gets the job done without having to built this kind of\nfunctionality into postgres. I am not proposing any filesystem\nor OS specific hooks/changes in postgres to make this work.\n\nI tried to override the copydir() function without any hooks\nand I haven't gotten it to work yet. If it does, I'd still prefer the\nhook. It's more predictable and probably more portable.\n\n[0] https://www.postgresql.org/message-id/511B5D11.4040507@socialserve.com\n[1] https://www.postgresql.org/message-id/bc9ca382-b98d-0446-f699-8c5de2307ca7%402ndquadrant.com\n\nOn Tue, Sep 3, 2019 at 9:48 AM Peter Eisentraut\n<peter.eisentraut@2ndquadrant.com> wrote:\n>\n> On 2019-09-02 22:16, Swen Kooij wrote:\n> > Is there anything that I am missing? My early experiments have been\n> > very promising but my experience with Postgres internals is limited. Any\n> > help or feedback would be much appreciated.\n>\n> You might want to review several previous threads that were\n> contemplating doing some reflink stuff with btrfs during database\n> creation. Not exactly what you are doing, but related.\n>\n> Also, wouldn't it work if your extension just defined its own copydir()\n> in the .so? That should then be used over the built-in one -- maybe.\n>\n> --\n> Peter Eisentraut http://www.2ndQuadrant.com/\n> PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 3 Sep 2019 12:14:28 +0300", "msg_from": "Swen Kooij <swenkooij@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Patch to add hook to copydir()" }, { "msg_contents": "Should I forget about getting such a patch in?\n\nI am up for implementing alternative solutions if the current\none is considered unacceptable. As I tried to demonstrate\nin my last email, previous attempts also failed.\n\nOn Tue, Sep 3, 2019 at 12:14 PM Swen Kooij <swenkooij@gmail.com> wrote:\n>\n> I read two previous proposals for something similar.\n>\n> First one is from 2013 [0]. It proposed a OS and filesystem specific\n> implementation. Which was then changed to a patch that adds a\n> config option to specify shell commands that postgres should use\n> for copying files and dirs. This was after commentary that such a\n> feature is better suited for an extension. Which is what I am trying to do.\n>\n> What was true in 2013 (when the other patch was proposed) is still\n> true. There's no good way at the moment to hook into how postgres\n> copies files and directories.\n>\n> The second thread I found from 2018 [1] proposes filesystem specific\n> changes (BTRFS, APFS and XFS) that operate on a file level. Really\n> nice patch actually, but much more invasive than what I am proposing.\n>\n>\n> Both patches make rather invasive and significant changes specific\n> to the features they're trying to build. The general sentiment I got\n> from reading those two threads is that building in support for these\n> kind of features is hard and is probably better first done as an extension.\n>\n> I understand that the patch I proposed is not an ideal interface,\n> but it gets the job done without having to built this kind of\n> functionality into postgres. I am not proposing any filesystem\n> or OS specific hooks/changes in postgres to make this work.\n>\n> I tried to override the copydir() function without any hooks\n> and I haven't gotten it to work yet. If it does, I'd still prefer the\n> hook. It's more predictable and probably more portable.\n>\n> [0] https://www.postgresql.org/message-id/511B5D11.4040507@socialserve.com\n> [1] https://www.postgresql.org/message-id/bc9ca382-b98d-0446-f699-8c5de2307ca7%402ndquadrant.com\n>\n> On Tue, Sep 3, 2019 at 9:48 AM Peter Eisentraut\n> <peter.eisentraut@2ndquadrant.com> wrote:\n> >\n> > On 2019-09-02 22:16, Swen Kooij wrote:\n> > > Is there anything that I am missing? My early experiments have been\n> > > very promising but my experience with Postgres internals is limited. Any\n> > > help or feedback would be much appreciated.\n> >\n> > You might want to review several previous threads that were\n> > contemplating doing some reflink stuff with btrfs during database\n> > creation. Not exactly what you are doing, but related.\n> >\n> > Also, wouldn't it work if your extension just defined its own copydir()\n> > in the .so? That should then be used over the built-in one -- maybe.\n> >\n> > --\n> > Peter Eisentraut http://www.2ndQuadrant.com/\n> > PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Sat, 7 Sep 2019 09:48:25 +0300", "msg_from": "Swen Kooij <swenkooij@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Patch to add hook to copydir()" } ]
[ { "msg_contents": "Hi,\n\nRight now, when assertions are enabled, using castNode() on a pointer to\nconst triggers a warning for my compilers:\nwarning: passing argument 2 of ‘castNodeImpl’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]\n\nwhich seems appropriate. Obviously we could easily suppress that just by\nadding an explicit cast into the castNode definition or to the\ncaller. But it strikes me as a somewhat legitimate warning.\n\nOn gcc etc we could fairly easily reformulate castNodeImpl() to not\ntrigger the above warning, but we'd still cast constness away due to the\nreturn type cast.\n\n#ifdef USE_ASSERT_CHECKING\n...\n#define castNode(_type_, nodeptr) ((_type_ *) castNodeImpl(T_##_type_, nodeptr))\n#else\n#define castNode(_type_, nodeptr) ((_type_ *) (nodeptr))\n#endif\t\t\t\t\t\t\t/* USE_ASSERT_CHECKING */\n\nISTM adding a castConstNode or castNodeConst would make sense?\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Tue, 3 Sep 2019 01:44:17 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": true, "msg_subject": "Const version of castNode()" } ]
[ { "msg_contents": "Hi pgsql hackers,\n\nI'd like to ask you for kind advice with problem I'm pretty long stuck on. I simplified it just to two tables and trigger. I described it thoroughly on Stack Overflow a week ago but nobody responded so far, so I was advised by Czech PG expert Pavel Stěhule to use this forum.\n\nDatabase setup:\n\n------------\ncreate table detail (\n id bigint not null,\n code varchar(255) not null,\n primary key (id)\n);\n\ncreate table master (\n id bigint not null,\n name varchar(255),\n detail_id bigint, -- \"preferred\" detail is one-to-one relation\n primary key (id),\n unique (detail_id),\n foreign key (detail_id) references detail(id)\n);\n\ncreate or replace function trgf() returns trigger as $$\nbegin\n return NEW;\nend;\n$$ language plpgsql;\n\ncreate trigger trg\n before insert or update\n on master\n for each row execute procedure trgf();\n\ninsert into master (id, name) values (1000, 'x');\ninsert into detail (code, id) values ('a', 1);\n\ncreate extension pgrowlocks;\n------------\n\nIn psql console, I open first transaction and run:\n\npostgres=# begin;\nBEGIN\npostgres=# update master set detail_id=null, name='y' where id=1000;\nUPDATE 1\n\nIn another psql console, I run:\n\npostgres=# select * from pgrowlocks('master');\n locked_row | locker | multi | xids | modes | pids\n------------+--------+-------+-------+----------+-------\n (0,3) | 564 | f | {564} | {Update} | {138}\n(1 row)\n\nNote the mode is Update, which means the attempt of taking FOR KEY SHARE lock is not successful:\n\npostgres=# set statement_timeout = 4000;\nSET\npostgres=# SELECT 1 FROM ONLY \"public\".\"master\" x WHERE \"id\" OPERATOR(pg_catalog.=) 1000 FOR KEY SHARE OF x;\nERROR: canceling statement due to statement timeout\nCONTEXT: while locking tuple (0,3) in relation \"master\"\n\nThis is ok. What is weird: this behaviour disappears when whole experiment is performed without trigger trg set up on master table. Mode is then No Key Update, which lets second transaction to acquire FOR KEY SHARE lock and perform select correctly. (Actually there's another table representing many-to-many relation between master and detail, at first I obtained timeout during attempt of insert binding row.)\n\nSo what I can't understand is:\n\n1. Why the rowlock mode is only No Key Update in case without trigger? According to https://www.postgresql.org/docs/9.6/explicit-locking.html#LOCKING-ROWS , thanks to unique constraint on master.detail_id column, the rowlock mode should be Update anyway, shouldn't it? Why is it Update only after adding trigger?\n\n2. How to make this case working with trigger on the table? I need it to be there, it worked before trigger addition.\n\nI reproduced it on Postgres 9.6.12 (embedded), 9.6.15 (in Docker) and 11.5 (in Docker).\nI dockerized database with setup above to DockerHub image tomaszalusky/trig-example , Dockerfile here: https://gist.github.com/tomaszalusky/4b953c678c806408025d05d984d30ed3 \nOriginal SO question: https://stackoverflow.com/q/57681970/653539 (captures some history of my investigations which I consider unnecessary to state here)\n\nThank you for all the effort.\n\nTomáš Záluský\n\n\n", "msg_date": "Tue, 03 Sep 2019 14:56:02 +0200", "msg_from": "=?utf-8?q?Tom=C3=A1=C5=A1_Z=C3=A1lusk=C3=BD?= <zalusky@centrum.cz>", "msg_from_op": true, "msg_subject": "=?utf-8?q?unexpected_rowlock_mode_when_trigger_is_on_the_table?=" }, { "msg_contents": "On 2019-Sep-03, Tomáš Záluský wrote:\n\n> postgres=# begin;\n> BEGIN\n> postgres=# update master set detail_id=null, name='y' where id=1000;\n> UPDATE 1\n> \n> In another psql console, I run:\n> \n> postgres=# select * from pgrowlocks('master');\n> locked_row | locker | multi | xids | modes | pids\n> ------------+--------+-------+-------+----------+-------\n> (0,3) | 564 | f | {564} | {Update} | {138}\n> (1 row)\n\nHmm, so I'm guessing that this tuple lock comes from GetTupleForTrigger\ncalled from ExecBRUpdateTriggers, which uses ExecUpdateLockMode() in\norder to figure out the lockmode to use, depending on whether the\nmodified columns by the update overlap columns indexed by any unique\nindex. I think there should be no overlap (PK is column \"id\", not modified)\nbut I may be missing something.\n\n(gdb) bt\n#0 heap_lock_tuple (relation=relation@entry=0x7eff2157b4d8, \n tuple=tuple@entry=0x7ffe570db3e0, cid=0, \n mode=mode@entry=LockTupleExclusive, \n wait_policy=wait_policy@entry=LockWaitBlock, \n follow_updates=follow_updates@entry=0 '\\000', buffer=0x7ffe570db3cc, \n hufd=0x7ffe570db3d0)\n at /pgsql/source/REL9_6_STABLE/src/backend/access/heap/heapam.c:4577\n#1 0x00005648b1d52f15 in GetTupleForTrigger (\n estate=estate@entry=0x5648b3894110, \n epqstate=epqstate@entry=0x5648b3894750, tid=tid@entry=0x7ffe570db674, \n lockmode=LockTupleExclusive, newSlot=0x7ffe570db498, \n relinfo=<optimized out>, relinfo=<optimized out>)\n at /pgsql/source/REL9_6_STABLE/src/backend/commands/trigger.c:2709\n#2 0x00005648b1d579a0 in ExecBRUpdateTriggers (\n estate=estate@entry=0x5648b3894110, \n epqstate=epqstate@entry=0x5648b3894750, \n relinfo=relinfo@entry=0x5648b3894260, \n tupleid=tupleid@entry=0x7ffe570db674, \n fdw_trigtuple=fdw_trigtuple@entry=0x0, slot=slot@entry=0x5648b3896670)\n at /pgsql/source/REL9_6_STABLE/src/backend/commands/trigger.c:2432\n#3 0x00005648b1d8ddc2 in ExecUpdate (tupleid=tupleid@entry=0x7ffe570db674, \n oldtuple=oldtuple@entry=0x0, slot=slot@entry=0x5648b3896670, \n planSlot=planSlot@entry=0x5648b3895998, \n epqstate=epqstate@entry=0x5648b3894750, \n estate=estate@entry=0x5648b3894110, canSetTag=1 '\\001')\n at /pgsql/source/REL9_6_STABLE/src/backend/executor/nodeModifyTable.c:850\n\nMaybe we're passing an argument wrong somewhere. Unclear ...\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 4 Sep 2019 18:28:37 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: unexpected rowlock mode when trigger is on the table" }, { "msg_contents": "Thanks for response.\n\n> I think there should be no overlap (PK is column \"id\", not modified)\n\nThe update command sets the detail_id column which has unique constraint.\nIf I read documentation correctly (13.3.2. Row-level Locks), unique columns also count to columns whose presence in update statement causes choosing FOR UPDATE lock.\n\nWhat is unclear to me, why FOR NO KEY UPDATE is chosen when there is no trigger.\nPerhaps the execution path to ExecUpdateLockMode is somehow different?\nAnd if FOR NO KEY UPDATE is correct, how to achieve it also with trigger?\n\nTomáš\n\n\n______________________________________________________________\n> Od: \"Alvaro Herrera\" <alvherre@2ndquadrant.com>\n> Komu: \"Tomáš Záluský\" <zalusky@centrum.cz>\n> Datum: 05.09.2019 00:52\n> Předmět: Re: unexpected rowlock mode when trigger is on the table\n>\n> CC: <pgsql-hackers@postgresql.org>\n>On 2019-Sep-03, Tomáš Záluský wrote:\n>\n>> postgres=# begin;\n>> BEGIN\n>> postgres=# update master set detail_id=null, name='y' where id=1000;\n>> UPDATE 1\n>> \n>> In another psql console, I run:\n>> \n>> postgres=# select * from pgrowlocks('master');\n>> locked_row | locker | multi | xids | modes | pids\n>> ------------+--------+-------+-------+----------+-------\n>> (0,3) | 564 | f | {564} | {Update} | {138}\n>> (1 row)\n>\n>Hmm, so I'm guessing that this tuple lock comes from GetTupleForTrigger\n>called from ExecBRUpdateTriggers, which uses ExecUpdateLockMode() in\n>order to figure out the lockmode to use, depending on whether the\n>modified columns by the update overlap columns indexed by any unique\n>index. I think there should be no overlap (PK is column \"id\", not modified)\n>but I may be missing something.\n>\n>(gdb) bt\n>#0 heap_lock_tuple (relation=relation@entry=0x7eff2157b4d8, \n> tuple=tuple@entry=0x7ffe570db3e0, cid=0, \n> mode=mode@entry=LockTupleExclusive, \n> wait_policy=wait_policy@entry=LockWaitBlock, \n> follow_updates=follow_updates@entry=0 '\\000', buffer=0x7ffe570db3cc, \n> hufd=0x7ffe570db3d0)\n> at /pgsql/source/REL9_6_STABLE/src/backend/access/heap/heapam.c:4577\n>#1 0x00005648b1d52f15 in GetTupleForTrigger (\n> estate=estate@entry=0x5648b3894110, \n> epqstate=epqstate@entry=0x5648b3894750, tid=tid@entry=0x7ffe570db674, \n> lockmode=LockTupleExclusive, newSlot=0x7ffe570db498, \n> relinfo=<optimized out>, relinfo=<optimized out>)\n> at /pgsql/source/REL9_6_STABLE/src/backend/commands/trigger.c:2709\n>#2 0x00005648b1d579a0 in ExecBRUpdateTriggers (\n> estate=estate@entry=0x5648b3894110, \n> epqstate=epqstate@entry=0x5648b3894750, \n> relinfo=relinfo@entry=0x5648b3894260, \n> tupleid=tupleid@entry=0x7ffe570db674, \n> fdw_trigtuple=fdw_trigtuple@entry=0x0, slot=slot@entry=0x5648b3896670)\n> at /pgsql/source/REL9_6_STABLE/src/backend/commands/trigger.c:2432\n>#3 0x00005648b1d8ddc2 in ExecUpdate (tupleid=tupleid@entry=0x7ffe570db674, \n> oldtuple=oldtuple@entry=0x0, slot=slot@entry=0x5648b3896670, \n> planSlot=planSlot@entry=0x5648b3895998, \n> epqstate=epqstate@entry=0x5648b3894750, \n> estate=estate@entry=0x5648b3894110, canSetTag=1 '\\001')\n> at /pgsql/source/REL9_6_STABLE/src/backend/executor/nodeModifyTable.c:850\n>\n>Maybe we're passing an argument wrong somewhere. Unclear ...\n>\n>-- \n>Álvaro Herrera https://www.2ndQuadrant.com/\n>PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n>\n>\n>\n>\n\n\n", "msg_date": "Thu, 05 Sep 2019 10:35:55 +0200", "msg_from": "=?utf-8?q?Tom=C3=A1=C5=A1_Z=C3=A1lusk=C3=BD?= <zalusky@centrum.cz>", "msg_from_op": true, "msg_subject": "\n =?utf-8?q?Re=3A_unexpected_rowlock_mode_when_trigger_is_on_the_table?=" }, { "msg_contents": "On 2019-Sep-05, Tomáš Záluský wrote:\n\n> Thanks for response.\n> \n> > I think there should be no overlap (PK is column \"id\", not modified)\n> \n> The update command sets the detail_id column which has unique constraint.\n\nOh, I see, yeah that explains it.\n\n> What is unclear to me, why FOR NO KEY UPDATE is chosen when there is no trigger.\n> Perhaps the execution path to ExecUpdateLockMode is somehow different?\n\nheap_update on its own uses a slightly different method to determine\nwhich columns are modified -- see HeapDetermineModifiedColumns. In this\ncase, since the old value is NULL and the updated value is NULL, that\nfunction decides that the column has not changed and thus it doesn't\nneed the stronger lock. I bet it would work differently if you had a\ndifferent detail_id originally, or if you set it to a different value\nafterwards.\n\n> And if FOR NO KEY UPDATE is correct, how to achieve it also with trigger?\n\nNot sure that's feasible, short of patching the Pg source.\n\n-- \nÁlvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 5 Sep 2019 09:30:32 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: unexpected rowlock mode when trigger is on the table" }, { "msg_contents": "I confirm the update statement with new value distinct from old value causes taking FOR UPDATE lock.\nIn my original example, the `set detail_id=null` clause is actually generated by Hibernate and was preserved during example minification.\nSo I'll have to either find a way how to stop generating unnecessary clauses or refactor database to avoid detail_id column at all.\n\nPatching PG source is not option for me at this moment, however, chapter 13.3.2 in documentation could be improved to explicitly state 1. the unchanged value of key/unique column causes FOR NO KEY UPDATE lock and 2. the sole usage of key/unique column in statement causes FOR UPDATE lock when table has trigger.\n\nThank you for clarification.\n\n\n______________________________________________________________\n> Od: \"Alvaro Herrera\" <alvherre@2ndquadrant.com>\n> Komu: \"Tomáš Záluský\" <zalusky@centrum.cz>\n> Datum: 05.09.2019 16:00\n> Předmět: Re: unexpected rowlock mode when trigger is on the table\n>\n> CC: <pgsql-hackers@postgresql.org>\n>On 2019-Sep-05, Tomáš Záluský wrote:\n>\n>> Thanks for response.\n>> \n>> > I think there should be no overlap (PK is column \"id\", not modified)\n>> \n>> The update command sets the detail_id column which has unique constraint.\n>\n>Oh, I see, yeah that explains it.\n>\n>> What is unclear to me, why FOR NO KEY UPDATE is chosen when there is no trigger.\n>> Perhaps the execution path to ExecUpdateLockMode is somehow different?\n>\n>heap_update on its own uses a slightly different method to determine\n>which columns are modified -- see HeapDetermineModifiedColumns. In this\n>case, since the old value is NULL and the updated value is NULL, that\n>function decides that the column has not changed and thus it doesn't\n>need the stronger lock. I bet it would work differently if you had a\n>different detail_id originally, or if you set it to a different value\n>afterwards.\n>\n>> And if FOR NO KEY UPDATE is correct, how to achieve it also with trigger?\n>\n>Not sure that's feasible, short of patching the Pg source.\n>\n>-- \n>Álvaro Herrera https://www.2ndQuadrant.com/\n>PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n>\n>\n>\n>\n\n\n", "msg_date": "Fri, 06 Sep 2019 14:44:21 +0200", "msg_from": "=?utf-8?q?Tom=C3=A1=C5=A1_Z=C3=A1lusk=C3=BD?= <zalusky@centrum.cz>", "msg_from_op": true, "msg_subject": "\n =?utf-8?q?Re=3A_unexpected_rowlock_mode_when_trigger_is_on_the_table?=" } ]
[ { "msg_contents": "When you lock a row with FOR KEY SHARE, and the row's non-key columns \nhave been updated, heap_lock_tuple() walks the update chain to mark all \nthe in-progress tuple versions also as locked. But it doesn't pay \nattention to the NOWAIT or SKIP LOCKED flags when doing so. The \nheap_lock_updated_tuple() function walks the update chain, but the \n'wait_policy' argument is not passed to it. As a result, a SELECT in KEY \nSHARE NOWAIT query can block waiting for another updating transaction, \ndespite the NOWAIT modifier.\n\nThis can be reproduced with the attached isolation test script.\n\nI'm not sure how to fix this. The logic to walk the update chain and \npropagate the tuple lock is already breathtakingly complicated :-(.\n\n- Heikki", "msg_date": "Tue, 3 Sep 2019 16:22:30 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": true, "msg_subject": "Locking a row with KEY SHARE NOWAIT blocks" }, { "msg_contents": "Heikki Linnakangas <hlinnaka@iki.fi> writes:\n> When you lock a row with FOR KEY SHARE, and the row's non-key columns \n> have been updated, heap_lock_tuple() walks the update chain to mark all \n> the in-progress tuple versions also as locked. But it doesn't pay \n> attention to the NOWAIT or SKIP LOCKED flags when doing so. The \n> heap_lock_updated_tuple() function walks the update chain, but the \n> 'wait_policy' argument is not passed to it. As a result, a SELECT in KEY \n> SHARE NOWAIT query can block waiting for another updating transaction, \n> despite the NOWAIT modifier.\n\n> This can be reproduced with the attached isolation test script.\n\n> I'm not sure how to fix this. The logic to walk the update chain and \n> propagate the tuple lock is already breathtakingly complicated :-(.\n\nWhy are we locking any but the most recent version?\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 03 Sep 2019 09:31:36 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: Locking a row with KEY SHARE NOWAIT blocks" }, { "msg_contents": "On 03/09/2019 16:31, Tom Lane wrote:\n> Heikki Linnakangas <hlinnaka@iki.fi> writes:\n>> When you lock a row with FOR KEY SHARE, and the row's non-key columns\n>> have been updated, heap_lock_tuple() walks the update chain to mark all\n>> the in-progress tuple versions also as locked. But it doesn't pay\n>> attention to the NOWAIT or SKIP LOCKED flags when doing so. The\n>> heap_lock_updated_tuple() function walks the update chain, but the\n>> 'wait_policy' argument is not passed to it. As a result, a SELECT in KEY\n>> SHARE NOWAIT query can block waiting for another updating transaction,\n>> despite the NOWAIT modifier.\n> \n>> This can be reproduced with the attached isolation test script.\n> \n>> I'm not sure how to fix this. The logic to walk the update chain and\n>> propagate the tuple lock is already breathtakingly complicated :-(.\n> \n> Why are we locking any but the most recent version?\n\nDefine \"most recent\". In KEY SHARE mode, there can be multiple UPDATEd \nversions of the tuple, such that the updating transactions are still \nin-progress, but we can still acquire the lock. We need to lock the most \nrecent version, including any in-progress transactions that have updated \nthe row but not committed yet. Otherwise, the lock would be lost when \nthe transaction commits (or if the in-progress transaction updates the \nsame row again). But locking that tuple is not enough, because otherwise \nthe lock would be lost if the in-progress transaction that updated the \nrow aborts. We also need to lock the latest live tuple (HEAPTUPLE_LIVE), \nto avoid that. And if there are subtransactions involved, we need to be \nprepared for a rollback/commit of any of the subtransactions.\n\nHmm. I think this could be fixed by locking the tuples in reverse order, \nstarting from the latest in-progress updated version, walking the update \nchain backwards. While we're walking the chain, if we find that an \nupdating transaction has committed, so that we have already acquired a \nlock on the now live version, we can stop. And if we find that the \ntransaction has aborted, we start from scratch, i.e. find the now latest \nINSERT_IN_PROGRESS tuple version, and walk backwards from there.\n\nWalking an update chain backwards is a bit painful, but you can walk \nforwards from the live tuple and remember the path, and walk backwards \nthe same path once you reach the end of the chain.\n\n- Heikki\n\n\n", "msg_date": "Tue, 3 Sep 2019 17:21:30 +0300", "msg_from": "Heikki Linnakangas <hlinnaka@iki.fi>", "msg_from_op": true, "msg_subject": "Re: Locking a row with KEY SHARE NOWAIT blocks" }, { "msg_contents": "On Tue, Sep 3, 2019 at 6:58 PM Heikki Linnakangas <hlinnaka@iki.fi> wrote:\n>\n> When you lock a row with FOR KEY SHARE, and the row's non-key columns\n> have been updated, heap_lock_tuple() walks the update chain to mark all\n> the in-progress tuple versions also as locked. But it doesn't pay\n> attention to the NOWAIT or SKIP LOCKED flags when doing so. The\n> heap_lock_updated_tuple() function walks the update chain, but the\n> 'wait_policy' argument is not passed to it. As a result, a SELECT in KEY\n> SHARE NOWAIT query can block waiting for another updating transaction,\n> despite the NOWAIT modifier.\n>\n> This can be reproduced with the attached isolation test script.\n>\n> I'm not sure how to fix this. The logic to walk the update chain and\n> propagate the tuple lock is already breathtakingly complicated :-(.\n>\n\nCan't we pass the wait_policy parameter to heap_lock_updated_tuple and\ndo the same handling as we do in the caller (heap_lock_tuple)?\nBasically, whenever we need to wait on any tuple version do the same\nas we do in heap_lock_tuple for 'require_sleep' case.\n\n-- \nWith Regards,\nAmit Kapila.\nEnterpriseDB: http://www.enterprisedb.com\n\n\n", "msg_date": "Thu, 5 Sep 2019 10:01:53 +0530", "msg_from": "Amit Kapila <amit.kapila16@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Locking a row with KEY SHARE NOWAIT blocks" } ]
[ { "msg_contents": "Shutdown postgres server immediately with pg_ctl stop -m immediate command.\nWhen I restart the server got following fatal message:\n-------------------------------------------\n126690 2019-09-03 14:06:52 UTC XX000 FATAL: could not access status of transaction 389225416\n126690 2019-09-03 14:06:52 UTC XX000 DETAIL: Could not read from file \"/1-1/kangda/pgdata/pg_xact/0E7F\" at offset 245760: Success.\n126690 2019-09-03 14:06:52 UTC XX000 CONTEXT: WAL redo at 237/B9FE02A8 for Transaction/COMMIT: 2019-09-03 10:42:06.086823+00\n------------------------------------------------\nI use pg_waldump to check xlog,and found this transaction was the first transaction after checkpoint.\n---------------------------------------------------\nrmgr: Btree len (rec/tot): 64/ 64, tx: 3892254157, lsn: 237/B9FDFBF0, prev 237/B9FDFBC8, desc: INSERT_LEAF off 97, blkref #0: rel 1663/259019/275985 blk 508\nrmgr: Transaction len (rec/tot): 34/ 34, tx: 3892254157, lsn: 237/B9FDFC30, prev 237/B9FDFBF0, desc: COMMIT 2019-09-03 18:42:06.086146 CST\nrmgr: Heap len (rec/tot): 245/ 245, tx: 3892254158, lsn: 237/B9FDFC58, prev 237/B9FDFC30, desc: INSERT off 37, blkref #0: rel 1663/259019/275784 blk 5740\nrmgr: Btree len (rec/tot): 64/ 64, tx: 3892254158, lsn: 237/B9FDFD50, prev 237/B9FDFC58, desc: INSERT_LEAF off 203, blkref #0: rel 1663/259019/275850 blk 585\nrmgr: Btree len (rec/tot): 64/ 64, tx: 3892254158, lsn: 237/B9FDFD90, prev 237/B9FDFD50, desc: INSERT_LEAF off 215, blkref #0: rel 1663/259019/275869 blk 188\nrmgr: Transaction len (rec/tot): 34/ 34, tx: 3892254158, lsn: 237/B9FDFDD0, prev 237/B9FDFD90, desc: COMMIT 2019-09-03 18:42:06.086162 CST\nrmgr: Heap len (rec/tot): 245/ 245, tx: 3892254161, lsn: 237/B9FDFDF8, prev 237/B9FDFDD0, desc: INSERT off 11, blkref #0: rel 1663/259019/275898 blk 5763\nrmgr: Standby len (rec/tot): 62/ 62, tx: 0, lsn: 237/B9FDFEF0, prev 237/B9FDFDF8, desc: RUNNING_XACTS nextXid 3892254162 latestCompletedXid 3892254158 oldestRunningXid 3892254159; 3 xacts: 3892254160 3892254161 3892254159\nrmgr: XLOG len (rec/tot): 106/ 106, tx: 0, lsn: 237/B9FDFF30, prev 237/B9FDFEF0, desc: CHECKPOINT_ONLINE redo 237/B7D65A10; tli 1; prev tli 1; fpw false; xid 0:3892180397; oid 283595; multi 5; offset 9; oldest xid 3451212705 in DB 13287; oldest multi 1 in DB 13286; oldest/newest commit timestamp xid: 0/0; oldest running xid 3892180384; online\nrmgr: Heap len (rec/tot): 245/ 245, tx: 3892254159, lsn: 237/B9FDFFA0, prev 237/B9FDFF30, desc: INSERT off 24, blkref #0: rel 1663/259019/275789 blk 5756\nrmgr: Btree len (rec/tot): 64/ 64, tx: 3892254161, lsn: 237/B9FE00B0, prev 237/B9FDFFA0, desc: INSERT_LEAF off 86, blkref #0: rel 1663/259019/275973 blk 586\nrmgr: Btree len (rec/tot): 64/ 64, tx: 3892254159, lsn: 237/B9FE00F0, prev 237/B9FE00B0, desc: INSERT_LEAF off 366, blkref #0: rel 1663/259019/275852 blk 585\nrmgr: Btree len (rec/tot): 64/ 64, tx: 3892254161, lsn: 237/B9FE0130, prev 237/B9FE00F0, desc: INSERT_LEAF off 88, blkref #0: rel 1663/259019/275991 blk 149\nrmgr: Btree len (rec/tot): 64/ 64, tx: 3892254159, lsn: 237/B9FE0170, prev 237/B9FE0130, desc: INSERT_LEAF off 20, blkref #0: rel 1663/259019/275865 blk 680\nrmgr: Heap len (rec/tot): 245/ 245, tx: 3892254160, lsn: 237/B9FE01B0, prev 237/B9FE0170, desc: INSERT off 16, blkref #0: rel 1663/259019/275900 blk 5753\nrmgr: Transaction len (rec/tot): 34/ 34, tx: 3892254161, lsn: 237/B9FE02A8, prev 237/B9FE01B0, desc: COMMIT 2019-09-03 18:42:06.086823 CST\nrmgr: Btree len (rec/tot): 64/ 64, tx: 3892254160, lsn: 237/B9FE02D0, prev 237/B9FE02A8, desc: INSERT_LEAF off 170, blkref #0: rel 1663/259019/275972 blk 585\nrmgr: Btree len (rec/tot): 64/ 64, tx: 3892254160, lsn: 237/B9FE0310, prev 237/B9FE02D0, desc: INSERT_LEAF off 146, blkref #0: rel 1663/259019/275989 blk 137\nrmgr: Transaction len (rec/tot): 34/ 34, tx: 3892254159, lsn: 237/B9FE0350, prev 237/B9FE0310, desc: COMMIT 2019-09-03 18:42:06.086830 CST\nrmgr: Transaction len (rec/tot): 34/ 34, tx: 3892254160, lsn: 237/B9FE0378, prev 237/B9FE0350, desc: COMMIT 2019-09-03 18:42:06.086834 CST \n-------------------------------------------------------------------\n\n\nThe call stack is\n#0 proc_exit (code=code@entry=1) at ipc.c:105\n#1 0x00000000009799c7 in errfinish (dummy=<optimized out>) at elog.c:557\n#2 0x000000000051a0b0 in SlruReportIOError (ctl=ctl@entry=0xe680c0 <ClogCtlData>, pageno=pageno@entry=118782, xid=xid@entry=3892254161) at slru.c:925\n#3 0x000000000051b524 in SimpleLruReadPage (ctl=ctl@entry=0xe680c0 <ClogCtlData>, pageno=118782, write_ok=<optimized out>, xid=xid@entry=3892254161) at slru.c:459\n#4 0x0000000000511ec2 in TransactionIdSetPageStatusInternal (xid=3892254161, nsubxids=0, subxids=0x0, status=1, lsn=0, pageno=<optimized out>) at clog.c:370\n#5 0x0000000000512787 in TransactionIdSetPageStatus (all_xact_same_page=true, pageno=118782, lsn=0, status=1, subxids=0x0, nsubxids=0, xid=3892254161) at clog.c:322\n#6 TransactionIdSetTreeStatus (xid=xid@entry=3892254161, nsubxids=<optimized out>, subxids=0x0, status=status@entry=1, lsn=lsn@entry=0) at clog.c:194\n#7 0x000000000051d41d in TransactionIdCommitTree (xid=xid@entry=3892254161, nxids=<optimized out>, xids=<optimized out>) at transam.c:262\n#8 0x0000000000521f3f in xact_redo_commit (parsed=parsed@entry=0x7fffc2219610, xid=3892254161, lsn=2438366888656, origin_id=<optimized out>) at xact.c:5629\n#9 0x0000000000526af3 in xact_redo (record=0x21ed058) at xact.c:5829\n#10 0x0000000000537539 in StartupXLOG () at xlog.c:7647\n#11 0x00000000007826fb in StartupProcessMain () at startup.c:213\n#12 0x0000000000562e95 in AuxiliaryProcessMain (argc=argc@entry=2, argv=argv@entry=0x7fffc221d8d0) at bootstrap.c:441\n#13 0x000000000077e7a4 in StartChildProcess (type=StartupProcess) at postmaster.c:5598\n#14 0x00000000007820eb in PostmasterMain (argc=argc@entry=3, argv=argv@entry=0x21b1cf0) at postmaster.c:1417\n#15 0x000000000048787b in main (argc=3, argv=0x21b1cf0) at main.c:228\n\n\nIs CLOG file flushed before commit log flushed to XLOG file?\n \nBest regards\n\n\nRay\n\n\nShutdown postgres server immediately with pg_ctl stop -m immediate command.When I restart the server got following fatal message:-------------------------------------------126690                          2019-09-03 14:06:52 UTC XX000                                           FATAL:  could not access status of transaction 389225416126690                          2019-09-03 14:06:52 UTC XX000                                           DETAIL:  Could not read from file \"/1-1/kangda/pgdata/pg_xact/0E7F\" at offset 245760: Success.126690                          2019-09-03 14:06:52 UTC XX000                                           CONTEXT:  WAL redo at 237/B9FE02A8 for Transaction/COMMIT: 2019-09-03 10:42:06.086823+00------------------------------------------------I use pg_waldump to check xlog,and found this transaction was the first transaction after checkpoint.---------------------------------------------------rmgr: Btree       len (rec/tot):     64/    64, tx: 3892254157, lsn: 237/B9FDFBF0, prev 237/B9FDFBC8, desc: INSERT_LEAF off 97, blkref #0: rel 1663/259019/275985 blk 508rmgr: Transaction len (rec/tot):     34/    34, tx: 3892254157, lsn: 237/B9FDFC30, prev 237/B9FDFBF0, desc: COMMIT 2019-09-03 18:42:06.086146 CSTrmgr: Heap        len (rec/tot):    245/   245, tx: 3892254158, lsn: 237/B9FDFC58, prev 237/B9FDFC30, desc: INSERT off 37, blkref #0: rel 1663/259019/275784 blk 5740rmgr: Btree       len (rec/tot):     64/    64, tx: 3892254158, lsn: 237/B9FDFD50, prev 237/B9FDFC58, desc: INSERT_LEAF off 203, blkref #0: rel 1663/259019/275850 blk 585rmgr: Btree       len (rec/tot):     64/    64, tx: 3892254158, lsn: 237/B9FDFD90, prev 237/B9FDFD50, desc: INSERT_LEAF off 215, blkref #0: rel 1663/259019/275869 blk 188rmgr: Transaction len (rec/tot):     34/    34, tx: 3892254158, lsn: 237/B9FDFDD0, prev 237/B9FDFD90, desc: COMMIT 2019-09-03 18:42:06.086162 CSTrmgr: Heap        len (rec/tot):    245/   245, tx: 3892254161, lsn: 237/B9FDFDF8, prev 237/B9FDFDD0, desc: INSERT off 11, blkref #0: rel 1663/259019/275898 blk 5763rmgr: Standby     len (rec/tot):     62/    62, tx:          0, lsn: 237/B9FDFEF0, prev 237/B9FDFDF8, desc: RUNNING_XACTS nextXid 3892254162 latestCompletedXid 3892254158 oldestRunningXid 3892254159; 3 xacts: 3892254160 3892254161 3892254159rmgr: XLOG        len (rec/tot):    106/   106, tx:          0, lsn: 237/B9FDFF30, prev 237/B9FDFEF0, desc: CHECKPOINT_ONLINE redo 237/B7D65A10; tli 1; prev tli 1; fpw false; xid 0:3892180397; oid 283595; multi 5; offset 9; oldest xid 3451212705 in DB 13287; oldest multi 1 in DB 13286; oldest/newest commit timestamp xid: 0/0; oldest running xid 3892180384; onlinermgr: Heap        len (rec/tot):    245/   245, tx: 3892254159, lsn: 237/B9FDFFA0, prev 237/B9FDFF30, desc: INSERT off 24, blkref #0: rel 1663/259019/275789 blk 5756rmgr: Btree       len (rec/tot):     64/    64, tx: 3892254161, lsn: 237/B9FE00B0, prev 237/B9FDFFA0, desc: INSERT_LEAF off 86, blkref #0: rel 1663/259019/275973 blk 586rmgr: Btree       len (rec/tot):     64/    64, tx: 3892254159, lsn: 237/B9FE00F0, prev 237/B9FE00B0, desc: INSERT_LEAF off 366, blkref #0: rel 1663/259019/275852 blk 585rmgr: Btree       len (rec/tot):     64/    64, tx: 3892254161, lsn: 237/B9FE0130, prev 237/B9FE00F0, desc: INSERT_LEAF off 88, blkref #0: rel 1663/259019/275991 blk 149rmgr: Btree       len (rec/tot):     64/    64, tx: 3892254159, lsn: 237/B9FE0170, prev 237/B9FE0130, desc: INSERT_LEAF off 20, blkref #0: rel 1663/259019/275865 blk 680rmgr: Heap        len (rec/tot):    245/   245, tx: 3892254160, lsn: 237/B9FE01B0, prev 237/B9FE0170, desc: INSERT off 16, blkref #0: rel 1663/259019/275900 blk 5753rmgr: Transaction len (rec/tot):     34/    34, tx: 3892254161, lsn: 237/B9FE02A8, prev 237/B9FE01B0, desc: COMMIT 2019-09-03 18:42:06.086823 CSTrmgr: Btree       len (rec/tot):     64/    64, tx: 3892254160, lsn: 237/B9FE02D0, prev 237/B9FE02A8, desc: INSERT_LEAF off 170, blkref #0: rel 1663/259019/275972 blk 585rmgr: Btree       len (rec/tot):     64/    64, tx: 3892254160, lsn: 237/B9FE0310, prev 237/B9FE02D0, desc: INSERT_LEAF off 146, blkref #0: rel 1663/259019/275989 blk 137rmgr: Transaction len (rec/tot):     34/    34, tx: 3892254159, lsn: 237/B9FE0350, prev 237/B9FE0310, desc: COMMIT 2019-09-03 18:42:06.086830 CSTrmgr: Transaction len (rec/tot):     34/    34, tx: 3892254160, lsn: 237/B9FE0378, prev 237/B9FE0350, desc: COMMIT 2019-09-03 18:42:06.086834 CST -------------------------------------------------------------------The call stack is#0  proc_exit (code=code@entry=1) at ipc.c:105#1  0x00000000009799c7 in errfinish (dummy=<optimized out>) at elog.c:557#2  0x000000000051a0b0 in SlruReportIOError (ctl=ctl@entry=0xe680c0 <ClogCtlData>, pageno=pageno@entry=118782, xid=xid@entry=3892254161) at slru.c:925#3  0x000000000051b524 in SimpleLruReadPage (ctl=ctl@entry=0xe680c0 <ClogCtlData>, pageno=118782, write_ok=<optimized out>, xid=xid@entry=3892254161) at slru.c:459#4  0x0000000000511ec2 in TransactionIdSetPageStatusInternal (xid=3892254161, nsubxids=0, subxids=0x0, status=1, lsn=0, pageno=<optimized out>) at clog.c:370#5  0x0000000000512787 in TransactionIdSetPageStatus (all_xact_same_page=true, pageno=118782, lsn=0, status=1, subxids=0x0, nsubxids=0, xid=3892254161) at clog.c:322#6  TransactionIdSetTreeStatus (xid=xid@entry=3892254161, nsubxids=<optimized out>, subxids=0x0, status=status@entry=1, lsn=lsn@entry=0) at clog.c:194#7  0x000000000051d41d in TransactionIdCommitTree (xid=xid@entry=3892254161, nxids=<optimized out>, xids=<optimized out>) at transam.c:262#8  0x0000000000521f3f in xact_redo_commit (parsed=parsed@entry=0x7fffc2219610, xid=3892254161, lsn=2438366888656, origin_id=<optimized out>) at xact.c:5629#9  0x0000000000526af3 in xact_redo (record=0x21ed058) at xact.c:5829#10 0x0000000000537539 in StartupXLOG () at xlog.c:7647#11 0x00000000007826fb in StartupProcessMain () at startup.c:213#12 0x0000000000562e95 in AuxiliaryProcessMain (argc=argc@entry=2, argv=argv@entry=0x7fffc221d8d0) at bootstrap.c:441#13 0x000000000077e7a4 in StartChildProcess (type=StartupProcess) at postmaster.c:5598#14 0x00000000007820eb in PostmasterMain (argc=argc@entry=3, argv=argv@entry=0x21b1cf0) at postmaster.c:1417#15 0x000000000048787b in main (argc=3, argv=0x21b1cf0) at main.c:228Is CLOG file flushed before commit log flushed to XLOG file?                                                                                                                    Best regardsRay", "msg_date": "Tue, 3 Sep 2019 23:22:14 +0800 (CST)", "msg_from": "Thunder <thunder1@126.com>", "msg_from_op": true, "msg_subject": "Got \"FATAL: could not access status of transaction\" in PG 11.2" } ]
[ { "msg_contents": "I've work in the a little patch to add into the \\conninfo of psql\ncommand the connection time against a server backend\n\nMaybe could add after, the precheck to if the connection is alive.\nI've take first look to the pqPacketSend, my idea is send a ECHO\npacket over to the database connection. If someone has a better idea\nit would be great to know.\n\nRegards!\n-- \nRodrigo Ramírez Norambuena\nhttp://www.rodrigoramirez.com/", "msg_date": "Tue, 3 Sep 2019 22:13:57 -0400", "msg_from": "=?UTF-8?Q?Rodrigo_Ram=C3=ADrez_Norambuena?= <decipher.hk@gmail.com>", "msg_from_op": true, "msg_subject": "[PATCH] Connection time for \\conninfo" }, { "msg_contents": "On Tue, Sep 03, 2019 at 10:13:57PM -0400, Rodrigo Ramírez Norambuena wrote:\n> I've work in the a little patch to add into the \\conninfo of psql\n> command the connection time against a server backend\n> \n> Maybe could add after, the precheck to if the connection is alive.\n> I've take first look to the pqPacketSend, my idea is send a ECHO\n> packet over to the database connection. If someone has a better idea\n> it would be great to know.\n\nYou can do basically the same thing by looking at\npg_stat_activity.backend_start and compare it with the clock\ntimestamp. Doing it at SQL level the way you want has also the\nadvantage to offer you a modular format output.\n--\nMichael", "msg_date": "Wed, 4 Sep 2019 12:06:04 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "On 2019-Sep-04, Michael Paquier wrote:\n\n> On Tue, Sep 03, 2019 at 10:13:57PM -0400, Rodrigo Ram�rez Norambuena wrote:\n> > I've work in the a little patch to add into the \\conninfo of psql\n> > command the connection time against a server backend\n> > \n> > Maybe could add after, the precheck to if the connection is alive.\n> > I've take first look to the pqPacketSend, my idea is send a ECHO\n> > packet over to the database connection. If someone has a better idea\n> > it would be great to know.\n> \n> You can do basically the same thing by looking at\n> pg_stat_activity.backend_start and compare it with the clock\n> timestamp. Doing it at SQL level the way you want has also the\n> advantage to offer you a modular format output.\n\nHmm, couldn't you say the same about the other details that \\conninfo\ngives? You can get them from pg_stat_activity or pg_stat_ssl, yet\nthey're still shown \\conninfo for convenience. Surely we don't want to\nremove everything from \\conninfo and tell users to query the stat views\ninstead.\n\nThe only thing that seems wrong about this proposal is that the time\nformat is a bit too verbose. I would have it do \"N days 12:23:34\".\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 4 Sep 2019 11:04:03 -0400", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "On Tue, Sep 3, 2019 at 11:06 PM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> You can do basically the same thing by looking at\n> pg_stat_activity.backend_start and compare it with the clock\n> timestamp. Doing it at SQL level the way you want has also the\n> advantage to offer you a modular format output.\n\nHi Michael,\n\nThanks you for paying attention, I appreciate this.\n\nWhat are you say seams little trick to what I propose in this patch\nbecause you'll need filter what is your connection, and if the\nconnection is through the connection pooler could be more.\n\nThe main goal this is only getting information from the client side\n(psql) as frontend.\n\nRegards!\n-- \nRodrigo Ramírez Norambuena\nhttp://www.rodrigoramirez.com/\n\n\n", "msg_date": "Thu, 5 Sep 2019 13:38:57 -0400", "msg_from": "=?UTF-8?Q?Rodrigo_Ram=C3=ADrez_Norambuena?= <decipher.hk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "On Wed, Sep 4, 2019 at 11:04 AM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n>\n> The only thing that seems wrong about this proposal is that the time\n> format is a bit too verbose. I would have it do \"N days 12:23:34\".\n>\n\nHi Alvaro!,\n\nI attach a second version with this change.\n\n-- \nRodrigo Ramírez Norambuena\nhttp://www.rodrigoramirez.com/", "msg_date": "Thu, 5 Sep 2019 13:40:02 -0400", "msg_from": "=?UTF-8?Q?Rodrigo_Ram=C3=ADrez_Norambuena?= <decipher.hk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "=?UTF-8?Q?Rodrigo_Ram=C3=ADrez_Norambuena?= <decipher.hk@gmail.com> writes:\n> On Tue, Sep 3, 2019 at 11:06 PM Michael Paquier <michael@paquier.xyz> wrote:\n>> You can do basically the same thing by looking at\n>> pg_stat_activity.backend_start and compare it with the clock\n>> timestamp. Doing it at SQL level the way you want has also the\n>> advantage to offer you a modular format output.\n\n> What are you say seams little trick to what I propose in this patch\n> because you'll need filter what is your connection, and if the\n> connection is through the connection pooler could be more.\n> The main goal this is only getting information from the client side\n> (psql) as frontend.\n\nA couple of thoughts on this ---\n\n* Michael's right that it's *possible* to get the session start time in\nSQL, but having to find one's session's entry in pg_stat_activity is\npretty awkward. I wonder if we should invent pg_backend_start_time()\nanalogous to pg_backend_pid(). Most of the other columns in\npg_stat_activity either already have similar functions (e.g. CURRENT_USER)\nor don't seem especially useful to be able to retrieve for one's own\nsession, but this one maybe is. That's somewhat orthogonal to the\nproposed patch but we should probably be considering it in the same\ndiscussion.\n\n* It's not quite clear what the use-case is for displaying this in\n\\conninfo. That's easy for humans to look at, but I don't really\nunderstand why a human would care, and it's just about useless for\nany programmatic application.\n\n* I wonder why the proposal is to display duration of connection rather\nthan start time. I don't especially like the idea that \\conninfo\nwould change every time you look at it, so I'd tend to lean to the\nlatter, but maybe there are other arguments for one or the other.\n\n* The patch appears to be tracking time measured at the client side,\nwhich is going to be just enough different from the server's idea of\nthe session start time to be confusing/annoying. Do we really want\nto do it that way?\n\n* There are other definitional questions like what happens when you\nreconnect (either due to intentional \\connect or momentary connection\nloss), or what should happen when you have no connection at all thanks\nto a non-recoverable connection loss. I suppose the patch's code\nprovides some answers but I'm not sure that it's consistent or well\nthought out. (Commit aef362385 provides some precedent you should look\nat in this regard, plus I think this patch has to be rebased over it\nanyway.)\n\nBTW, the result type of time(2) is not \"int\", so this is just wrong:\n\n+\tint connected; /* unixtime for connected init time */\n\nThis field name is pretty poorly chosen as well; it sounds like\nit's a boolean \"am I connected\" state, and there's certainly no\nhint that it's a time value.\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Thu, 05 Sep 2019 14:22:54 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "On Thu, Sep 5, 2019 at 2:22 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:\n>\n> =?UTF-8?Q?Rodrigo_Ram=C3=ADrez_Norambuena?= <decipher.hk@gmail.com> writes:\n> > On Tue, Sep 3, 2019 at 11:06 PM Michael Paquier <michael@paquier.xyz> wrote:\n> >> You can do basically the same thing by looking at\n> >> pg_stat_activity.backend_start and compare it with the clock\n> >> timestamp. Doing it at SQL level the way you want has also the\n> >> advantage to offer you a modular format output.\n>\n> > What are you say seams little trick to what I propose in this patch\n> > because you'll need filter what is your connection, and if the\n> > connection is through the connection pooler could be more.\n> > The main goal this is only getting information from the client side\n> > (psql) as frontend.\n>\n> A couple of thoughts on this ---\n> [...]\n\nHi Tom, about your concerns and feedback I send a new proposal of\npatch related with the original idea.\n\nRegards!\n-- \nRodrigo Ramírez Norambuena\nhttp://www.rodrigoramirez.com/", "msg_date": "Sat, 7 Sep 2019 21:30:41 -0400", "msg_from": "=?UTF-8?Q?Rodrigo_Ram=C3=ADrez_Norambuena?= <decipher.hk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "My opinion is that this is not particularly useful and not appropriate \nto piggy-back onto \\conninfo. Connection information including host, \nport, database, user name is a well-established concept in PostgreSQL \nprograms and tools and it contains a delimited set of information. \nKnowing what server and what database you are connected to also seems \nkind of important. Moreover, this is information that is under control \nof the client, so it must be tracked on the client side.\n\nKnowing how long you've been connected on the other hand seems kind of \nfundamentally unimportant. If we add that, what's to stop us from \nadding other statistics of minor interest such as how many commands \nyou've run, how many errors there were, etc. The connection time is \nalready available, and perhaps we should indeed make it a bit easier to \nget, but it doesn't need to be a psql command.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 27 Feb 2020 10:21:52 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "Hi Rodrigo,\n\nOn 2/27/20 4:21 AM, Peter Eisentraut wrote:\n> My opinion is that this is not particularly useful and not appropriate \n> to piggy-back onto \\conninfo.  Connection information including host, \n> port, database, user name is a well-established concept in PostgreSQL \n> programs and tools and it contains a delimited set of information. \n> Knowing what server and what database you are connected to also seems \n> kind of important.  Moreover, this is information that is under control \n> of the client, so it must be tracked on the client side.\n> \n> Knowing how long you've been connected on the other hand seems kind of \n> fundamentally unimportant.  If we add that, what's to stop us from \n> adding other statistics of minor interest such as how many commands \n> you've run, how many errors there were, etc.  The connection time is \n> already available, and perhaps we should indeed make it a bit easier to \n> get, but it doesn't need to be a psql command.\n\nThe consensus from the committers (with the exception of Álvaro) seems \nto be that this is not a feature we want. FWIW, I agree with the majority.\n\nI'll mark this as rejected on MAR-16 unless Álvaro makes an argument for \ncommitting it.\n\nRegards,\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Tue, 10 Mar 2020 12:50:48 -0400", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "Greetings,\n\n* David Steele (david@pgmasters.net) wrote:\n> On 2/27/20 4:21 AM, Peter Eisentraut wrote:\n> >My opinion is that this is not particularly useful and not appropriate to\n> >piggy-back onto \\conninfo.  Connection information including host, port,\n> >database, user name is a well-established concept in PostgreSQL programs\n> >and tools and it contains a delimited set of information. Knowing what\n> >server and what database you are connected to also seems kind of\n> >important.  Moreover, this is information that is under control of the\n> >client, so it must be tracked on the client side.\n\nI have to say that I disagree. Wishing to know when you connected to a\nserver is entirely reasonable and it's also rather clearly under control\nof the client (though I don't entirely understand that argument in the\nfirst place).\n\n> >Knowing how long you've been connected on the other hand seems kind of\n> >fundamentally unimportant.  If we add that, what's to stop us from adding\n> >other statistics of minor interest such as how many commands you've run,\n> >how many errors there were, etc.  The connection time is already\n> >available, and perhaps we should indeed make it a bit easier to get, but\n> >it doesn't need to be a psql command.\n\nOf 'minor' interest, or not, if it's something you'd like to know then\nit's pretty handy if there's a way to get that info. This also isn't\ninventing a new psql command but rather adding on to one that's clearly\nalready a 'creature comfort' command as everything included could be\ngotten at in other ways.\n\nAs for the comparison to other things of minor interest, we do give\nusers a way to get things like line number (%l in PROMPT), so including\nsomething akin to that certainly doesn't seem out of the question.\nHaving a '%T' or something in the prompt for connected-at-time seems\nlike it could certainly be useful too.\n\nGoing a bit farther, I wonder if conninfo could be configurable as a\nPrompt-like string, that seems like it'd be pretty neat.\n\nAnyway, I don't anticipate having time to do anything with this patch\nbut I disagree that this is a \"we don't want it\" kind of thing, rather\nwe maybe want it, since someone cared enough to write a patch, but the\npatch needs work and maybe we want it to look a bit different and be\nbetter defined.\n\nThanks,\n\nStephen", "msg_date": "Tue, 10 Mar 2020 13:38:01 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "On 2020-03-10 18:38, Stephen Frost wrote:\n>> On 2/27/20 4:21 AM, Peter Eisentraut wrote:\n>>> My opinion is that this is not particularly useful and not appropriate to\n>>> piggy-back onto \\conninfo.� Connection information including host, port,\n>>> database, user name is a well-established concept in PostgreSQL programs\n>>> and tools and it contains a delimited set of information. Knowing what\n>>> server and what database you are connected to also seems kind of\n>>> important.� Moreover, this is information that is under control of the\n>>> client, so it must be tracked on the client side.\n> \n> I have to say that I disagree. Wishing to know when you connected to a\n> server is entirely reasonable and it's also rather clearly under control\n> of the client (though I don't entirely understand that argument in the\n> first place).\n\nThe argument is that the server already knows when the client connected \nand that information is already available. So there is no reason for \nthe client to also track and display that information, other than \nperhaps convenience. But the server does not, in general, know what \nhost and port the client connected to (because of proxying and other \nnetwork stuff), so this is something that the client must record itself.\n\n-- \nPeter Eisentraut http://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 10 Mar 2020 18:44:45 +0100", "msg_from": "Peter Eisentraut <peter.eisentraut@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "Stephen Frost <sfrost@snowman.net> writes:\n> Anyway, I don't anticipate having time to do anything with this patch\n> but I disagree that this is a \"we don't want it\" kind of thing, rather\n> we maybe want it, since someone cared enough to write a patch, but the\n> patch needs work and maybe we want it to look a bit different and be\n> better defined.\n\nI think Peter's primary argument was that this doesn't belong in\n\\conninfo, which is about reporting the parameters required to\nestablish the connection. We have kind of broken that already by\ncramming SSL and GSS encryption info into the results, but that\ndoesn't mean it should become a kitchen-sink listing of anything\nanybody says they'd like to know.\n\nAnyway, I think your point is that maybe this should be RWF\nnot Rejected, and I agree with that.\n\n(I had not looked at the last version of the patch, but now that\nI have, I still don't like the fact that it has the client tracking\nsession start time separately from what the server does. The small\ndiscrepancy that introduces is going to confuse somebody. I see\nthat there's no documentation update either.)\n\n\t\t\tregards, tom lane\n\n\n", "msg_date": "Tue, 10 Mar 2020 14:03:20 -0400", "msg_from": "Tom Lane <tgl@sss.pgh.pa.us>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "Greetings,\n\n* Peter Eisentraut (peter.eisentraut@2ndquadrant.com) wrote:\n> On 2020-03-10 18:38, Stephen Frost wrote:\n> >>On 2/27/20 4:21 AM, Peter Eisentraut wrote:\n> >>>My opinion is that this is not particularly useful and not appropriate to\n> >>>piggy-back onto \\conninfo.  Connection information including host, port,\n> >>>database, user name is a well-established concept in PostgreSQL programs\n> >>>and tools and it contains a delimited set of information. Knowing what\n> >>>server and what database you are connected to also seems kind of\n> >>>important.  Moreover, this is information that is under control of the\n> >>>client, so it must be tracked on the client side.\n> >\n> >I have to say that I disagree. Wishing to know when you connected to a\n> >server is entirely reasonable and it's also rather clearly under control\n> >of the client (though I don't entirely understand that argument in the\n> >first place).\n> \n> The argument is that the server already knows when the client connected and\n> that information is already available. So there is no reason for the client\n> to also track and display that information, other than perhaps convenience.\n\nYes, it'd be for convenience.\n\n> But the server does not, in general, know what host and port the client\n> connected to (because of proxying and other network stuff), so this is\n> something that the client must record itself.\n\nI agree that there are some things the client has to track and not ask\nthe server for, because the server's answers could be different, but I\ndon't agree that conninfo should only ever include that info (and I\nseriously doubt that was the original idea, considering 'database' is\nincluded at least as far back as 1999..).\n\nAs a side-note, we should probably update our documentation for psql,\nsince the description of things under Prompting tends to presume that\nthere isn't anything between the client and the server (for example,\n%> says \"The port number at which the database server is listening.\",\nbut it's really \"The port number used to connect to the database\nserver.\" or something along those lines).\n\nThanks,\n\nStephen", "msg_date": "Tue, 10 Mar 2020 14:05:24 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "Greetings,\n\n* Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> Stephen Frost <sfrost@snowman.net> writes:\n> > Anyway, I don't anticipate having time to do anything with this patch\n> > but I disagree that this is a \"we don't want it\" kind of thing, rather\n> > we maybe want it, since someone cared enough to write a patch, but the\n> > patch needs work and maybe we want it to look a bit different and be\n> > better defined.\n> \n> I think Peter's primary argument was that this doesn't belong in\n> \\conninfo, which is about reporting the parameters required to\n> establish the connection. We have kind of broken that already by\n> cramming SSL and GSS encryption info into the results, but that\n> doesn't mean it should become a kitchen-sink listing of anything\n> anybody says they'd like to know.\n\nI could certainly agree with wanting to have a psql command that's \"give\nme what I need to connect\", but that idea and what conninfo actually\nreturns are pretty distant from each other. For one thing, if I wanted\nthat from psql, I'd sure hope to get back something that I could\ndirectly use when starting up a new psql session.\n\n> Anyway, I think your point is that maybe this should be RWF\n> not Rejected, and I agree with that.\n\nOk.\n\n> (I had not looked at the last version of the patch, but now that\n> I have, I still don't like the fact that it has the client tracking\n> session start time separately from what the server does. The small\n> discrepancy that introduces is going to confuse somebody. I see\n> that there's no documentation update either.)\n\nThis worries me about as much as I worry that someone's going to be\nconfused by explain-analyze output vs. \\timing. Yes, it happens, and\nactually pretty often, but I wouldn't change how it works because\nthey're two different things, not to mention that if I'm going to be\nimpacted by the time being off on one of the systems, I'd at least like\nto know when my client thought it connected relative to the clock on my\nclient.\n\nTHanks,\n\nStephen", "msg_date": "Tue, 10 Mar 2020 14:15:12 -0400", "msg_from": "Stephen Frost <sfrost@snowman.net>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "Hi There!\n\nI forgot about that ... It passed a little time from my new pushed\nchanges. So go ahead :)\n\nOn Tue, Mar 10, 2020 at 3:15 PM Stephen Frost <sfrost@snowman.net> wrote:\n>\n> Greetings,\n>\n> * Tom Lane (tgl@sss.pgh.pa.us) wrote:\n> > Stephen Frost <sfrost@snowman.net> writes:\n> > > Anyway, I don't anticipate having time to do anything with this patch\n> > > but I disagree that this is a \"we don't want it\" kind of thing, rather\n> > > we maybe want it, since someone cared enough to write a patch, but the\n> > > patch needs work and maybe we want it to look a bit different and be\n> > > better defined.\n> >\n> > I think Peter's primary argument was that this doesn't belong in\n> > \\conninfo, which is about reporting the parameters required to\n> > establish the connection. We have kind of broken that already by\n> > cramming SSL and GSS encryption info into the results, but that\n> > doesn't mean it should become a kitchen-sink listing of anything\n> > anybody says they'd like to know.\n>\n> I could certainly agree with wanting to have a psql command that's \"give\n> me what I need to connect\", but that idea and what conninfo actually\n> returns are pretty distant from each other. For one thing, if I wanted\n> that from psql, I'd sure hope to get back something that I could\n> directly use when starting up a new psql session.\n>\n> > Anyway, I think your point is that maybe this should be RWF\n> > not Rejected, and I agree with that.\n>\n> Ok.\n>\n> > (I had not looked at the last version of the patch, but now that\n> > I have, I still don't like the fact that it has the client tracking\n> > session start time separately from what the server does. The small\n> > discrepancy that introduces is going to confuse somebody. I see\n> > that there's no documentation update either.)\n>\n> This worries me about as much as I worry that someone's going to be\n> confused by explain-analyze output vs. \\timing. Yes, it happens, and\n> actually pretty often, but I wouldn't change how it works because\n> they're two different things, not to mention that if I'm going to be\n> impacted by the time being off on one of the systems, I'd at least like\n> to know when my client thought it connected relative to the clock on my\n> client.\n\nSo if the path it set as RWF could push a extra work in there but in\nmain point what be the address about that.\n\n\nThanks to all for you feedback.\nRegards!\n-- \nRodrigo Ramírez Norambuena\nhttp://www.rodrigoramirez.com/\n\n\n", "msg_date": "Sat, 14 Mar 2020 16:16:21 -0300", "msg_from": "=?UTF-8?Q?Rodrigo_Ram=C3=ADrez_Norambuena?= <decipher.hk@gmail.com>", "msg_from_op": true, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "On 3/14/20 3:16 PM, Rodrigo Ramírez Norambuena wrote:\n> \n> I forgot about that ... It passed a little time from my new pushed\n> changes. So go ahead :)\n\nThis patch has been returned with feedback. Please feel free to resubmit \nin a future CF when you believe the feedback has been addressed.\n\nRegards,\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Mon, 16 Mar 2020 08:24:23 -0400", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "On Mon, Mar 16, 2020 at 1:24 PM David Steele <david@pgmasters.net> wrote:\n\n> On 3/14/20 3:16 PM, Rodrigo Ramírez Norambuena wrote:\n> >\n> > I forgot about that ... It passed a little time from my new pushed\n> > changes. So go ahead :)\n>\n> This patch has been returned with feedback. Please feel free to resubmit\n> in a future CF when you believe the feedback has been addressed.\n\n\nThere is a duplicate entry as:\n\nhttps://commitfest.postgresql.org/27/2423/\n\nRegards,\n\nJuan José Santamaría Flecha\n\nOn Mon, Mar 16, 2020 at 1:24 PM David Steele <david@pgmasters.net> wrote:On 3/14/20 3:16 PM, Rodrigo Ramírez Norambuena wrote:\n> \n> I forgot about that ... It passed a little time from my new pushed\n> changes. So go ahead :)\n\nThis patch has been returned with feedback. Please feel free to resubmit \nin a future CF when you believe the feedback has been addressed.There is a duplicate entry as:https://commitfest.postgresql.org/27/2423/Regards,Juan José Santamaría Flecha", "msg_date": "Mon, 16 Mar 2020 15:59:20 +0100", "msg_from": "=?UTF-8?Q?Juan_Jos=C3=A9_Santamar=C3=ADa_Flecha?=\n <juanjo.santamaria@gmail.com>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" }, { "msg_contents": "On 3/16/20 10:59 AM, Juan José Santamaría Flecha wrote:\n> On Mon, Mar 16, 2020 at 1:24 PM David Steele <david@pgmasters.net \n> <mailto:david@pgmasters.net>> wrote:\n> \n> On 3/14/20 3:16 PM, Rodrigo Ramírez Norambuena wrote:\n> >\n> > I forgot about that ... It passed a little time from my new pushed\n> > changes. So go ahead :)\n> \n> This patch has been returned with feedback. Please feel free to\n> resubmit\n> in a future CF when you believe the feedback has been addressed.\n> \n> \n> There is a duplicate entry as:\n\nThanks. I've marked in as withdrawn but in the future you can feel free \nto do so yourself.\n\nRegards,\n-- \n-David\ndavid@pgmasters.net\n\n\n", "msg_date": "Mon, 16 Mar 2020 12:01:29 -0400", "msg_from": "David Steele <david@pgmasters.net>", "msg_from_op": false, "msg_subject": "Re: [PATCH] Connection time for \\conninfo" } ]
[ { "msg_contents": "Hi,\n\nMaybe I'm forgetting some dependency management discussion that I was\npart of recently, but is the following behavior unintentional?\n\ncreate table p (a int, b int, c int) partition by list (a);\ncreate table p1 partition of p for values in (1) partition by list (b);\ncreate table p11 partition of p1 for values in (1);\ncreate index on p (c);\nalter table p drop column c;\nERROR: cannot drop index p11_c_idx because index p1_c_idx requires it\nHINT: You can drop index p1_c_idx instead.\n\nDropping c should've automatically dropped the index p_c_idx and its\nchildren and grandchildren, so the above complaint seems redundant.\n\nThanks,\nAmit\n\n\n", "msg_date": "Wed, 4 Sep 2019 14:36:33 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": true, "msg_subject": "dropping column prevented due to inherited index" }, { "msg_contents": "On Wed, Sep 4, 2019 at 2:36 PM Amit Langote <amitlangote09@gmail.com> wrote:\n>\n> Hi,\n>\n> Maybe I'm forgetting some dependency management discussion that I was\n> part of recently, but is the following behavior unintentional?\n>\n> create table p (a int, b int, c int) partition by list (a);\n> create table p1 partition of p for values in (1) partition by list (b);\n> create table p11 partition of p1 for values in (1);\n> create index on p (c);\n> alter table p drop column c;\n> ERROR: cannot drop index p11_c_idx because index p1_c_idx requires it\n> HINT: You can drop index p1_c_idx instead.\n>\n> Dropping c should've automatically dropped the index p_c_idx and its\n> children and grandchildren, so the above complaint seems redundant.\n\nInterestingly, this behavior only occurs with v12 and HEAD. With v11:\n\ncreate table p (a int, b int, c int) partition by list (a);\ncreate table p1 partition of p for values in (1) partition by list (b);\ncreate table p11 partition of p1 for values in (1);\ncreate index on p (c);\nalter table p drop column c; -- ok\n\nNote that the multi-level partitioning is not really needed to\nreproduce the error.\n\nI think the error in my first email has to do with the following\ncommit made to v12 and HEAD branches earlier this year:\n\ncommit 1d92a0c9f7dd547ad14cd8a3974289c5ec7f04ce\nAuthor: Tom Lane <tgl@sss.pgh.pa.us>\nDate: Mon Feb 11 14:41:13 2019 -0500\n\n Redesign the partition dependency mechanism.\n\nThere may not really be any problem with the commit itself, but I\nsuspect that the new types of dependencies (or the way\nfindDependentObject() analyzes them) don't play well with inheritance\nrecursion of ATExecDropColumn(). Currently, child columns (and its\ndependencies) are dropped before the parent column (and its\ndependencies). By using the attached patch which reverses that order,\nthe error goes away, but I'm not sure that that's the correct\nsolution.\n\nTom, thoughts?\n\nThanks,\nAmit", "msg_date": "Thu, 3 Oct 2019 19:14:36 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": true, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On 2019-Oct-03, Amit Langote wrote:\n\n> There may not really be any problem with the commit itself, but I\n> suspect that the new types of dependencies (or the way\n> findDependentObject() analyzes them) don't play well with inheritance\n> recursion of ATExecDropColumn(). Currently, child columns (and its\n> dependencies) are dropped before the parent column (and its\n> dependencies). By using the attached patch which reverses that order,\n> the error goes away, but I'm not sure that that's the correct\n> solution.\n\nHmm. I wonder if we shouldn't adopt the coding pattern we've used\nelsewhere of collecting all columns to be dropped first into an\nObjectAddresses array, then use performMultipleDeletions.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Thu, 3 Oct 2019 09:18:12 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On Thu, Oct 03, 2019 at 09:18:12AM -0300, Alvaro Herrera wrote:\n> Hmm. I wonder if we shouldn't adopt the coding pattern we've used\n> elsewhere of collecting all columns to be dropped first into an\n> ObjectAddresses array, then use performMultipleDeletions.\n\n+1. That's the common pattern these days, because that's more\nperformant. I think that the patch should have regression tests.\n--\nMichael", "msg_date": "Fri, 4 Oct 2019 17:57:14 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "Hello,\n\nOn Fri, Oct 4, 2019 at 5:57 PM Michael Paquier <michael@paquier.xyz> wrote:\n>\n> On Thu, Oct 03, 2019 at 09:18:12AM -0300, Alvaro Herrera wrote:\n> > Hmm. I wonder if we shouldn't adopt the coding pattern we've used\n> > elsewhere of collecting all columns to be dropped first into an\n> > ObjectAddresses array, then use performMultipleDeletions.\n>\n> +1. That's the common pattern these days, because that's more\n> performant.\n\nActually I don't see the peformMultipleDeletions() pattern being used\nfor the situations where there are multiple objects to drop due to\ninheritance. I only see it where there are multiple objects related\nto one table. Maybe it's possible to apply to the inheritance\nsituation though, but in this particular case, it seems a bit hard to\ndo, because ATExecDropColumn steps through an inheritance tree level\nat a time.\n\nBut maybe I misunderstood Alvaro's suggestion?\n\n> I think that the patch should have regression tests.\n\nI have added one in the attached updated patch.\n\nThanks,\nAmit", "msg_date": "Mon, 7 Oct 2019 11:01:13 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": true, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "I think we could have first deleted all the dependency of child object\non parent and then deleted the child itself using performDeletion().\nAs an example let's consider the case of toast table where we first\ndelete the dependency of toast relation on main relation and then\ndelete the toast table itself otherwise the toast table deletion would\nfail. But, the problem I see here is that currently we do not have any\nentry in pg_attribute table that would tell us about the dependency of\nchild column on parent.\n\n-- \nWith Regards,\nAshutosh Sharma\nEnterpriseDB:http://www.enterprisedb.com\n\nOn Mon, Oct 7, 2019 at 7:31 AM Amit Langote <amitlangote09@gmail.com> wrote:\n>\n> Hello,\n>\n> On Fri, Oct 4, 2019 at 5:57 PM Michael Paquier <michael@paquier.xyz> wrote:\n> >\n> > On Thu, Oct 03, 2019 at 09:18:12AM -0300, Alvaro Herrera wrote:\n> > > Hmm. I wonder if we shouldn't adopt the coding pattern we've used\n> > > elsewhere of collecting all columns to be dropped first into an\n> > > ObjectAddresses array, then use performMultipleDeletions.\n> >\n> > +1. That's the common pattern these days, because that's more\n> > performant.\n>\n> Actually I don't see the peformMultipleDeletions() pattern being used\n> for the situations where there are multiple objects to drop due to\n> inheritance. I only see it where there are multiple objects related\n> to one table. Maybe it's possible to apply to the inheritance\n> situation though, but in this particular case, it seems a bit hard to\n> do, because ATExecDropColumn steps through an inheritance tree level\n> at a time.\n>\n> But maybe I misunderstood Alvaro's suggestion?\n>\n> > I think that the patch should have regression tests.\n>\n> I have added one in the attached updated patch.\n>\n> Thanks,\n> Amit\n\n\n", "msg_date": "Mon, 7 Oct 2019 10:09:01 +0530", "msg_from": "Ashutosh Sharma <ashu.coek88@gmail.com>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "Hi Ashutosh,\n\nOn Mon, Oct 7, 2019 at 1:39 PM Ashutosh Sharma <ashu.coek88@gmail.com> wrote:\n> I think we could have first deleted all the dependency of child object\n> on parent and then deleted the child itself using performDeletion().\n\nSo, there are two objects to consider in this case -- column and an\nindex that depends on it.\n\nFor columns, we don't store any dependency records for the dependency\nbetween a child column and its corresponding parent column. That\ndependency is explicitly managed by the code and the attinhcount flag,\nwhich if set, prevents the column from being dropped on its own.\n\nIndexes do rely on dependency records for the dependency between a\nchild index and its corresponding parent index. This dependency\nprevents a child index from being dropped if the corresponding parent\nindex is also not being dropped.\n\nIn this case, recursively dropping a child's column will in turn try\nto drop the depending child index. findDependentObject() complains\nbecause it can't allow a child index to be dropped, because it can't\nestablish that the corresponding parent index is also being dropped.\nThat's because the parent index will be dropped when the parent's\ncolumn will be dropped, which due to current coding of\nATExecDropColumn() is *after* all the child columns and indexes are\ndropped. If we drop the parent column and depending index first and\nthen recurse to children as my proposed patch does, then the parent\nindex would already have been dropped when dropping the child column\nand the depending index.\n\n> As an example let's consider the case of toast table where we first\n> delete the dependency of toast relation on main relation and then\n> delete the toast table itself otherwise the toast table deletion would\n> fail. But, the problem I see here is that currently we do not have any\n> entry in pg_attribute table that would tell us about the dependency of\n> child column on parent.\n\nI couldn't imagine how that trick could be implemented for this case. :(\n\nThanks,\nAmit\n\n\n", "msg_date": "Tue, 8 Oct 2019 17:42:36 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": true, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "Apologies for not helping much here; I'm on vacation for a couple of\nweeks.\n\nOn 2019-Oct-08, Amit Langote wrote:\n\n> I couldn't imagine how that trick could be implemented for this case. :(\n\nCan't we pass around an ObjectAddresses pointer to which each recursion\nlevel adds the object(s) it wants to delete, and in the outermost level\nwe drop everything in it? I vaguely recall we implemented something\nlike that somewhere within the past year, but all I can find is\n20bef2c3110a.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Tue, 8 Oct 2019 06:15:05 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On Tue, Oct 8, 2019 at 6:15 PM Alvaro Herrera <alvherre@2ndquadrant.com> wrote:\n> Apologies for not helping much here; I'm on vacation for a couple of\n> weeks.\n\nNo worries, please take your time.\n\n> On 2019-Oct-08, Amit Langote wrote:\n>\n> > I couldn't imagine how that trick could be implemented for this case. :(\n>\n> Can't we pass around an ObjectAddresses pointer to which each recursion\n> level adds the object(s) it wants to delete, and in the outermost level\n> we drop everything in it? I vaguely recall we implemented something\n> like that somewhere within the past year, but all I can find is\n> 20bef2c3110a.\n\nI thought about doing something like that, but wasn't sure if\nintroducing that much complexity is warranted.\n\nThanks,\nAmit\n\n\n", "msg_date": "Tue, 8 Oct 2019 18:25:05 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": true, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On Tue, Oct 8, 2019 at 2:12 PM Amit Langote <amitlangote09@gmail.com> wrote:\n>\n> Hi Ashutosh,\n>\n> On Mon, Oct 7, 2019 at 1:39 PM Ashutosh Sharma <ashu.coek88@gmail.com> wrote:\n> > I think we could have first deleted all the dependency of child object\n> > on parent and then deleted the child itself using performDeletion().\n>\n> So, there are two objects to consider in this case -- column and an\n> index that depends on it.\n>\n> For columns, we don't store any dependency records for the dependency\n> between a child column and its corresponding parent column. That\n> dependency is explicitly managed by the code and the attinhcount flag,\n> which if set, prevents the column from being dropped on its own.\n>\n> Indexes do rely on dependency records for the dependency between a\n> child index and its corresponding parent index. This dependency\n> prevents a child index from being dropped if the corresponding parent\n> index is also not being dropped.\n>\n> In this case, recursively dropping a child's column will in turn try\n> to drop the depending child index. findDependentObject() complains\n> because it can't allow a child index to be dropped, because it can't\n> establish that the corresponding parent index is also being dropped.\n> That's because the parent index will be dropped when the parent's\n> column will be dropped, which due to current coding of\n> ATExecDropColumn() is *after* all the child columns and indexes are\n> dropped. If we drop the parent column and depending index first and\n> then recurse to children as my proposed patch does, then the parent\n> index would already have been dropped when dropping the child column\n> and the depending index.\n>\n> > As an example let's consider the case of toast table where we first\n> > delete the dependency of toast relation on main relation and then\n> > delete the toast table itself otherwise the toast table deletion would\n> > fail. But, the problem I see here is that currently we do not have any\n> > entry in pg_attribute table that would tell us about the dependency of\n> > child column on parent.\n>\n> I couldn't imagine how that trick could be implemented for this case. :(\n>\n\nI don't think that is possible because presently in pg_attribute table\nwe do not have any column indicating that there exists index on the\ngiven attribute. If we were knowing that then we could find out if the\ngiven index on child table have been inherited from parent and if so,\nwe could delete all the dependencies on the child table index first\nand then delete the column itself in the child table but that doesn't\nseem to be doable here. So, although the standard way that I feel to\nperform an object deletion is to first remove all it's dependencies\nfrom the pg_depend table and then delete the object itself but\nconsidering the information available in the relevant catalog table\nthat doesn't seem to be possible.\n\n--\nWith Regards,\nAshutosh Sharma\nEnterpriseDB:http://www.enterprisedb.com\n\n\n--\nWith Regards,\nAshutosh Sharma\nEnterpriseDB:http://www.enterprisedb.com\n\n\n", "msg_date": "Tue, 8 Oct 2019 18:26:45 +0530", "msg_from": "Ashutosh Sharma <ashu.coek88@gmail.com>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On Tue, Oct 08, 2019 at 06:25:05PM +0900, Amit Langote wrote:\n> I thought about doing something like that, but wasn't sure if\n> introducing that much complexity is warranted.\n\nI looked at that. By experience, I think that it would be wiser to do\nfirst the lookup of all the dependencies you would like to delete, and\nthen let the internal dependency machinery sort things out after\nrecursing (remember recent fixes related to ON COMMIT actions). In\norder to do that, you actually just need to be careful to not trigger\nthe deletions as long as \"recursing\" is true because ATExecDropColumn\ncalls itself. And it is not actually as bad as I assumed, please see\nthe attached.\n--\nMichael", "msg_date": "Wed, 9 Oct 2019 16:18:12 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On 2019-Oct-09, Michael Paquier wrote:\n\n> On Tue, Oct 08, 2019 at 06:25:05PM +0900, Amit Langote wrote:\n> > I thought about doing something like that, but wasn't sure if\n> > introducing that much complexity is warranted.\n> \n> I looked at that. By experience, I think that it would be wiser to do\n> first the lookup of all the dependencies you would like to delete, and\n> then let the internal dependency machinery sort things out after\n> recursing (remember recent fixes related to ON COMMIT actions). In\n> order to do that, you actually just need to be careful to not trigger\n> the deletions as long as \"recursing\" is true because ATExecDropColumn\n> calls itself. And it is not actually as bad as I assumed, please see\n> the attached.\n\nRight, something like that. Needs a comment to explain what we do and\nhow recursing=true correlates with addrs=NULL, I think. Maybe add an\nassert.\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Wed, 9 Oct 2019 06:36:35 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On Wed, Oct 09, 2019 at 06:36:35AM -0300, Alvaro Herrera wrote:\n> Right, something like that. Needs a comment to explain what we do and\n> how recursing=true correlates with addrs=NULL, I think. Maybe add an\n> assert.\n\nYes, that would be a thing to do. So I have added more comments\nregarding that aspect, an assertion, and more tests with a partitioned\ntable without any children, and an actual check that all columns have\nbeen dropped in the leaves of the partition tree. How does that look?\n--\nMichael", "msg_date": "Thu, 10 Oct 2019 13:13:37 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "Hello,\n\nOn Thu, Oct 10, 2019 at 1:13 PM Michael Paquier <michael@paquier.xyz> wrote:\n> On Wed, Oct 09, 2019 at 06:36:35AM -0300, Alvaro Herrera wrote:\n> > Right, something like that. Needs a comment to explain what we do and\n> > how recursing=true correlates with addrs=NULL, I think. Maybe add an\n> > assert.\n>\n> Yes, that would be a thing to do. So I have added more comments\n> regarding that aspect, an assertion, and more tests with a partitioned\n> table without any children, and an actual check that all columns have\n> been dropped in the leaves of the partition tree. How does that look?\n\nThanks for the patch. I think we should test there being multiple\ndependent indexes on the column being dropped; the patch currently\ntests only one.\n\nComments on comments: ;)\n\n+ *\n+ * *addrs stores the object addresses of all the columns to delete in\n+ * case of a recursive lookup on children relations.\n\nI think this comment fails to make clear the state of addrs in a given\ninvocation of ATExecDropColumn(). Maybe the whole header comment\ncould be rewritten to explain this function's new mode of operation.\nHow about this:\n\n/*\n * Drops column 'colName' from relation 'rel' and returns the address of the\n * dropped column. The column is also dropped (or marked as no longer\n * inherited from relation) from the relation's inheritance children, if any.\n *\n * In the recursive invocations for inheritance child relations, instead of\n * dropping the column directly (if to be dropped at all), its object address\n * is added to 'addrs', which must be non-NULL in such invocations.\n * All columns are dropped at the same time after all the children have been\n * checked recursively.\n */\n\n /*\n+ * Initialize the location of addresses which will be deleted on a\n+ * recursive lookup on children relations. The structure to store all the\n+ * object addresses to delete is initialized once when the recursive\n+ * lookup begins.\n+ */\n+ Assert(!recursing || addrs != NULL);\n+ if (!recursing)\n+ addrs = new_object_addresses();\n\nMaybe this could just say:\n\n/* Initialize addrs on the first invocation. */\n\n+ /*\n+ * The recursion is ending, hence perform the actual column deletions.\n+ */\n\nMaybe:\n\n/* All columns to be dropped must now be in addrs, so drop. */\n\nThanks,\nAmit\n\n\n", "msg_date": "Thu, 10 Oct 2019 14:56:32 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": true, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On Thu, Oct 10, 2019 at 02:56:32PM +0900, Amit Langote wrote:\n> /*\n> * Drops column 'colName' from relation 'rel' and returns the address of the\n> * dropped column. The column is also dropped (or marked as no longer\n> * inherited from relation) from the relation's inheritance children, if any.\n> *\n> * In the recursive invocations for inheritance child relations, instead of\n> * dropping the column directly (if to be dropped at all), its object address\n> * is added to 'addrs', which must be non-NULL in such invocations.\n> * All columns are dropped at the same time after all the children have been\n> * checked recursively.\n> */\n\nSounds fine to me.\n\n> + * Initialize the location of addresses which will be deleted on a\n> + * recursive lookup on children relations. The structure to store all the\n> + * object addresses to delete is initialized once when the recursive\n> + * lookup begins.\n> + */\n> + Assert(!recursing || addrs != NULL);\n> + if (!recursing)\n> + addrs = new_object_addresses();\n> \n> Maybe this could just say:\n> \n> /* Initialize addrs on the first invocation. */\n\nI would add \"recursive\" here, to give:\n/* Initialize addrs on the first recursive invocation. */\n\n> + /*\n> + * The recursion is ending, hence perform the actual column deletions.\n> + */\n> \n> Maybe:\n> \n> /* All columns to be dropped must now be in addrs, so drop. */\n\nI think that it would be better to clarify as well that this stands\nafter all the child relations have been checked, so what about that?\n\"The resursive lookup for inherited child relations is done. All the\nchild relations have been scanned and the object addresses of all the\ncolumns to-be-dropped are registered in addrs, so drop.\"\n--\nMichael", "msg_date": "Thu, 10 Oct 2019 16:53:04 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On Thu, Oct 10, 2019 at 4:53 PM Michael Paquier <michael@paquier.xyz> wrote:\n> On Thu, Oct 10, 2019 at 02:56:32PM +0900, Amit Langote wrote:\n> > /* Initialize addrs on the first invocation. */\n>\n> I would add \"recursive\" here, to give:\n> /* Initialize addrs on the first recursive invocation. */\n\nActually, the code initializes it on the first call (recursing is\nfalse) and asserts that it must have been already initialized in a\nrecursive (recursing is true) call.\n\n> > + /*\n> > + * The recursion is ending, hence perform the actual column deletions.\n> > + */\n> >\n> > Maybe:\n> >\n> > /* All columns to be dropped must now be in addrs, so drop. */\n>\n> I think that it would be better to clarify as well that this stands\n> after all the child relations have been checked, so what about that?\n> \"The resursive lookup for inherited child relations is done. All the\n> child relations have been scanned and the object addresses of all the\n> columns to-be-dropped are registered in addrs, so drop.\"\n\nOkay, sure. Maybe it's better to write the comment inside the if\nblock, because if recursing is true, we don't drop yet.\n\nThoughts on suggestion to expand the test case?\n\nThanks,\nAmit\n\n\n", "msg_date": "Thu, 10 Oct 2019 17:28:02 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": true, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On Thu, Oct 10, 2019 at 05:28:02PM +0900, Amit Langote wrote:\n> Actually, the code initializes it on the first call (recursing is\n> false) and asserts that it must have been already initialized in a\n> recursive (recursing is true) call.\n\nI have actually kept your simplified version.\n\n> Okay, sure. Maybe it's better to write the comment inside the if\n> block, because if recursing is true, we don't drop yet.\n\nSure.\n\n> Thoughts on suggestion to expand the test case?\n\nNo objections to that, so done as per the attached. Does that match\nwhat you were thinking about?\n--\nMichael", "msg_date": "Fri, 11 Oct 2019 16:16:54 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On Fri, Oct 11, 2019 at 4:16 PM Michael Paquier <michael@paquier.xyz> wrote:\n> On Thu, Oct 10, 2019 at 05:28:02PM +0900, Amit Langote wrote:\n> > Actually, the code initializes it on the first call (recursing is\n> > false) and asserts that it must have been already initialized in a\n> > recursive (recursing is true) call.\n>\n> I have actually kept your simplified version.\n>\n> > Okay, sure. Maybe it's better to write the comment inside the if\n> > block, because if recursing is true, we don't drop yet.\n>\n> Sure.\n>\n> > Thoughts on suggestion to expand the test case?\n>\n> No objections to that, so done as per the attached. Does that match\n> what you were thinking about?\n\nThanks. The index on b is not really necessary for testing because it\nremains unaffected, but maybe it's fine.\n\nRegards,\nAmit\n\n\n", "msg_date": "Fri, 11 Oct 2019 16:23:51 +0900", "msg_from": "Amit Langote <amitlangote09@gmail.com>", "msg_from_op": true, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On Fri, Oct 11, 2019 at 04:23:51PM +0900, Amit Langote wrote:\n> Thanks. The index on b is not really necessary for testing because it\n> remains unaffected, but maybe it's fine.\n\nThat's on purpose. Any more comments?\n--\nMichael", "msg_date": "Fri, 11 Oct 2019 17:52:57 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On 2019-Oct-11, Michael Paquier wrote:\n\n> +\tif (!recursing)\n> +\t{\n> +\t\t/*\n> +\t\t * The resursing lookup for inherited child relations is done. All\n> +\t\t * the child relations have been scanned and the object addresses of\n> +\t\t * all the columns to-be-dropped are registered in addrs, so drop.\n> +\t\t */\n> +\t\tperformMultipleDeletions(addrs, behavior, 0);\n> +\t\tfree_object_addresses(addrs);\n> +\t}\n\nTypo \"resursing\". This comment seems a bit too long to me. Maybe\n\"Recursion having ended, drop everything that was collected.\" suffices.\n(Fits in one line.)\n\n-- \n�lvaro Herrera https://www.2ndQuadrant.com/\nPostgreSQL Development, 24x7 Support, Remote DBA, Training & Services\n\n\n", "msg_date": "Fri, 11 Oct 2019 18:39:47 -0300", "msg_from": "Alvaro Herrera <alvherre@2ndquadrant.com>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On Fri, Oct 11, 2019 at 06:39:47PM -0300, Alvaro Herrera wrote:\n> Typo \"resursing\". This comment seems a bit too long to me. Maybe\n> \"Recursion having ended, drop everything that was collected.\" suffices.\n> (Fits in one line.)\n\nSounds fine to me, thanks.\n--\nMichael", "msg_date": "Sat, 12 Oct 2019 15:08:41 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" }, { "msg_contents": "On Sat, Oct 12, 2019 at 03:08:41PM +0900, Michael Paquier wrote:\n> On Fri, Oct 11, 2019 at 06:39:47PM -0300, Alvaro Herrera wrote:\n>> Typo \"resursing\". This comment seems a bit too long to me. Maybe\n>> \"Recursion having ended, drop everything that was collected.\" suffices.\n>> (Fits in one line.)\n> \n> Sounds fine to me, thanks.\n\nI have been able to look at this issue once again, and applied the fix\ndown to v12. Thanks, all!\n--\nMichael", "msg_date": "Sun, 13 Oct 2019 17:56:02 +0900", "msg_from": "Michael Paquier <michael@paquier.xyz>", "msg_from_op": false, "msg_subject": "Re: dropping column prevented due to inherited index" } ]
[ { "msg_contents": "Hello,\n\nA few years back[1] I experimented with a simple readiness API that\nwould allow Append to start emitting tuples from whichever Foreign\nScan has data available, when working with FDW-based sharding. I used\nthat primarily as a way to test Andres's new WaitEventSet stuff and my\nkqueue implementation of that, but I didn't pursue it seriously\nbecause I knew we wanted a more ambitious async executor rewrite and\nmany people had ideas about that, with schedulers capable of jumping\nall over the tree etc.\n\nAnyway, Stephen Frost pinged me off-list to ask about that patch, and\nasked why we don't just do this naive thing until we have something\nbetter. It's a very localised feature that works only between Append\nand its immediate children. The patch makes it work for postgres_fdw,\nbut it should work for any FDW that can get its hands on a socket.\n\nHere's a quick rebase of that old POC patch, along with a demo. Since\n2016, Parallel Append landed, but I didn't have time to think about\nhow to integrate with that so I did a quick \"sledgehammer\" rebase that\ndisables itself if parallelism is in the picture.\n\n=== demo ===\n\ncreate table t (a text, b text);\n\ncreate or replace function slow_data(name text) returns setof t as\n$$\nbegin\n perform pg_sleep(random());\n return query select name, generate_series(1, 100)::text as i;\nend;\n$$\nlanguage plpgsql;\n\ncreate view t1 as select * from slow_data('t1');\ncreate view t2 as select * from slow_data('t2');\ncreate view t3 as select * from slow_data('t3');\n\ncreate extension postgres_fdw;\ncreate server server1 foreign data wrapper postgres_fdw options\n(dbname 'postgres');\ncreate server server2 foreign data wrapper postgres_fdw options\n(dbname 'postgres');\ncreate server server3 foreign data wrapper postgres_fdw options\n(dbname 'postgres');\ncreate user mapping for current_user server server1;\ncreate user mapping for current_user server server2;\ncreate user mapping for current_user server server3;\ncreate foreign table ft1 (a text, b text) server server1 options\n(table_name 't1');\ncreate foreign table ft2 (a text, b text) server server2 options\n(table_name 't2');\ncreate foreign table ft3 (a text, b text) server server3 options\n(table_name 't3');\n\n-- create three remote shards\ncreate table pt (a text, b text) partition by list (a);\nalter table pt attach partition ft1 for values in ('ft1');\nalter table pt attach partition ft2 for values in ('ft2');\nalter table pt attach partition ft3 for values in ('ft3');\n\n-- see that tuples come back in the order that they're ready\n
select * from pt where b like '42';\n\n[1] https://www.postgresql.org/message-id/CAEepm%3D1CuAWfxDk%3D%3DjZ7pgCDCv52fiUnDSpUvmznmVmRKU5zpA%40mail.gmail.com\n\n-- \nThomas Munro\nhttps://enterprisedb.com", "msg_date": "Wed, 4 Sep 2019 18:18:31 +1200", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Append with naive multiplexing of FDWs" }, { "msg_contents": "On Wed, Sep 4, 2019 at 06:18:31PM +1200, Thomas Munro wrote:\n> Hello,\n> \n> A few years back[1] I experimented with a simple readiness API that\n> would allow Append to start emitting tuples from whichever Foreign\n> Scan has data available, when working with FDW-based sharding. I used\n> that primarily as a way to test Andres's new WaitEventSet stuff and my\n> kqueue implementation of that, but I didn't pursue it seriously\n> because I knew we wanted a more ambitious async executor rewrite and\n> many people had ideas about that, with schedulers capable of jumping\n> all over the tree etc.\n> \n> Anyway, Stephen Frost pinged me off-list to ask about that patch, and\n> asked why we don't just do this naive thing until we have something\n> better. It's a very localised feature that works only between Append\n> and its immediate children. The patch makes it work for postgres_fdw,\n> but it should work for any FDW that can get its hands on a socket.\n> \n> Here's a quick rebase of that old POC patch, along with a demo. Since\n> 2016, Parallel Append landed, but I didn't have time to think about\n> how to integrate with that so I did a quick \"sledgehammer\" rebase that\n> disables itself if parallelism is in the picture.\n\nYes, sharding has been waiting on parallel FDW scans. Would this work\nfor parallel partition scans if the partitions were FDWs?\n\n-- \n Bruce Momjian <bruce@momjian.us> http://momjian.us\n EnterpriseDB http://enterprisedb.com\n\n+ As you are, so once was I. As I am, so you will be. +\n+ Ancient Roman grave inscription +\n\n\n", "msg_date": "Fri, 27 Sep 2019 12:20:02 -0400", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "On Sat, Sep 28, 2019 at 4:20 AM Bruce Momjian <bruce@momjian.us> wrote:\n> On Wed, Sep 4, 2019 at 06:18:31PM +1200, Thomas Munro wrote:\n> > A few years back[1] I experimented with a simple readiness API that\n> > would allow Append to start emitting tuples from whichever Foreign\n> > Scan has data available, when working with FDW-based sharding. I used\n> > that primarily as a way to test Andres's new WaitEventSet stuff and my\n> > kqueue implementation of that, but I didn't pursue it seriously\n> > because I knew we wanted a more ambitious async executor rewrite and\n> > many people had ideas about that, with schedulers capable of jumping\n> > all over the tree etc.\n> >\n> > Anyway, Stephen Frost pinged me off-list to ask about that patch, and\n> > asked why we don't just do this naive thing until we have something\n> > better. It's a very localised feature that works only between Append\n> > and its immediate children. The patch makes it work for postgres_fdw,\n> > but it should work for any FDW that can get its hands on a socket.\n> >\n> > Here's a quick rebase of that old POC patch, along with a demo. Since\n> > 2016, Parallel Append landed, but I didn't have time to think about\n> > how to integrate with that so I did a quick \"sledgehammer\" rebase that\n> > disables itself if parallelism is in the picture.\n>\n> Yes, sharding has been waiting on parallel FDW scans. Would this work\n> for parallel partition scans if the partitions were FDWs?\n\nYeah, this works for partitions that are FDWs (as shown), but only for\nAppend, not for Parallel Append. So you'd have parallelism in the\nsense that your N remote shard servers are all doing stuff at the same\ntime, but it couldn't be in a parallel query on your 'home' server,\nwhich is probably good for things that push down aggregation and bring\nback just a few tuples from each shard, but bad for anything wanting\nto ship back millions of tuples to chew on locally. Do you think\nthat'd be useful enough on its own?\n\nThe problem is that parallel safe non-partial plans (like postgres_fdw\nscans) are exclusively 'claimed' by one process under Parallel Append,\nso with the patch as posted, if you modify it to allow parallelism\nthen it'll probably give correct answers but nothing prevents a single\nprocess from claiming and starting all the scans and then waiting for\nthem to be ready, while the other processes miss out on doing any work\nat all. There's probably some kludgy solution involving not letting\nany one worker start more than X, and some space cadet solution\ninvolving passing sockets around and teaching libpq to hand over\nconnections at certain controlled phases of the protocol (due to lack\nof threads), but nothing like that has jumped out as the right path so\nfar.\n\nOne idea that seems promising but requires a bunch more infrastructure\nis to offload the libpq multiplexing to a background worker that owns\nall the sockets, and have it push tuples into a multi-consumer shared\nmemory queue that regular executor processes could read from. I have\nbeen wondering if that would be best done by each FDW implementation,\nor if there is a way to make a generic infrastructure for converting\nparallel-safe executor nodes into partial plans by the use of a\n'Scatter' (opposite of Gather) node that can spread the output of any\nnode over many workers.\n\nIf you had that, you'd still want a way for Parallel Append to be\nreadiness-based, but it would probably look a bit different to this\npatch because it'd need to use (vapourware) multiconsumer shm queue\nreadiness, not fd readiness. And another kind of fd-readiness\nmultiplexing would be going on inside the new (vapourware) worker that\nhandles all the libpq connections (and maybe other kinds of work for\nother FDWs that are able to expose a socket).\n\n\n", "msg_date": "Sun, 17 Nov 2019 21:54:55 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "On Sun, Nov 17, 2019 at 09:54:55PM +1300, Thomas Munro wrote:\n> On Sat, Sep 28, 2019 at 4:20 AM Bruce Momjian <bruce@momjian.us> wrote:\n> > On Wed, Sep 4, 2019 at 06:18:31PM +1200, Thomas Munro wrote:\n> > > A few years back[1] I experimented with a simple readiness API that\n> > > would allow Append to start emitting tuples from whichever Foreign\n> > > Scan has data available, when working with FDW-based sharding. I used\n> > > that primarily as a way to test Andres's new WaitEventSet stuff and my\n> > > kqueue implementation of that, but I didn't pursue it seriously\n> > > because I knew we wanted a more ambitious async executor rewrite and\n> > > many people had ideas about that, with schedulers capable of jumping\n> > > all over the tree etc.\n> > >\n> > > Anyway, Stephen Frost pinged me off-list to ask about that patch, and\n> > > asked why we don't just do this naive thing until we have something\n> > > better. It's a very localised feature that works only between Append\n> > > and its immediate children. The patch makes it work for postgres_fdw,\n> > > but it should work for any FDW that can get its hands on a socket.\n> > >\n> > > Here's a quick rebase of that old POC patch, along with a demo. Since\n> > > 2016, Parallel Append landed, but I didn't have time to think about\n> > > how to integrate with that so I did a quick \"sledgehammer\" rebase that\n> > > disables itself if parallelism is in the picture.\n> >\n> > Yes, sharding has been waiting on parallel FDW scans. Would this work\n> > for parallel partition scans if the partitions were FDWs?\n> \n> Yeah, this works for partitions that are FDWs (as shown), but only for\n> Append, not for Parallel Append. So you'd have parallelism in the\n> sense that your N remote shard servers are all doing stuff at the same\n> time, but it couldn't be in a parallel query on your 'home' server,\n> which is probably good for things that push down aggregation and bring\n> back just a few tuples from each shard, but bad for anything wanting\n> to ship back millions of tuples to chew on locally. Do you think\n> that'd be useful enough on its own?\n\nYes, I think so. There are many data warehouse queries that want to\nreturn only aggregate values, or filter for a small number of rows. \nEven OLTP queries might return only a few rows from multiple partitions.\nThis would allow for a proof-of-concept implementation so we can see how\nrealistic this approach is.\n\n> The problem is that parallel safe non-partial plans (like postgres_fdw\n> scans) are exclusively 'claimed' by one process under Parallel Append,\n> so with the patch as posted, if you modify it to allow parallelism\n> then it'll probably give correct answers but nothing prevents a single\n> process from claiming and starting all the scans and then waiting for\n> them to be ready, while the other processes miss out on doing any work\n> at all. There's probably some kludgy solution involving not letting\n> any one worker start more than X, and some space cadet solution\n> involving passing sockets around and teaching libpq to hand over\n> connections at certain controlled phases of the protocol (due to lack\n> of threads), but nothing like that has jumped out as the right path so\n> far.\n\nI am unclear how many queries can do any meaningful work until all\nshards have giving their full results.\n\n-- \n Bruce Momjian <bruce@momjian.us> http://momjian.us\n EnterpriseDB http://enterprisedb.com\n\n+ As you are, so once was I. As I am, so you will be. +\n+ Ancient Roman grave inscription +\n\n\n", "msg_date": "Sat, 30 Nov 2019 14:26:11 -0500", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "Hello.\n\nAt Sat, 30 Nov 2019 14:26:11 -0500, Bruce Momjian <bruce@momjian.us> wrote in \n> On Sun, Nov 17, 2019 at 09:54:55PM +1300, Thomas Munro wrote:\n> > On Sat, Sep 28, 2019 at 4:20 AM Bruce Momjian <bruce@momjian.us> wrote:\n> > > On Wed, Sep 4, 2019 at 06:18:31PM +1200, Thomas Munro wrote:\n> > > > A few years back[1] I experimented with a simple readiness API that\n> > > > would allow Append to start emitting tuples from whichever Foreign\n> > > > Scan has data available, when working with FDW-based sharding. I used\n> > > > that primarily as a way to test Andres's new WaitEventSet stuff and my\n> > > > kqueue implementation of that, but I didn't pursue it seriously\n> > > > because I knew we wanted a more ambitious async executor rewrite and\n> > > > many people had ideas about that, with schedulers capable of jumping\n> > > > all over the tree etc.\n> > > >\n> > > > Anyway, Stephen Frost pinged me off-list to ask about that patch, and\n> > > > asked why we don't just do this naive thing until we have something\n> > > > better. It's a very localised feature that works only between Append\n> > > > and its immediate children. The patch makes it work for postgres_fdw,\n> > > > but it should work for any FDW that can get its hands on a socket.\n> > > >\n> > > > Here's a quick rebase of that old POC patch, along with a demo. Since\n> > > > 2016, Parallel Append landed, but I didn't have time to think about\n> > > > how to integrate with that so I did a quick \"sledgehammer\" rebase that\n> > > > disables itself if parallelism is in the picture.\n> > >\n> > > Yes, sharding has been waiting on parallel FDW scans. Would this work\n> > > for parallel partition scans if the partitions were FDWs?\n> > \n> > Yeah, this works for partitions that are FDWs (as shown), but only for\n> > Append, not for Parallel Append. So you'd have parallelism in the\n> > sense that your N remote shard servers are all doing stuff at the same\n> > time, but it couldn't be in a parallel query on your 'home' server,\n> > which is probably good for things that push down aggregation and bring\n> > back just a few tuples from each shard, but bad for anything wanting\n> > to ship back millions of tuples to chew on locally. Do you think\n> > that'd be useful enough on its own?\n> \n> Yes, I think so. There are many data warehouse queries that want to\n> return only aggregate values, or filter for a small number of rows. \n> Even OLTP queries might return only a few rows from multiple partitions.\n> This would allow for a proof-of-concept implementation so we can see how\n> realistic this approach is.\n> \n> > The problem is that parallel safe non-partial plans (like postgres_fdw\n> > scans) are exclusively 'claimed' by one process under Parallel Append,\n> > so with the patch as posted, if you modify it to allow parallelism\n> > then it'll probably give correct answers but nothing prevents a single\n> > process from claiming and starting all the scans and then waiting for\n> > them to be ready, while the other processes miss out on doing any work\n> > at all. There's probably some kludgy solution involving not letting\n> > any one worker start more than X, and some space cadet solution\n> > involving passing sockets around and teaching libpq to hand over\n> > connections at certain controlled phases of the protocol (due to lack\n> > of threads), but nothing like that has jumped out as the right path so\n> > far.\n> \n> I am unclear how many queries can do any meaningful work until all\n> shards have giving their full results.\n\nThere's my pending (somewhat stale) patch, which allows to run local\nscans while waiting for remote servers.\n\nhttps://www.postgresql.org/message-id/20180515.202945.69332784.horiguchi.kyotaro@lab.ntt.co.jp\n\nI (or we) wanted to introduce the asynchronous node mechanism as the\nbasis of async-capable postgres_fdw. The reason why it is stopping is\nthat we are seeing and I am waiting the executor change that makes\nexecutor push-up style, on which the async-node mechanism will be\nconstructed. If that won't happen shortly, I'd like to continue that\nwork..\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Thu, 05 Dec 2019 12:26:37 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "On Thu, Dec 5, 2019 at 4:26 PM Kyotaro Horiguchi\n<horikyota.ntt@gmail.com> wrote:\n> There's my pending (somewhat stale) patch, which allows to run local\n> scans while waiting for remote servers.\n>\n> https://www.postgresql.org/message-id/20180515.202945.69332784.horiguchi.kyotaro@lab.ntt.co.jp\n>\n> I (or we) wanted to introduce the asynchronous node mechanism as the\n> basis of async-capable postgres_fdw. The reason why it is stopping is\n> that we are seeing and I am waiting the executor change that makes\n> executor push-up style, on which the async-node mechanism will be\n> constructed. If that won't happen shortly, I'd like to continue that\n> work..\n\nAfter rereading some threads to remind myself what happened here...\nright, my little patch began life in March 2016[1] when I wanted a\ntest case to test Andres's work on WaitEventSets, and your patch set\nstarted a couple of months later and is vastly more ambitious[2][3].\nIt wants to escape from the volcano give-me-one-tuple-or-give-me-EOF\nmodel. And I totally agree that there are lots of reason to want to\ndo that (including yielding to other parts of the plan instead of\nwaiting for I/O, locks and some parallelism primitives enabling new\nkinds of parallelism), and I'm hoping to help with some small pieces\nof that if I can.\n\nMy patch set (rebased upthread) was extremely primitive, with no new\nplanner concepts, and added only a very simple new executor node\nmethod: ExecReady(). Append used that to try to ask its children if\nthey'd like some time to warm up. By default, ExecReady() says \"I\ndon't know what you're talking about, go away\", but FDWs can provide\nan implementation that says \"yes, please call me again when this fd is\nready\" or \"yes, I am ready, please call ExecProc() now\". It doesn't\ndeal with anything more complicated than that, and in particular it\ndoesn't work if there are extra planner nodes in between Append and\nthe foreign scan. (It also doesn't mix particularly well with\nparallelism, as mentioned.)\n\nThe reason I reposted this unambitious work is because Stephen keeps\nasking me why we don't consider the stupidly simple thing that would\nhelp with simple foreign partition-based queries today, instead of\nwaiting for someone to redesign the entire executor, because that's\n... really hard.\n\n[1] https://www.postgresql.org/message-id/CAEepm%3D1CuAWfxDk%3D%3DjZ7pgCDCv52fiUnDSpUvmznmVmRKU5zpA%40mail.gmail.com\n[2] https://www.postgresql.org/message-id/flat/CA%2BTgmobx8su_bYtAa3DgrqB%2BR7xZG6kHRj0ccMUUshKAQVftww%40mail.gmail.com\n[3] https://www.postgresql.org/message-id/flat/CA%2BTgmoaXQEt4tZ03FtQhnzeDEMzBck%2BLrni0UWHVVgOTnA6C1w%40mail.gmail.com\n\n\n", "msg_date": "Thu, 5 Dec 2019 17:45:24 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "On Thu, Dec 5, 2019 at 05:45:24PM +1300, Thomas Munro wrote:\n> My patch set (rebased upthread) was extremely primitive, with no new\n> planner concepts, and added only a very simple new executor node\n> method: ExecReady(). Append used that to try to ask its children if\n> they'd like some time to warm up. By default, ExecReady() says \"I\n> don't know what you're talking about, go away\", but FDWs can provide\n> an implementation that says \"yes, please call me again when this fd is\n> ready\" or \"yes, I am ready, please call ExecProc() now\". It doesn't\n> deal with anything more complicated than that, and in particular it\n> doesn't work if there are extra planner nodes in between Append and\n> the foreign scan. (It also doesn't mix particularly well with\n> parallelism, as mentioned.)\n> \n> The reason I reposted this unambitious work is because Stephen keeps\n> asking me why we don't consider the stupidly simple thing that would\n> help with simple foreign partition-based queries today, instead of\n> waiting for someone to redesign the entire executor, because that's\n> ... really hard.\n\nI agree with Stephen's request. We have been waiting for the executor\nrewrite for a while, so let's just do something simple and see how it\nperforms.\n\n-- \n Bruce Momjian <bruce@momjian.us> http://momjian.us\n EnterpriseDB http://enterprisedb.com\n\n+ As you are, so once was I. As I am, so you will be. +\n+ Ancient Roman grave inscription +\n\n\n", "msg_date": "Thu, 5 Dec 2019 13:12:17 -0500", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "On Thu, Dec 5, 2019 at 1:12 PM Bruce Momjian <bruce@momjian.us> wrote:\n> I agree with Stephen's request. We have been waiting for the executor\n> rewrite for a while, so let's just do something simple and see how it\n> performs.\n\nI'm sympathetic to the frustration here, and I think it would be great\nif we could find a way forward that doesn't involve waiting for a full\nrewrite of the executor. However, I seem to remember that when we\ntested the various patches that various people had written for this\nfeature (I wrote one, too) they all had a noticeable performance\npenalty in the case of a plain old Append that involved no FDWs and\nnothing asynchronous. I don't think it's OK to have, say, a 2%\nregression on every query that involves an Append, because especially\nnow that we have partitioning, that's a lot of queries.\n\nI don't know whether this patch has that kind of problem. If it\ndoesn't, I would consider that a promising sign.\n\n-- \nRobert Haas\nEnterpriseDB: http://www.enterprisedb.com\nThe Enterprise PostgreSQL Company\n\n\n", "msg_date": "Thu, 5 Dec 2019 15:19:50 -0500", "msg_from": "Robert Haas <robertmhaas@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "On Fri, Dec 6, 2019 at 9:20 AM Robert Haas <robertmhaas@gmail.com> wrote:\n>\n> On Thu, Dec 5, 2019 at 1:12 PM Bruce Momjian <bruce@momjian.us> wrote:\n> > I agree with Stephen's request. We have been waiting for the executor\n> > rewrite for a while, so let's just do something simple and see how it\n> > performs.\n>\n> I'm sympathetic to the frustration here, and I think it would be great\n> if we could find a way forward that doesn't involve waiting for a full\n> rewrite of the executor. However, I seem to remember that when we\n> tested the various patches that various people had written for this\n> feature (I wrote one, too) they all had a noticeable performance\n> penalty in the case of a plain old Append that involved no FDWs and\n> nothing asynchronous. I don't think it's OK to have, say, a 2%\n> regression on every query that involves an Append, because especially\n> now that we have partitioning, that's a lot of queries.\n>\n> I don't know whether this patch has that kind of problem. If it\n> doesn't, I would consider that a promising sign.\n\nI'll look into that. If there is a measurable impact, I suspect it\ncan be avoided by, for example, installing a different ExecProcNode\nfunction.\n\n\n", "msg_date": "Fri, 6 Dec 2019 10:03:44 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "At Fri, 6 Dec 2019 10:03:44 +1300, Thomas Munro <thomas.munro@gmail.com> wrote in \n> On Fri, Dec 6, 2019 at 9:20 AM Robert Haas <robertmhaas@gmail.com> wrote:\n> > I don't know whether this patch has that kind of problem. If it\n> > doesn't, I would consider that a promising sign.\n> \n> I'll look into that. If there is a measurable impact, I suspect it\n> can be avoided by, for example, installing a different ExecProcNode\n> function.\n\nReplacing ExecProcNode perfectly isolates additional process in\nExecAppendAsync. Thus, for pure local appends, the patch can impact\nperformance through only planner and execinit. But I don't believe it\ncannot be as large as observable in a large scan.\n\nAs the mail pointed upthread, the patch acceleartes all remote cases\nwhen fetch_size is >= 200. The problem was that local scans seemed\nslightly slowed down. I dusted off the old patch (FWIW I attached it)\nand.. will re-run on the current development environment. (And\nre-check the code.).\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center", "msg_date": "Fri, 06 Dec 2019 17:12:11 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "On Thu, Dec 5, 2019 at 03:19:50PM -0500, Robert Haas wrote:\n> On Thu, Dec 5, 2019 at 1:12 PM Bruce Momjian <bruce@momjian.us> wrote:\n> > I agree with Stephen's request. We have been waiting for the executor\n> > rewrite for a while, so let's just do something simple and see how it\n> > performs.\n> \n> I'm sympathetic to the frustration here, and I think it would be great\n> if we could find a way forward that doesn't involve waiting for a full\n> rewrite of the executor. However, I seem to remember that when we\n> tested the various patches that various people had written for this\n> feature (I wrote one, too) they all had a noticeable performance\n> penalty in the case of a plain old Append that involved no FDWs and\n> nothing asynchronous. I don't think it's OK to have, say, a 2%\n> regression on every query that involves an Append, because especially\n> now that we have partitioning, that's a lot of queries.\n> \n> I don't know whether this patch has that kind of problem. If it\n> doesn't, I would consider that a promising sign.\n\nCertainly any overhead on normal queries would be unacceptable.\n\n-- \n Bruce Momjian <bruce@momjian.us> http://momjian.us\n EnterpriseDB http://enterprisedb.com\n\n+ As you are, so once was I. As I am, so you will be. +\n+ Ancient Roman grave inscription +\n\n\n", "msg_date": "Mon, 9 Dec 2019 12:18:44 -0500", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "Hello.\n\nI think I can say that this patch doesn't slows non-AsyncAppend,\nnon-postgres_fdw scans.\n\n\nAt Mon, 9 Dec 2019 12:18:44 -0500, Bruce Momjian <bruce@momjian.us> wrote in \n> Certainly any overhead on normal queries would be unacceptable.\n\nI took performance numbers on the current shape of the async execution\npatch for the following scan cases.\n\nt0 : single local table (parallel disabled)\npll : local partitioning (local Append, parallel disabled)\nft0 : single foreign table\npf0 : inheritance on 4 foreign tables, single connection\npf1 : inheritance on 4 foreign tables, 4 connections\nptf0 : partition on 4 foreign tables, single connection\nptf1 : partition on 4 foreign tables, 4 connections\n\nThe benchmarking system is configured as the follows on a single\nmachine.\n\n [ benchmark client ]\n | |\n (localhost:5433) (localhost:5432)\n | |\n +----+ | +------+ |\n | V V V | V\n | [master server] | [async server]\n | V | V\n +--fdw--+ +--fdw--+\n\n\nThe patch works roughly in the following steps.\n\n1. Planner decides how many children out of an append can run\n asynchrnously (called as async-capable.).\n\n2. While ExecInit if an Append doesn't have an async-capable children,\n ExecAppend that is exactly the same function is set as\n ExecProcNode. Otherwise ExecAppendAsync is used.\n\nIf the infrastructure part in the patch causes any degradation, the\n\"t0\"(scan on local single table) and/or \"pll\" test (scan on a local\nparitioned table) gets slow.\n\n3. postgresql_fdw always runs async-capable code path.\n\nIf the postgres_fdw part causes degradation, ft0 reflects that.\n\n\nThe tables has two integers and the query does sum(a) on all tuples.\n\nWith the default fetch_size = 100, number is run time in ms. Each\nnumber is the average of 14 runs.\n\n master patched gain\nt0 7325 7130 +2.7%\npll 4558 4484 +1.7%\nft0 3670 3675 -0.1%\npf0 2322 1550 +33.3%\npf1 2367 1475 +37.7%\nptf0 2517 1624 +35.5%\nptf1 2343 1497 +36.2%\n\nWith larger fetch_size (200) the gain mysteriously decreases for\nsharing single connection cases (pf0, ptf0), but others don't seem\nchange so much.\n\n master patched gain\nt0 7212 7252 -0.6%\npll 4546 4397 +3.3%\nft0 3712 3731 -0.5%\npf0 2131 1570 +26.4%\npf1 1926 1189 +38.3%\nptf0 2001 1557 +22.2%\nptf1 1903 1193 +37.4%\n\nFWIW, attached are the test script.\n\ngentblr2.sql: Table creation script.\ntestrun.sh : Benchmarking script.\n\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\nSELECT :scale * 0 as th0,\n :scale * 1 as th1,\n :scale * 2 as th2,\n :scale * 3 as th3,\n :scale * 4 as th4,\n :scale * 10 as th10,\n :scale * 20 as th20,\n :scale * 30 as th30,\n :scale * 40 as th40,\n :scale * 100 as th100,\n :scale * 1000 as th1000\n\\gset\n\nDROP TABLE IF EXISTS t0 CASCADE;\nDROP TABLE IF EXISTS pl CASCADE;\nDROP TABLE IF EXISTS pll CASCADE;\nDROP TABLE IF EXISTS pf0 CASCADE;\nDROP TABLE IF EXISTS pf1 CASCADE;\nDROP TABLE IF EXISTS ptf0;\nDROP TABLE IF EXISTS ptf1;\n\nCREATE TABLE pl (a int, b int);\nCREATE TABLE cl1 (LIKE pl) INHERITS (pl);\nCREATE TABLE cl2 (LIKE pl) INHERITS (pl);\nCREATE TABLE cl3 (LIKE pl) INHERITS (pl);\nCREATE TABLE cl4 (LIKE pl) INHERITS (pl);\nINSERT INTO cl1 (SELECT a, a FROM generate_series(:th0, :th1 - 1) a);\nINSERT INTO cl2 (SELECT a, a FROM generate_series(:th1, :th2 - 1) a);\nINSERT INTO cl3 (SELECT a, a FROM generate_series(:th2, :th3 - 1) a);\nINSERT INTO cl4 (SELECT a, a FROM generate_series(:th3, :th4 - 1) a);\n\nCREATE TABLE pll (a int, b int);\nCREATE TABLE cll1 (LIKE pl) INHERITS (pll);\nCREATE TABLE cll2 (LIKE pl) INHERITS (pll);\nCREATE TABLE cll3 (LIKE pl) INHERITS (pll);\nCREATE TABLE cll4 (LIKE pl) INHERITS (pll);\nINSERT INTO cll1 (SELECT a, a FROM generate_series(:th0, :th10 - 1) a);\nINSERT INTO cll2 (SELECT a, a FROM generate_series(:th10, :th20 - 1) a);\nINSERT INTO cll3 (SELECT a, a FROM generate_series(:th20, :th30 - 1) a);\nINSERT INTO cll4 (SELECT a, a FROM generate_series(:th30, :th40 - 1) a);\n\n\nCREATE TABLE t0 (LIKE pl);\nINSERT INTO t0 (SELECT a, a FROM generate_series(0, :th100 - 1) a);\n\nDROP SERVER IF EXISTS svl CASCADE;\nDROP SERVER IF EXISTS sv0 CASCADE;\nDROP SERVER IF EXISTS sv1 CASCADE;\nDROP SERVER IF EXISTS sv2 CASCADE;\nDROP SERVER IF EXISTS sv3 CASCADE;\nDROP SERVER IF EXISTS sv4 CASCADE;\n\nCREATE SERVER svl FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host :'svhost', port :'svport', dbname :'svdbname', fetch_size :'fetchsize');\nCREATE SERVER sv0 FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host :'svhost', port :'svport', dbname :'svdbname', fetch_size :'fetchsize');\nCREATE SERVER sv1 FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host :'svhost', port :'svport', dbname :'svdbname', fetch_size :'fetchsize');\nCREATE SERVER sv2 FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host :'svhost', port :'svport', dbname :'svdbname', fetch_size :'fetchsize');\nCREATE SERVER sv3 FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host :'svhost', port :'svport', dbname :'svdbname', fetch_size :'fetchsize');\nCREATE SERVER sv4 FOREIGN DATA WRAPPER postgres_fdw OPTIONS (host :'svhost', port :'svport', dbname :'svdbname', fetch_size :'fetchsize');\n\nCREATE USER MAPPING FOR public SERVER svl;\nCREATE USER MAPPING FOR public SERVER sv0;\nCREATE USER MAPPING FOR public SERVER sv1;\nCREATE USER MAPPING FOR public SERVER sv2;\nCREATE USER MAPPING FOR public SERVER sv3;\nCREATE USER MAPPING FOR public SERVER sv4;\n\nCREATE FOREIGN TABLE ft0 (a int, b int) SERVER svl OPTIONS (table_name 't0');\n\nCREATE FOREIGN TABLE ft10 (a int, b int) SERVER sv0 OPTIONS (table_name 'cl1');\nCREATE FOREIGN TABLE ft20 (a int, b int) SERVER sv0 OPTIONS (table_name 'cl2');\nCREATE FOREIGN TABLE ft30 (a int, b int) SERVER sv0 OPTIONS (table_name 'cl3');\nCREATE FOREIGN TABLE ft40 (a int, b int) SERVER sv0 OPTIONS (table_name 'cl4');\nCREATE FOREIGN TABLE ft11 (a int, b int) SERVER sv1 OPTIONS (table_name 'cl1');\nCREATE FOREIGN TABLE ft22 (a int, b int) SERVER sv2 OPTIONS (table_name 'cl2');\nCREATE FOREIGN TABLE ft33 (a int, b int) SERVER sv3 OPTIONS (table_name 'cl3');\nCREATE FOREIGN TABLE ft44 (a int, b int) SERVER sv4 OPTIONS (table_name 'cl4');\n\nCREATE TABLE pf0 (LIKE pl);\nALTER FOREIGN TABLE ft10 INHERIT pf0;\nALTER FOREIGN TABLE ft20 INHERIT pf0;\nALTER FOREIGN TABLE ft30 INHERIT pf0;\nALTER FOREIGN TABLE ft40 INHERIT pf0;\n\nCREATE TABLE pf1 (LIKE pl);\nALTER FOREIGN TABLE ft11 INHERIT pf1;\nALTER FOREIGN TABLE ft22 INHERIT pf1;\nALTER FOREIGN TABLE ft33 INHERIT pf1;\nALTER FOREIGN TABLE ft44 INHERIT pf1;\n\nCREATE FOREIGN TABLE ftp10 (a int, b int) SERVER sv0 OPTIONS (table_name 'cl1');\nCREATE FOREIGN TABLE ftp20 (a int, b int) SERVER sv0 OPTIONS (table_name 'cl2');\nCREATE FOREIGN TABLE ftp30 (a int, b int) SERVER sv0 OPTIONS (table_name 'cl3');\nCREATE FOREIGN TABLE ftp40 (a int, b int) SERVER sv0 OPTIONS (table_name 'cl4');\nCREATE FOREIGN TABLE ftp11 (a int, b int) SERVER sv1 OPTIONS (table_name 'cl1');\nCREATE FOREIGN TABLE ftp22 (a int, b int) SERVER sv2 OPTIONS (table_name 'cl2');\nCREATE FOREIGN TABLE ftp33 (a int, b int) SERVER sv3 OPTIONS (table_name 'cl3');\nCREATE FOREIGN TABLE ftp44 (a int, b int) SERVER sv4 OPTIONS (table_name 'cl4');\n\nCREATE TABLE ptf0 (a int, b int) PARTITION BY RANGE (a);\nALTER TABLE ptf0 ATTACH PARTITION ftp10 FOR VALUES FROM (:th0) TO (:th1);\nALTER TABLE ptf0 ATTACH PARTITION ftp20 FOR VALUES FROM (:th1) TO (:th2);\nALTER TABLE ptf0 ATTACH PARTITION ftp30 FOR VALUES FROM (:th2) TO (:th3);\nALTER TABLE ptf0 ATTACH PARTITION ftp40 FOR VALUES FROM (:th3) TO (:th4);\n\nCREATE TABLE ptf1 (a int, b int) PARTITION BY RANGE (a);\nALTER TABLE ptf1 ATTACH PARTITION ftp11 FOR VALUES FROM (:th0) TO (:th1);\nALTER TABLE ptf1 ATTACH PARTITION ftp22 FOR VALUES FROM (:th1) TO (:th2);\nALTER TABLE ptf1 ATTACH PARTITION ftp33 FOR VALUES FROM (:th2) TO (:th3);\nALTER TABLE ptf1 ATTACH PARTITION ftp44 FOR VALUES FROM (:th3) TO (:th4);\n\nANALYZE;\n\n#! /bin/bash\n\nfunction do_test() {\n\techo $1\n\tfor i in $(seq 1 14); do psql postgres -c \"set max_parallel_workers_per_gather to 0; set log_min_duration_statement = 0; set client_min_messages=log; explain analyze select sum(a) from $1\"; done | grep LOG\n}\n\nfunction do_test_union1() {\n\techo \"UNION_pf0\"\n\tfor i in $(seq 1 14); do psql postgres -c \"set max_parallel_workers_per_gather to 0; set log_min_duration_statement = 0; set client_min_messages=log; SELECT sum(a) FROM (SELECT a FROM ft10 UNION ALL SELECT a FROM ft20 UNION ALL SELECT a FROM ft30 UNION ALL SELECT a FROM ft40) as pf0\"; done | grep LOG\n}\nfunction do_test_union2() {\n\techo \"UNION_pf1\"\n\tfor i in $(seq 1 14); do psql postgres -c \"set max_parallel_workers_per_gather to 0; set log_min_duration_statement = 0; set client_min_messages=log; SELECT sum(a) FROM (SELECT a FROM ft11 UNION ALL SELECT a FROM ft22 UNION ALL SELECT a FROM ft33 UNION ALL SELECT a FROM ft44) as pf1\"; done | grep LOG\n}\n\nfunction warmup() {\n\tfor i in $(seq 1 5); do psql postgres -c \"set log_min_duration_statement = -1; select sum(a) from $1\"; done 1>&2 > /dev/null\n}\n\n#for t in \"t0\" \"pll\";\n#for t in \"ft0\" \"pf0\" \"pf1\" \"ptf0\" \"ptf1\";\n#for t in \"pf0\" \"ptf0\";\nfor t in \"t0\" \"pll\" \"ft0\" \"pf0\" \"pf1\" \"ptf0\" \"ptf1\";\n do\n warmup $t\n do_test $t\n done\nexit\nfor t in \"ft0\" \"pf0\" \"pf1\" \"ptf0\" \"ptf1\";\ndo\n warmup $t\n do_test $t\ndone\n#do_test_union1\n#do_test_union2", "msg_date": "Thu, 12 Dec 2019 21:40:57 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "Hi Hackers,\n\nSharing the email below from Movead Li, I believe he wanted to share the\nbenchmarking results as a response to this email thread but it started a\nnew thread.. Here it is...\n\n\"\nHello\n\nI have tested the patch with a partition table with several foreign\npartitions living on seperate data nodes. The initial testing was done\nwith a partition table having 3 foreign partitions, test was done with\nvariety of scale facters. The seonnd test was with fixed data per data\nnode but number of data nodes were increased incrementally to see\nthe peformance impact as more nodes are added to the cluster. The\ntest three is similar to the initial test but with much huge data and\n4 nodes.\n\nThe results are summary is given below and test script attached:\n\n*Test ENV*\nParent node:2Core 8G\nChild Nodes:2Core 4G\n\n\n*Test one:*\n\n1.1 The partition struct as below:\n\n [ ptf:(a int, b int, c varchar)]\n (Parent node)\n | | |\n [ptf1] [ptf2] [ptf3]\n (Node1) (Node2) (Node3)\n\nThe table data is partitioned across nodes, the test is done using a\nsimple select query and a count aggregate as shown below. The result\nis an average of executing each query multiple times to ensure reliable\nand consistent results.\n\n①select * from ptf where b = 100;\n②select count(*) from ptf;\n\n1.2. Test Results\n\n For ① result:\n scalepernode master patched performance\n 2G 7s 2s 350%\n 5G 173s 63s 275%\n 10G 462s 156s 296%\n 20G 968s 327s 296%\n 30G 1472s 494s 297%\n\n For ② result:\n scalepernode master patched performance\n 2G 1079s 291s 370%\n 5G 2688s 741s 362%\n 10G 4473s 1493s 299%\n\nIt takes too long time to test a aggregate so the test was done with a\nsmaller data size.\n\n\n1.3. summary\n\nWith the table partitioned over 3 nodes, the average performance gain\nacross variety of scale factors is almost 300%\n\n\n*Test Two*\n2.1 The partition struct as below:\n\n [ ptf:(a int, b int, c varchar)]\n (Parent node)\n | | |\n [ptf1] ... [ptfN]\n (Node1) (...) (NodeN)\n\n①select * from ptf\n②select * from ptf where b = 100;\n\nThis test is done with same size of data per node but table is partitioned\nacross N number of nodes. Each varation (master or patches) is tested\nat-least 3 times to get reliable and consistent results. The purpose of the\ntest is to see impact on performance as number of data nodes are increased.\n\n2.2 The results\n\nFor ① result(scalepernode=2G):\n nodenumber master patched performance\n 2 432s 180s 240%\n 3 636s 223s 285%\n 4 830s 283s 293%\n 5 1065s 361s 295%\nFor ② result(scalepernode=10G):\n nodenumber master patched performance\n 2 281s 140s 201%\n 3 421s 140s 300%\n 4 562s 141s 398%\n 5 702s 141s 497%\n 6 833s 139s 599%\n 7 986s 141s 699%\n 8 1125s 140s 803%\n\n\n*Test Three*\n\nThis test is similar to the [test one] but with much huge data and\n4 nodes.\n\nFor ① result:\n scalepernode master patched performance\n 100G 6592s 1649s 399%\nFor ② result:\n scalepernode master patched performance\n 100G 35383 12363 286%\nThe result show it work well in much huge data.\n\n\n*Summary*\nThe patch is pretty good, it works well when there were little data back to\nthe parent node. The patch doesn’t provide parallel FDW scan, it ensures\nthat child nodes can send data to parent in parallel but the parent can\nonly\nsequennly process the data from data nodes.\n\nProviding there is no performance degrdation for non FDW append queries,\nI would recomend to consider this patch as an interim soluton while we are\nwaiting for parallel FDW scan.\n\"\n\n\n\nOn Thu, Dec 12, 2019 at 5:41 PM Kyotaro Horiguchi <horikyota.ntt@gmail.com>\nwrote:\n\n> Hello.\n>\n> I think I can say that this patch doesn't slows non-AsyncAppend,\n> non-postgres_fdw scans.\n>\n>\n> At Mon, 9 Dec 2019 12:18:44 -0500, Bruce Momjian <bruce@momjian.us> wrote\n> in\n> > Certainly any overhead on normal queries would be unacceptable.\n>\n> I took performance numbers on the current shape of the async execution\n> patch for the following scan cases.\n>\n> t0 : single local table (parallel disabled)\n> pll : local partitioning (local Append, parallel disabled)\n> ft0 : single foreign table\n> pf0 : inheritance on 4 foreign tables, single connection\n> pf1 : inheritance on 4 foreign tables, 4 connections\n> ptf0 : partition on 4 foreign tables, single connection\n> ptf1 : partition on 4 foreign tables, 4 connections\n>\n> The benchmarking system is configured as the follows on a single\n> machine.\n>\n> [ benchmark client ]\n> | |\n> (localhost:5433) (localhost:5432)\n> | |\n> +----+ | +------+ |\n> | V V V | V\n> | [master server] | [async server]\n> | V | V\n> +--fdw--+ +--fdw--+\n>\n>\n> The patch works roughly in the following steps.\n>\n> 1. Planner decides how many children out of an append can run\n> asynchrnously (called as async-capable.).\n>\n> 2. While ExecInit if an Append doesn't have an async-capable children,\n> ExecAppend that is exactly the same function is set as\n> ExecProcNode. Otherwise ExecAppendAsync is used.\n>\n> If the infrastructure part in the patch causes any degradation, the\n> \"t0\"(scan on local single table) and/or \"pll\" test (scan on a local\n> paritioned table) gets slow.\n>\n> 3. postgresql_fdw always runs async-capable code path.\n>\n> If the postgres_fdw part causes degradation, ft0 reflects that.\n>\n>\n> The tables has two integers and the query does sum(a) on all tuples.\n>\n> With the default fetch_size = 100, number is run time in ms. Each\n> number is the average of 14 runs.\n>\n> master patched gain\n> t0 7325 7130 +2.7%\n> pll 4558 4484 +1.7%\n> ft0 3670 3675 -0.1%\n> pf0 2322 1550 +33.3%\n> pf1 2367 1475 +37.7%\n> ptf0 2517 1624 +35.5%\n> ptf1 2343 1497 +36.2%\n>\n> With larger fetch_size (200) the gain mysteriously decreases for\n> sharing single connection cases (pf0, ptf0), but others don't seem\n> change so much.\n>\n> master patched gain\n> t0 7212 7252 -0.6%\n> pll 4546 4397 +3.3%\n> ft0 3712 3731 -0.5%\n> pf0 2131 1570 +26.4%\n> pf1 1926 1189 +38.3%\n> ptf0 2001 1557 +22.2%\n> ptf1 1903 1193 +37.4%\n>\n> FWIW, attached are the test script.\n>\n> gentblr2.sql: Table creation script.\n> testrun.sh : Benchmarking script.\n>\n>\n> regards.\n>\n> --\n> Kyotaro Horiguchi\n> NTT Open Source Software Center\n>", "msg_date": "Tue, 14 Jan 2020 14:37:48 +0500", "msg_from": "Ahsan Hadi <ahsan.hadi@highgo.ca>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "On Tue, Jan 14, 2020 at 02:37:48PM +0500, Ahsan Hadi wrote:\n> Summary\n> The patch is pretty good, it works well when there were little data back to\n> the parent node. The patch doesn’t provide parallel FDW scan, it ensures\n> that child nodes can send data to parent in parallel but  the parent can only\n> sequennly process the data from data nodes.\n> \n> Providing there is no performance degrdation for non FDW append queries,\n> I would recomend to consider this patch as an interim soluton while we are\n> waiting for parallel FDW scan.\n\nWow, these are very impressive results!\n\n-- \n Bruce Momjian <bruce@momjian.us> http://momjian.us\n EnterpriseDB http://enterprisedb.com\n\n+ As you are, so once was I. As I am, so you will be. +\n+ Ancient Roman grave inscription +\n\n\n", "msg_date": "Wed, 15 Jan 2020 15:41:04 -0500", "msg_from": "Bruce Momjian <bruce@momjian.us>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "Thank you very much for the testing of the patch, Ahsan!\r\n\r\nAt Wed, 15 Jan 2020 15:41:04 -0500, Bruce Momjian <bruce@momjian.us> wrote in \r\n> On Tue, Jan 14, 2020 at 02:37:48PM +0500, Ahsan Hadi wrote:\r\n> > Summary\r\n> > The patch is pretty good, it works well when there were little data back to\r\n> > the parent node. The patch doesn’t provide parallel FDW scan, it ensures\r\n> > that child nodes can send data to parent in parallel but the parent can only\r\n> > sequennly process the data from data nodes.\r\n\r\n\"Parallel scan\" at the moment means multiple workers fetch unique\r\nblocks from *one* table in an arbitrated manner. In this sense\r\n\"parallel FDW scan\" means multiple local workers fetch unique bundles\r\nof tuples from *one* foreign table, which means it is running on a\r\nsingle session. That doesn't offer an advantage.\r\n\r\nIf parallel query processing worked in worker-per-table mode,\r\nespecially on partitioned tables, maybe the current FDW would work\r\nwithout much of modification. But I believe asynchronous append on\r\nforeign tables on a single process is far resource-effective and\r\nmoderately faster than parallel append.\r\n\r\n> > Providing there is no performance degrdation for non FDW append queries,\r\n> > I would recomend to consider this patch as an interim soluton while we are\r\n> > waiting for parallel FDW scan.\r\n> \r\n> Wow, these are very impressive results!\r\n\r\nThanks.\r\n\r\n-- \r\nKyotaro Horiguchi\r\nNTT Open Source Software Center\r\n", "msg_date": "Thu, 16 Jan 2020 15:50:02 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "On Thu, Jan 16, 2020 at 9:41 AM Bruce Momjian <bruce@momjian.us> wrote:\n> On Tue, Jan 14, 2020 at 02:37:48PM +0500, Ahsan Hadi wrote:\n> > Summary\n> > The patch is pretty good, it works well when there were little data back to\n> > the parent node. The patch doesn’t provide parallel FDW scan, it ensures\n> > that child nodes can send data to parent in parallel but the parent can only\n> > sequennly process the data from data nodes.\n> >\n> > Providing there is no performance degrdation for non FDW append queries,\n> > I would recomend to consider this patch as an interim soluton while we are\n> > waiting for parallel FDW scan.\n>\n> Wow, these are very impressive results!\n\n+1\n\nThanks Ahsan and Movead. Could you please confirm which patch set you tested?\n\n\n", "msg_date": "Thu, 23 Jan 2020 22:28:20 +1300", "msg_from": "Thomas Munro <thomas.munro@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "Hello Kyotaro,\n\n\n\n>\"Parallel scan\" at the moment means multiple workers fetch unique \n\n>blocks from *one* table in an arbitrated manner. In this sense \n\n>\"parallel FDW scan\" means multiple local workers fetch unique bundles \n\n>of tuples from *one* foreign table, which means it is running on a \n\n>single session. That doesn't offer an advantage. \n\n\n\nIt maybe not \"parallel FDW scan\", it can be \"parallel shards scan\"\n\nthe local workers will pick every foreign partition to scan. I have ever \n\ndraw a picture about that you can see it in the link below.\n\nhttps://www.highgo.ca/2019/08/22/parallel-foreign-scan-of-postgresql/\n\nI think the \"parallel shards scan\" make sence in this way.\n\n\n\n>If parallel query processing worked in worker-per-table mode, \n\n>especially on partitioned tables, maybe the current FDW would work \n\n>without much of modification. But I believe asynchronous append on \n\n>foreign tables on a single process is far resource-effective and \n\n>moderately faster than parallel append. \n\n\n\nAs the test result, current patch can not gain more performance when \n\nit returns a huge number of tuples. By \"parallel shards scan\" method,\n\nit can work well, because the 'parallel' can take full use of CPUs while \n\n'asynchronous' can't. \n\n\n\n\n\n\nHighgo Software (Canada/China/Pakistan) \n\nURL : http://www.highgo.ca/ \n\nEMAIL: mailto:movead(dot)li(at)highgo(dot)ca\nHello Kyotaro,>\"Parallel scan\" at the moment means multiple workers fetch unique >blocks from *one* table in an arbitrated manner. In this sense >\"parallel FDW scan\" means multiple local workers fetch unique bundles >of tuples from *one* foreign table, which means it is running on a >single session. That doesn't offer an advantage. It maybe not \"parallel FDW scan\", it can be \"parallel shards scan\"the local workers will pick every foreign partition to scan. I have ever draw a picture about that you can see it in the link below.https://www.highgo.ca/2019/08/22/parallel-foreign-scan-of-postgresql/I think the \"parallel shards scan\" make sence in this way.>If parallel query processing worked in worker-per-table mode, >especially on partitioned tables, maybe the current FDW would work >without much of modification. But I believe asynchronous append on >foreign tables on a single process is far resource-effective and >moderately faster than parallel append. As the test result, current patch can not gain more performance when it returns a huge number of tuples. By \"parallel shards scan\" method,it can work well, because the 'parallel' can take full use of CPUs while 'asynchronous' can't. Highgo Software (Canada/China/Pakistan) URL : www.highgo.ca EMAIL: mailto:movead(dot)li(at)highgo(dot)ca", "msg_date": "Wed, 29 Jan 2020 14:41:07 +0800", "msg_from": "Movead Li <movead.li@highgo.ca>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "Thanks!\n\nAt Wed, 29 Jan 2020 14:41:07 +0800, Movead Li <movead.li@highgo.ca> wrote in \n> >\"Parallel scan\" at the moment means multiple workers fetch unique \n> >blocks from *one* table in an arbitrated manner. In this sense \n> >\"parallel FDW scan\" means multiple local workers fetch unique bundles \n> >of tuples from *one* foreign table, which means it is running on a \n> >single session. That doesn't offer an advantage. \n> \n> It maybe not \"parallel FDW scan\", it can be \"parallel shards scan\"\n> the local workers will pick every foreign partition to scan. I have ever \n> draw a picture about that you can see it in the link below.\n> \n> https://www.highgo.ca/2019/08/22/parallel-foreign-scan-of-postgresql/\n> \n> I think the \"parallel shards scan\" make sence in this way.\n\nIt is \"asynchronous append on async-capable'd postgres-fdw scans\". It\ncould be called as such in the sense that it is intended to be used\nwith sharding.\n\n> >If parallel query processing worked in worker-per-table mode, \n> >especially on partitioned tables, maybe the current FDW would work \n> >without much of modification. But I believe asynchronous append on \n> >foreign tables on a single process is far resource-effective and \n> >moderately faster than parallel append. \n> \n> As the test result, current patch can not gain more performance when \n> it returns a huge number of tuples. By \"parallel shards scan\" method,\n> it can work well, because the 'parallel' can take full use of CPUs while \n> 'asynchronous' can't. \n\nDid you looked at my benchmarking result upthread? Even it gives\nsignificant gain even when gathering large number of tuples from\nmultiple servers or even from a single server. It is because of its\nasynchronous nature.\n\nregards.\n\n-- \nKyotaro Horiguchi\nNTT Open Source Software Center\n\n\n", "msg_date": "Wed, 29 Jan 2020 17:39:35 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "Hello,\r\n\r\n>It is \"asynchronous append on async-capable'd postgres-fdw scans\". It\r\n>could be called as such in the sense that it is intended to be used \r\n>with sharding.\r\n Yes that's it.\r\n\r\n \r\n>Did you looked at my benchmarking result upthread? Even it gives\r\n>significant gain even when gathering large number of tuples from\r\n>multiple servers or even from a single server. It is because of its\r\n>asynchronous nature.\r\nI mean it gain performance at first, but it mets bottleneck while\r\nincrease the number of the nodes.\r\nFor example:\r\n It has 2 nodes, it will gain 200% performance.\r\n It has 3 nodes, it will gain 300% performance.\r\n However,\r\n It has 4 nodes, it gain 300% performance.\r\n It has 5 nodes, it gain 300% performance.\r\n ...\r\n \r\n \r\n----\r\nHighgo Software (Canada/China/Pakistan) \r\nURL : www.highgo.ca \r\nEMAIL: mailto:movead(dot)li(at)highgo(dot)ca\r\n\n\nHello,\n>It is \"asynchronous append on async-capable'd postgres-fdw scans\". It\n>could be called as such in the sense that it is intended to be used\n>with sharding.\n Yes that's it.\n\n \n>Did you looked at my benchmarking result upthread?  Even it gives\n>significant gain even when gathering large number of tuples from\n>multiple servers or even from a single server.  It is because of its\n>asynchronous nature.I mean it gain performance at first, but it mets bottleneck whileincrease the number of the nodes.For example:   It has 2 nodes, it will gain 200% performance.   It has 3 nodes, it will gain 300% performance.   However,   It has 4 nodes, it gain 300% performance.   It has 5 nodes, it gain 300% performance.   ...    \n \n----\nHighgo Software (Canada/China/Pakistan) URL : www.highgo.ca EMAIL: mailto:movead(dot)li(at)highgo(dot)ca", "msg_date": "Wed, 29 Jan 2020 17:58:57 +0800", "msg_from": "\"movead.li@highgo.ca\" <movead.li@highgo.ca>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "On Sun, Dec 1, 2019 at 4:26 AM Bruce Momjian <bruce@momjian.us> wrote:\n> On Sun, Nov 17, 2019 at 09:54:55PM +1300, Thomas Munro wrote:\n> > On Sat, Sep 28, 2019 at 4:20 AM Bruce Momjian <bruce@momjian.us> wrote:\n> > > On Wed, Sep 4, 2019 at 06:18:31PM +1200, Thomas Munro wrote:\n> > > > A few years back[1] I experimented with a simple readiness API that\n> > > > would allow Append to start emitting tuples from whichever Foreign\n> > > > Scan has data available, when working with FDW-based sharding. I used\n> > > > that primarily as a way to test Andres's new WaitEventSet stuff and my\n> > > > kqueue implementation of that, but I didn't pursue it seriously\n> > > > because I knew we wanted a more ambitious async executor rewrite and\n> > > > many people had ideas about that, with schedulers capable of jumping\n> > > > all over the tree etc.\n> > > >\n> > > > Anyway, Stephen Frost pinged me off-list to ask about that patch, and\n> > > > asked why we don't just do this naive thing until we have something\n> > > > better. It's a very localised feature that works only between Append\n> > > > and its immediate children. The patch makes it work for postgres_fdw,\n> > > > but it should work for any FDW that can get its hands on a socket.\n> > > >\n> > > > Here's a quick rebase of that old POC patch, along with a demo. Since\n> > > > 2016, Parallel Append landed, but I didn't have time to think about\n> > > > how to integrate with that so I did a quick \"sledgehammer\" rebase that\n> > > > disables itself if parallelism is in the picture.\n> > >\n> > > Yes, sharding has been waiting on parallel FDW scans. Would this work\n> > > for parallel partition scans if the partitions were FDWs?\n> >\n> > Yeah, this works for partitions that are FDWs (as shown), but only for\n> > Append, not for Parallel Append. So you'd have parallelism in the\n> > sense that your N remote shard servers are all doing stuff at the same\n> > time, but it couldn't be in a parallel query on your 'home' server,\n> > which is probably good for things that push down aggregation and bring\n> > back just a few tuples from each shard, but bad for anything wanting\n> > to ship back millions of tuples to chew on locally. Do you think\n> > that'd be useful enough on its own?\n>\n> Yes, I think so. There are many data warehouse queries that want to\n> return only aggregate values, or filter for a small number of rows.\n> Even OLTP queries might return only a few rows from multiple partitions.\n> This would allow for a proof-of-concept implementation so we can see how\n> realistic this approach is.\n\n+1\n\nBest regards,\nEtsuro Fujita\n\n\n", "msg_date": "Mon, 31 Aug 2020 18:15:36 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "On Thu, Dec 5, 2019 at 1:46 PM Thomas Munro <thomas.munro@gmail.com> wrote:\n> On Thu, Dec 5, 2019 at 4:26 PM Kyotaro Horiguchi\n> <horikyota.ntt@gmail.com> wrote:\n> > There's my pending (somewhat stale) patch, which allows to run local\n> > scans while waiting for remote servers.\n> >\n> > https://www.postgresql.org/message-id/20180515.202945.69332784.horiguchi.kyotaro@lab.ntt.co.jp\n\nI think it’s great to execute local scans while waiting for the\nresults of remote scans, but looking at your patch (the 0002 patch of\nyour patch set in [1]), I’m not sure that the 0002 patch does it much\nefficiently, because it modifies nodeAppend.c so that all the work is\ndone by a single process. Rather than doing so, I’m wondering if it\nwould be better to modify Parallel Append so that some processes\nexecute remote scans and others execute local scans. I’m not sure\nthat we need to have this improvement as well in the first cut of this\nfeature, though.\n\n> After rereading some threads to remind myself what happened here...\n> right, my little patch began life in March 2016[1] when I wanted a\n> test case to test Andres's work on WaitEventSets, and your patch set\n> started a couple of months later and is vastly more ambitious[2][3].\n> It wants to escape from the volcano give-me-one-tuple-or-give-me-EOF\n> model. And I totally agree that there are lots of reason to want to\n> do that (including yielding to other parts of the plan instead of\n> waiting for I/O, locks and some parallelism primitives enabling new\n> kinds of parallelism), and I'm hoping to help with some small pieces\n> of that if I can.\n>\n> My patch set (rebased upthread) was extremely primitive, with no new\n> planner concepts, and added only a very simple new executor node\n> method: ExecReady(). Append used that to try to ask its children if\n> they'd like some time to warm up. By default, ExecReady() says \"I\n> don't know what you're talking about, go away\", but FDWs can provide\n> an implementation that says \"yes, please call me again when this fd is\n> ready\" or \"yes, I am ready, please call ExecProc() now\". It doesn't\n> deal with anything more complicated than that, and in particular it\n> doesn't work if there are extra planner nodes in between Append and\n> the foreign scan. (It also doesn't mix particularly well with\n> parallelism, as mentioned.)\n>\n> The reason I reposted this unambitious work is because Stephen keeps\n> asking me why we don't consider the stupidly simple thing that would\n> help with simple foreign partition-based queries today, instead of\n> waiting for someone to redesign the entire executor, because that's\n> ... really hard.\n\nYeah, I think your patch is much simpler, compared to Horiguchi-san’s\npatch set, which I think is a good thing, considering this would be\nrather an interim solution until executor rewrite is done. Here are a\nfew comments that I have for now:\n\n* I know your patch is a POC one, but one concern about it (and\nHoriguchi-san's patch set) is concurrent data fetches by multiple\nforeign scan nodes using the same connection in the case of\npostgres_fdw. Here is an example causing an error:\n\ncreate or replace function slow_data_ext(name text, secs float)\nreturns setof t as\n$$\nbegin\n perform pg_sleep(secs);\n return query select name, generate_series(1, 100)::text as i;\nend;\n$$\nlanguage plpgsql;\n\ncreate view t11 as select * from slow_data_ext('t11', 1.0);\ncreate view t12 as select * from slow_data_ext('t12', 2.0);\ncreate view t13 as select * from slow_data_ext('t13', 3.0);\ncreate foreign table ft11 (a text, b text) server server1 options\n(table_name 't11');\ncreate foreign table ft12 (a text, b text) server server2 options\n(table_name 't12');\ncreate foreign table ft13 (a text, b text) server server3 options\n(table_name 't13');\ncreate table pt1 (a text, b text) partition by list (a);\nalter table pt1 attach partition ft11 for values in ('t11');\nalter table pt1 attach partition ft12 for values in ('t12');\nalter table pt1 attach partition ft13 for values in ('t13');\n\ncreate view t21 as select * from slow_data_ext('t21', 1.0);\ncreate view t22 as select * from slow_data_ext('t22', 2.0);\ncreate view t23 as select * from slow_data_ext('t23', 3.0);\ncreate foreign table ft21 (a text, b text) server server1 options\n(table_name 't21');\ncreate foreign table ft22 (a text, b text) server server2 options\n(table_name 't22');\ncreate foreign table ft23 (a text, b text) server server3 options\n(table_name 't23');\ncreate table pt2 (a text, b text) partition by list (a);\nalter table pt2 attach partition ft21 for values in ('t21');\nalter table pt2 attach partition ft22 for values in ('t22');\nalter table pt2 attach partition ft23 for values in ('t23');\n\nexplain verbose select * from pt1, pt2 where pt2.a = 't22' or pt2.a = 't23';\n QUERY PLAN\n--------------------------------------------------------------------------------------------------------------\n Nested Loop (cost=200.00..1303.80 rows=50220 width=128)\n Output: pt1.a, pt1.b, pt2.a, pt2.b\n -> Append (cost=100.00..427.65 rows=2790 width=64)\n -> Foreign Scan on public.ft11 pt1_1 (cost=100.00..137.90\nrows=930 width=64)\n Output: pt1_1.a, pt1_1.b\n Remote SQL: SELECT a, b FROM public.t11\n -> Foreign Scan on public.ft12 pt1_2 (cost=100.00..137.90\nrows=930 width=64)\n Output: pt1_2.a, pt1_2.b\n Remote SQL: SELECT a, b FROM public.t12\n -> Foreign Scan on public.ft13 pt1_3 (cost=100.00..137.90\nrows=930 width=64)\n Output: pt1_3.a, pt1_3.b\n Remote SQL: SELECT a, b FROM public.t13\n -> Materialize (cost=100.00..248.44 rows=18 width=64)\n Output: pt2.a, pt2.b\n -> Append (cost=100.00..248.35 rows=18 width=64)\n -> Foreign Scan on public.ft22 pt2_1\n(cost=100.00..124.13 rows=9 width=64)\n Output: pt2_1.a, pt2_1.b\n Remote SQL: SELECT a, b FROM public.t22 WHERE\n(((a = 't22'::text) OR (a = 't23'::text)))\n -> Foreign Scan on public.ft23 pt2_2\n(cost=100.00..124.13 rows=9 width=64)\n Output: pt2_2.a, pt2_2.b\n Remote SQL: SELECT a, b FROM public.t23 WHERE\n(((a = 't22'::text) OR (a = 't23'::text)))\n(21 rows)\n\nselect * from pt1, pt2 where pt2.a = 't22' or pt2.a = 't23';\nERROR: another command is already in progress\nCONTEXT: remote SQL command: DECLARE c4 CURSOR FOR\nSELECT a, b FROM public.t22 WHERE (((a = 't22'::text) OR (a = 't23'::text)))\n\nI think the cause of this error is that an asynchronous data fetch for\nft22 is blocked by that for ft12 that is in progress.\n(Horiguchi-san’s patch set doesn't work for this query either, causing\nthe same error. Though, it looks like he intended to handle cases\nlike this by a queuing system added to postgres_fdw to process such\nconcurrent data fetches.) I think a simple solution for this issue\nwould be to just disable asynchrony optimization for such cases. I\nthink we could do so by tracking foreign scan nodes across the entire\nfinal plan tree that use the same connection at plan or execution\ntime.\n\n* Another one is “no new planner concepts”. I think it leads to this:\n\n@@ -239,9 +242,207 @@ ExecInitAppend(Append *node, EState *estate, int eflags)\n /* For parallel query, this will be overridden later. */\n appendstate->choose_next_subplan = choose_next_subplan_locally;\n\n+ /*\n+ * Initially we consider all subplans to be potentially\nasynchronous.\n+ */\n+ appendstate->asyncplans = (PlanState **) palloc(nplans *\nsizeof(PlanState *));\n+ appendstate->asyncfds = (int *) palloc0(nplans * sizeof(int));\n+ appendstate->nasyncplans = nplans;\n+ memcpy(appendstate->asyncplans, appendstate->appendplans, nplans *\nsizeof(PlanState *));\n+ appendstate->lastreadyplan = 0;\n\nI’m not sure that this would cause performance degradation in the case\nof an plain Append that involves no FDWs supporting asynchrony\noptimization, but I think it would be better to determine subplans\nwith that optimization at plan time and save cycles at execution time\nas done in Horiguchi-san’s patch set. (I’m not sure that we need a\nnew ExecAppend function proposed there, though.) Also, consider this\nordered Append example:\n\ncreate table t31 (a int check (a >= 10 and a < 20), b text);\ncreate table t32 (a int check (a >= 20 and a < 30), b text);\ncreate table t33 (a int check (a >= 30 and a < 40), b text);\ncreate foreign table ft31 (a int check (a >= 10 and a < 20), b text)\nserver server1 options (table_name 't31');\ncreate foreign table ft32 (a int check (a >= 20 and a < 30), b text)\nserver server2 options (table_name 't32');\ncreate foreign table ft33 (a int check (a >= 30 and a < 40), b text)\nserver server3 options (table_name 't33');\ncreate table pt3 (a int, b text) partition by range (a);\nalter table pt3 attach partition ft31 for values from (10) to (20);\nalter table pt3 attach partition ft32 for values from (20) to (30);\nalter table pt3 attach partition ft33 for values from (30) to (40);\n\nexplain verbose select * from pt3 order by a;\n QUERY PLAN\n-----------------------------------------------------------------------------------\n Append (cost=300.00..487.52 rows=4095 width=36)\n -> Foreign Scan on public.ft31 pt3_1 (cost=100.00..155.68\nrows=1365 width=36)\n Output: pt3_1.a, pt3_1.b\n Remote SQL: SELECT a, b FROM public.t31 ORDER BY a ASC NULLS LAST\n -> Foreign Scan on public.ft32 pt3_2 (cost=100.00..155.68\nrows=1365 width=36)\n Output: pt3_2.a, pt3_2.b\n Remote SQL: SELECT a, b FROM public.t32 ORDER BY a ASC NULLS LAST\n -> Foreign Scan on public.ft33 pt3_3 (cost=100.00..155.68\nrows=1365 width=36)\n Output: pt3_3.a, pt3_3.b\n Remote SQL: SELECT a, b FROM public.t33 ORDER BY a ASC NULLS LAST\n(10 rows)\n\nFor this query, we can’t apply asynchrony optimization. To disable it\nfor such cases I think it would be better to do something at plan time\nas well as done in his patch set.\n\nI haven’t finished reviewing your patch, but before doing so, I’ll\nreview Horiguchi-san's patch set in more detail for further\ncomparison. Attached is a rebased version of your patch, in which I\nadded the same changes to the postgres_fdw regression tests as\nHoriguchi-san so that the tests run successfully.\n\nThank you for working on this, Thomas and Horiguchi-san! Sorry for the delay.\n\nBest regards,\nEtsuro Fujita\n\n[1] https://www.postgresql.org/message-id/20200820.163608.1893015081639298019.horikyota.ntt%40gmail.com", "msg_date": "Mon, 31 Aug 2020 18:20:15 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "On Mon, Aug 31, 2020 at 6:20 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:\n> * I know your patch is a POC one, but one concern about it (and\n> Horiguchi-san's patch set) is concurrent data fetches by multiple\n> foreign scan nodes using the same connection in the case of\n> postgres_fdw. Here is an example causing an error:\n\n> select * from pt1, pt2 where pt2.a = 't22' or pt2.a = 't23';\n> ERROR: another command is already in progress\n> CONTEXT: remote SQL command: DECLARE c4 CURSOR FOR\n> SELECT a, b FROM public.t22 WHERE (((a = 't22'::text) OR (a = 't23'::text)))\n\n> (Horiguchi-san’s patch set doesn't work for this query either, causing\n> the same error. Though, it looks like he intended to handle cases\n> like this by a queuing system added to postgres_fdw to process such\n> concurrent data fetches.)\n\nI was wrong here; Horiguchi-san's patch set works well for this query.\nMaybe I did something wrong when testing his patch set. Sorry for\nthat.\n\nBest regards,\nEtsuro Fujita\n\n\n", "msg_date": "Mon, 31 Aug 2020 19:10:39 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "Fujita-san, thank you for taking time!\r\n\r\nAt Mon, 31 Aug 2020 19:10:39 +0900, Etsuro Fujita <etsuro.fujita@gmail.com> wrote in \r\n> On Mon, Aug 31, 2020 at 6:20 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:\r\n> > * I know your patch is a POC one, but one concern about it (and\r\n> > Horiguchi-san's patch set) is concurrent data fetches by multiple\r\n> > foreign scan nodes using the same connection in the case of\r\n> > postgres_fdw. Here is an example causing an error:\r\n> \r\n> > select * from pt1, pt2 where pt2.a = 't22' or pt2.a = 't23';\r\n> > ERROR: another command is already in progress\r\n> > CONTEXT: remote SQL command: DECLARE c4 CURSOR FOR\r\n> > SELECT a, b FROM public.t22 WHERE (((a = 't22'::text) OR (a = 't23'::text)))\r\n> \r\n> > (Horiguchi-san’s patch set doesn't work for this query either, causing\r\n> > the same error. Though, it looks like he intended to handle cases\r\n> > like this by a queuing system added to postgres_fdw to process such\r\n> > concurrent data fetches.)\r\n> \r\n> I was wrong here; Horiguchi-san's patch set works well for this query.\r\n> Maybe I did something wrong when testing his patch set. Sorry for\r\n> that.\r\n\r\nYeah. postgresIterateForeignScan calls vacate_connection() to make the\r\nunderlying connection available if a server connection is busy with\r\nanother remote query. The mechanism is backed by a waiting queue\r\n(add_async_waiter, move_to_next_waiter, remove_async_node).\r\n\r\nregards.\r\n\r\n-- \r\nKyotaro Horiguchi\r\nNTT Open Source Software Center\r\n", "msg_date": "Tue, 01 Sep 2020 09:44:56 +0900 (JST)", "msg_from": "Kyotaro Horiguchi <horikyota.ntt@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" }, { "msg_contents": "On Tue, Sep 1, 2020 at 9:45 AM Kyotaro Horiguchi\n<horikyota.ntt@gmail.com> wrote:\n> At Mon, 31 Aug 2020 19:10:39 +0900, Etsuro Fujita <etsuro.fujita@gmail.com> wrote in\n> > On Mon, Aug 31, 2020 at 6:20 PM Etsuro Fujita <etsuro.fujita@gmail.com> wrote:\n> > > * I know your patch is a POC one, but one concern about it (and\n> > > Horiguchi-san's patch set) is concurrent data fetches by multiple\n> > > foreign scan nodes using the same connection in the case of\n> > > postgres_fdw. Here is an example causing an error:\n> >\n> > > select * from pt1, pt2 where pt2.a = 't22' or pt2.a = 't23';\n> > > ERROR: another command is already in progress\n> > > CONTEXT: remote SQL command: DECLARE c4 CURSOR FOR\n> > > SELECT a, b FROM public.t22 WHERE (((a = 't22'::text) OR (a = 't23'::text)))\n> >\n> > > (Horiguchi-san’s patch set doesn't work for this query either, causing\n> > > the same error. Though, it looks like he intended to handle cases\n> > > like this by a queuing system added to postgres_fdw to process such\n> > > concurrent data fetches.)\n> >\n> > I was wrong here; Horiguchi-san's patch set works well for this query.\n> > Maybe I did something wrong when testing his patch set. Sorry for\n> > that.\n>\n> Yeah. postgresIterateForeignScan calls vacate_connection() to make the\n> underlying connection available if a server connection is busy with\n> another remote query. The mechanism is backed by a waiting queue\n> (add_async_waiter, move_to_next_waiter, remove_async_node).\n\nThanks for the explanation, Horiguchi-san!\n\nSo your version of the patch processes the query successfully, because\n1) before performing an asynchronous data fetch of ft22, it waits for\nthe in-progress data fetch of ft12 using the same connection to\ncomplete so that the data fetch of ft22 can be done, and 2) before\nperforming an asynchronous data fetch of ft23, it waits for the\nin-progress data fetch of ft13 using the same connection to complete\nso that the data fetch of ft23 can be done. Right? If so, I think in\nsome cases such handling would impact performance negatively.\nConsider the same query with LIMIT processed by your version:\n\nexplain verbose select * from pt1, pt2 where pt2.a = 't22' or pt2.a =\n't23' limit 1;\n QUERY PLAN\n--------------------------------------------------------------------------------------------------------------------\n Limit (cost=200.00..200.01 rows=1 width=128)\n Output: pt1.a, pt1.b, pt2.a, pt2.b\n -> Nested Loop (cost=200.00..903.87 rows=50220 width=128)\n Output: pt1.a, pt1.b, pt2.a, pt2.b\n -> Append (cost=100.00..151.85 rows=2790 width=64)\n Async subplans: 3\n -> Async Foreign Scan on public.ft11 pt1_1\n(cost=100.00..137.90 rows=930 width=64)\n Output: pt1_1.a, pt1_1.b\n Remote SQL: SELECT a, b FROM public.t11\n -> Async Foreign Scan on public.ft12 pt1_2\n(cost=100.00..137.90 rows=930 width=64)\n Output: pt1_2.a, pt1_2.b\n Remote SQL: SELECT a, b FROM public.t12\n -> Async Foreign Scan on public.ft13 pt1_3\n(cost=100.00..137.90 rows=930 width=64)\n Output: pt1_3.a, pt1_3.b\n Remote SQL: SELECT a, b FROM public.t13\n -> Materialize (cost=100.00..124.31 rows=18 width=64)\n Output: pt2.a, pt2.b\n -> Append (cost=100.00..124.22 rows=18 width=64)\n Async subplans: 2\n -> Async Foreign Scan on public.ft22 pt2_1\n(cost=100.00..124.13 rows=9 width=64)\n Output: pt2_1.a, pt2_1.b\n Remote SQL: SELECT a, b FROM public.t22\nWHERE (((a = 't22'::text) OR (a = 't23'::text)))\n -> Async Foreign Scan on public.ft23 pt2_2\n(cost=100.00..124.13 rows=9 width=64)\n Output: pt2_2.a, pt2_2.b\n Remote SQL: SELECT a, b FROM public.t23\nWHERE (((a = 't22'::text) OR (a = 't23'::text)))\n(25 rows)\n\nI think your version would require extra time to process this query\ncompared to HEAD due to such handling. This query throws an error\nwith your version, though:\n\nselect * from pt1, pt2 where pt2.a = 't22' or pt2.a = 't23' limit 1;\nERROR: another command is already in progress\nCONTEXT: remote SQL command: CLOSE c1\n\nBest regards,\nEtsuro Fujita\n\n\n", "msg_date": "Mon, 7 Sep 2020 02:05:50 +0900", "msg_from": "Etsuro Fujita <etsuro.fujita@gmail.com>", "msg_from_op": false, "msg_subject": "Re: Append with naive multiplexing of FDWs" } ]
[ { "msg_contents": "Since JIT is on by default in v12, I wanted to revisit the issue raised in\nhttps://www.postgresql.org/message-id/CAMkU=1zVhQ5k5d=YyHNyrigLUNTkOj4=YB17s9--3ts8H-SO=Q@mail.gmail.com\n\nWhen the total estimated cost is between jit_above_cost and\njit_optimize_above_cost, I get a substantial regression in the attached.\nNote that I did not devise this case specifically to cause this problem, I\njust stumbled upon it.\n\nJIT, no optimization: 10.5s\nJIT, optimization: 3.8s\nno JIT: 4.1s\n\nIt seems like the unoptimized JIT code is much worse than the general\npurpose code.\n\nThis is on AWS c4.large, Ubuntu 18.04, installed from PGDG apt repository.\nNo config changes were made, other than the local ones included in the\nscript. (Previously there were questions about how LLVM was configured,\nthat I couldn't really answer well, but here there should be question as I\ndidn't compile or configure it at all.)\n\nThere were some proposed mitigations in sister threads, but none have been\nadopted in v12.\n\nI think it is intuitive, and with empirical evidence, that we do not want\nto JIT compile at all unless we are going to optimize the compiled code.\n\nIs there a rationale for, or other examples to show, that it makes sense\nfor the default value of jit_optimize_above_cost to be 5 fold higher than\nthe default setting of jit_above_cost?\n\nI think these defaults are setting a trap for our users who aren't really\ninterested in JIT, and are just upgrading to stay on the most-current\nversion. I would propose lowering the default jit_optimize_above_cost to\nbe the same as jit_above_cost, or set it to 0 so that jit_above_cost is\nalways in control and always optimizes.\n\nCheers,\n\nJeff", "msg_date": "Wed, 4 Sep 2019 09:56:28 -0400", "msg_from": "Jeff Janes <jeff.janes@gmail.com>", "msg_from_op": true, "msg_subject": "Default JIT setting in V12" }, { "msg_contents": "Hi,\n\nOn 2019-09-04 09:56:28 -0400, Jeff Janes wrote:\n> I think it is intuitive, and with empirical evidence, that we do not want\n> to JIT compile at all unless we are going to optimize the compiled code.\n\nThere's pretty clear counter-evidence however as well :(\n\nI think it's probably more sensible to use some cheap minimal\noptimization for the \"unoptimized\" mode - because there's some\nnon-linear cost algorithms with full optimizations enabled.\n\nHow does your example look with something like:\n\ndiff --git i/src/backend/jit/llvm/llvmjit.c w/src/backend/jit/llvm/llvmjit.c\nindex 82c4afb7011..85ddae2ea2b 100644\n--- i/src/backend/jit/llvm/llvmjit.c\n+++ w/src/backend/jit/llvm/llvmjit.c\n@@ -428,7 +428,7 @@ llvm_optimize_module(LLVMJitContext *context, LLVMModuleRef module)\n if (context->base.flags & PGJIT_OPT3)\n compile_optlevel = 3;\n else\n- compile_optlevel = 0;\n+ compile_optlevel = 1;\n \n /*\n * Have to create a new pass manager builder every pass through, as the\n\nwhich I think - but I'd have to check - doesn't include any of the\nnon-linear cost optimizations.\n\n\n> Is there a rationale for, or other examples to show, that it makes sense\n> for the default value of jit_optimize_above_cost to be 5 fold higher than\n> the default setting of jit_above_cost?\n\nYes. IIRC even tpc-h or something shows that with small scale one does\nget noticable - but not crazy - speedups with unoptimized code, but that\nit's a loss with optimized code.\n\nGreetings,\n\nAndres Freund\n\n\n", "msg_date": "Wed, 4 Sep 2019 07:51:16 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Default JIT setting in V12" }, { "msg_contents": "Hi,\n\nOn 2019-09-04 07:51:16 -0700, Andres Freund wrote:\n> On 2019-09-04 09:56:28 -0400, Jeff Janes wrote:\n> > I think it is intuitive, and with empirical evidence, that we do not want\n> > to JIT compile at all unless we are going to optimize the compiled code.\n> \n> There's pretty clear counter-evidence however as well :(\n> \n> I think it's probably more sensible to use some cheap minimal\n> optimization for the \"unoptimized\" mode - because there's some\n> non-linear cost algorithms with full optimizations enabled.\n> \n> How does your example look with something like:\n> \n> diff --git i/src/backend/jit/llvm/llvmjit.c w/src/backend/jit/llvm/llvmjit.c\n> index 82c4afb7011..85ddae2ea2b 100644\n> --- i/src/backend/jit/llvm/llvmjit.c\n> +++ w/src/backend/jit/llvm/llvmjit.c\n> @@ -428,7 +428,7 @@ llvm_optimize_module(LLVMJitContext *context, LLVMModuleRef module)\n> if (context->base.flags & PGJIT_OPT3)\n> compile_optlevel = 3;\n> else\n> - compile_optlevel = 0;\n> + compile_optlevel = 1;\n> \n> /*\n> * Have to create a new pass manager builder every pass through, as the\n> \n> which I think - but I'd have to check - doesn't include any of the\n> non-linear cost optimizations.\n\nOr better, something slightly more complete, like the attached (which\naffects both code-gen time optimizations (which are more like peephole\nones), and both function/global ones that are cheap).\n\nGreetings,\n\nAndres Freund", "msg_date": "Wed, 4 Sep 2019 08:24:38 -0700", "msg_from": "Andres Freund <andres@anarazel.de>", "msg_from_op": false, "msg_subject": "Re: Default JIT setting in V12" }, { "msg_contents": "On Wed, Sep 4, 2019 at 11:24 AM Andres Freund <andres@anarazel.de> wrote:\n\n> Hi,\n>\n> On 2019-09-04 07:51:16 -0700, Andres Freund wrote:\n>\n\n\n> Or better, something slightly more complete, like the attached (which\n> affects both code-gen time optimizations (which are more like peephole\n> ones), and both function/global ones that are cheap).\n>\n\nYes, that does completely solve the issue I raised. It makes JIT either\nbetter or at least harmless, even when falling into the gap between\njit_above_cost\nand jit_optimize_above_cost.\n\nWhat TPC-H implementation do you use/recommend? This one\nhttps://wiki.postgresql.org/wiki/DBT-3?\n\nCheers,\n\nJeff\n\nOn Wed, Sep 4, 2019 at 11:24 AM Andres Freund <andres@anarazel.de> wrote:Hi,\n\nOn 2019-09-04 07:51:16 -0700, Andres Freund wrote: \nOr better, something slightly more complete, like the attached (which\naffects both code-gen time optimizations (which are more like peephole\nones), and both function/global ones that are cheap).Yes, that does completely solve the issue I raised.  It makes JIT either better or at least harmless, even when falling into the gap between  jit_above_cost and jit_optimize_above_cost.What TPC-H implementation do you use/recommend?  This one https://wiki.postgresql.org/wiki/DBT-3?Cheers,Jeff", "msg_date": "Mon, 16 Sep 2019 11:12:04 -0400", "msg_from": "Jeff Janes <jeff.janes@gmail.com>", "msg_from_op": true, "msg_subject": "Re: Default JIT setting in V12" }, { "msg_contents": "Hello,\n\nBased on this thread, Alexandra and I decided to investigate if we could\nborrow\nsome passes from -O1 and add on to the default optimization of -O0 and\nmem2reg.\nTo determine what passes would make most sense, we ran ICW with\njit_above_cost\nset to 0, dumped all the backends and then analyzed them with 'opt'. Based\non\nthe stats dumped that the instcombine pass and sroa had the most scope for\noptimization. We have attached the stats we dumped.\n\nThen, we investigated whether mixing in sroa and instcombine gave us a\nbetter\nrun time. We used TPCH Q1 (TPCH repo we used:\nhttps://github.com/dimitri/tpch-citus) at scales of 1, 5 and 50. We found\nthat\nthere was no significant difference in query runtime over the default of -O0\nwith mem2reg.\n\nWe also performed the same experiment with -O1 as the default\noptimization level, as Andres had suggested on this thread. We found\nthat the results were much more promising (refer the results for scale\n= 5 and 50 below). At the lower scale of 1, we had to force optimization\nto meet the query cost. There was no adverse impact from increased\nquery optimization time due to the ramp up to -O1 at this lower scale.\n\n\nResults summary (eyeball-averaged over 5 runs, excluding first run after\nrestart. For each configuration we flushed the OS cache and restarted the\ndatabase):\n\nsettings: max_parallel_workers_per_gather = 0\n\nscale = 50:\n-O3 : 77s\n-O0 + mem2reg : 107s\n-O0 + mem2reg + instcombine : 107s\n-O0 + mem2reg + sroa : 107s\n-O0 + mem2reg + sroa + instcombine : 107s\n-O1 : 84s\n\nscale = 5:\n-O3 : 8s\n-O0 + mem2reg : 10s\n-O0 + mem2reg + instcombine : 10s\n-O0 + mem2reg + sroa : 10s\n-O0 + mem2reg + sroa + instcombine : 10s\n-O1 : 8s\n\n\nscale = 1:\n-O3 : 1.7s\n-O0 + mem2reg : 1.7s\n-O0 + mem2reg + instcombine : 1.7s\n-O0 + mem2reg + sroa : 1.7s\n-O0 + mem2reg + sroa + instcombine : 1.7s\n-O1 : 1.7s\n\nBased on the evidence above, maybe it is worth considering ramping up the\ndefault optimization level to -O1.\n\nRegards,\n\nSoumyadeep and Alexandra", "msg_date": "Wed, 29 Jan 2020 12:30:47 -0800", "msg_from": "Soumyadeep Chakraborty <sochakraborty@pivotal.io>", "msg_from_op": false, "msg_subject": "Re: Default JIT setting in V12" } ]
[ { "msg_contents": "Hello hackers\n\nI am getting sporadic errors when I tried to use PG12 bionic debian\nrepository.\n\nHere is the error message that is result of apt-get update.\n-----------\nFailed to fetch\nhttp://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-i386/Packages.gz\nFile has unexpected size (260865 != 260866). Mirror sync in progress? [IP:\n34.96.81.152 80]\nHashes of expected file:\n - Filesize:260866 [weak]\n - SHA256:433bef097d8a54a9899350c182d0074c1a13f62c8e7e9987cc6c63cd11242abc\n - SHA1:1be55e080a1dd277929f095690ae9b9cf01e971f [weak]\n - MD5Sum:08189bf54aa297f53b9656bc3c529c62 [weak]\n Release file created at: Mon, 02 Sep 2019 10:25:33 +0000\n Failed to fetch\nhttp://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-amd64/Packages.gz\n Some index files failed to download. They have been ignored, or old ones\nused instead.\n------------------\n\nIt usually succeeds when I run it again. Is there a way to avoid this?\n\nThanks\nMurat\n\nHello hackersI am getting sporadic errors when I tried to use PG12 bionic debian repository.Here is the error message that is result of apt-get update.-----------Failed to fetch http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-i386/Packages.gz File has unexpected size (260865 != 260866). Mirror sync in progress? [IP: 34.96.81.152 80]Hashes of expected file: - Filesize:260866 [weak] - SHA256:433bef097d8a54a9899350c182d0074c1a13f62c8e7e9987cc6c63cd11242abc - SHA1:1be55e080a1dd277929f095690ae9b9cf01e971f [weak] - MD5Sum:08189bf54aa297f53b9656bc3c529c62 [weak] Release file created at: Mon, 02 Sep 2019 10:25:33 +0000 Failed to fetch http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-amd64/Packages.gz  Some index files failed to download. They have been ignored, or old ones used instead.------------------It usually succeeds when I run it again.  Is there a way to avoid this? ThanksMurat", "msg_date": "Wed, 4 Sep 2019 17:45:52 +0300", "msg_from": "Murat Tuncer <mtuncer@citusdata.com>", "msg_from_op": true, "msg_subject": "having issues with PG12 debian packaging repository" }, { "msg_contents": "On Wed, Sep 4, 2019 at 5:43 PM Murat Tuncer <mtuncer@citusdata.com> wrote:\n\n> Hello hackers\n>\n> I am getting sporadic errors when I tried to use PG12 bionic debian\n> repository.\n>\n> Here is the error message that is result of apt-get update.\n> -----------\n> Failed to fetch\n> http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-i386/Packages.gz\n> File has unexpected size (260865 != 260866). Mirror sync in progress? [IP:\n> 34.96.81.152 80]\n> Hashes of expected file:\n> - Filesize:260866 [weak]\n> - SHA256:433bef097d8a54a9899350c182d0074c1a13f62c8e7e9987cc6c63cd11242abc\n> - SHA1:1be55e080a1dd277929f095690ae9b9cf01e971f [weak]\n> - MD5Sum:08189bf54aa297f53b9656bc3c529c62 [weak]\n> Release file created at: Mon, 02 Sep 2019 10:25:33 +0000\n> Failed to fetch\n> http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-amd64/Packages.gz\n> Some index files failed to download. They have been ignored, or old ones\n> used instead.\n> ------------------\n>\n> It usually succeeds when I run it again. Is there a way to avoid this?\n>\n>\nThis sounds very similar to an issue people ran into on travis, which I\nbelieve was tracked down to travis putting a cache in between themselves\nand apt.postgresql.org, which broke the order of downloads. Any chance you\nalso have a cache sitting there somewhere?\n\n//Magnus\n\nOn Wed, Sep 4, 2019 at 5:43 PM Murat Tuncer <mtuncer@citusdata.com> wrote:Hello hackersI am getting sporadic errors when I tried to use PG12 bionic debian repository.Here is the error message that is result of apt-get update.-----------Failed to fetch http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-i386/Packages.gz File has unexpected size (260865 != 260866). Mirror sync in progress? [IP: 34.96.81.152 80]Hashes of expected file: - Filesize:260866 [weak] - SHA256:433bef097d8a54a9899350c182d0074c1a13f62c8e7e9987cc6c63cd11242abc - SHA1:1be55e080a1dd277929f095690ae9b9cf01e971f [weak] - MD5Sum:08189bf54aa297f53b9656bc3c529c62 [weak] Release file created at: Mon, 02 Sep 2019 10:25:33 +0000 Failed to fetch http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-amd64/Packages.gz  Some index files failed to download. They have been ignored, or old ones used instead.------------------It usually succeeds when I run it again.  Is there a way to avoid this? This sounds very similar to an issue people ran into on travis, which I believe was tracked down to travis putting a cache in between themselves and apt.postgresql.org, which broke the order of downloads. Any chance you also have a cache sitting there somewhere?//Magnus", "msg_date": "Sun, 8 Sep 2019 20:42:55 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: having issues with PG12 debian packaging repository" }, { "msg_contents": "On Sun, Sep 8, 2019, 21:43 Magnus Hagander <magnus@hagander.net> wrote:\n\n> On Wed, Sep 4, 2019 at 5:43 PM Murat Tuncer <mtuncer@citusdata.com> wrote:\n>\n>> Hello hackers\n>>\n>> I am getting sporadic errors when I tried to use PG12 bionic debian\n>> repository.\n>>\n>> Here is the error message that is result of apt-get update.\n>> -----------\n>> Failed to fetch\n>> http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-i386/Packages.gz\n>> File has unexpected size (260865 != 260866). Mirror sync in progress? [IP:\n>> 34.96.81.152 80]\n>> Hashes of expected file:\n>> - Filesize:260866 [weak]\n>> - SHA256:433bef097d8a54a9899350c182d0074c1a13f62c8e7e9987cc6c63cd11242abc\n>> - SHA1:1be55e080a1dd277929f095690ae9b9cf01e971f [weak]\n>> - MD5Sum:08189bf54aa297f53b9656bc3c529c62 [weak]\n>> Release file created at: Mon, 02 Sep 2019 10:25:33 +0000\n>> Failed to fetch\n>> http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-amd64/Packages.gz\n>> Some index files failed to download. They have been ignored, or old ones\n>> used instead.\n>> ------------------\n>>\n>> It usually succeeds when I run it again. Is there a way to avoid this?\n>>\n>>\n> This sounds very similar to an issue people ran into on travis, which I\n> believe was tracked down to travis putting a cache in between themselves\n> and apt.postgresql.org, which broke the order of downloads. Any chance\n> you also have a cache sitting there somewhere?\n>\n> //Magnus\n>\n\n\nThanks.\n\nI should have added I was seeing this in travis. I tought it was a general\nissue.\n\nIs there a workaround for this in travis ?\n\nMurat\n\n>\n\nOn Sun, Sep 8, 2019, 21:43 Magnus Hagander <magnus@hagander.net> wrote:On Wed, Sep 4, 2019 at 5:43 PM Murat Tuncer <mtuncer@citusdata.com> wrote:Hello hackersI am getting sporadic errors when I tried to use PG12 bionic debian repository.Here is the error message that is result of apt-get update.-----------Failed to fetch http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-i386/Packages.gz File has unexpected size (260865 != 260866). Mirror sync in progress? [IP: 34.96.81.152 80]Hashes of expected file: - Filesize:260866 [weak] - SHA256:433bef097d8a54a9899350c182d0074c1a13f62c8e7e9987cc6c63cd11242abc - SHA1:1be55e080a1dd277929f095690ae9b9cf01e971f [weak] - MD5Sum:08189bf54aa297f53b9656bc3c529c62 [weak] Release file created at: Mon, 02 Sep 2019 10:25:33 +0000 Failed to fetch http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-amd64/Packages.gz  Some index files failed to download. They have been ignored, or old ones used instead.------------------It usually succeeds when I run it again.  Is there a way to avoid this? This sounds very similar to an issue people ran into on travis, which I believe was tracked down to travis putting a cache in between themselves and apt.postgresql.org, which broke the order of downloads. Any chance you also have a cache sitting there somewhere?//MagnusThanks.I should have added I was seeing this in travis. I tought it was a general issue.Is there a workaround for this in travis ?Murat", "msg_date": "Mon, 9 Sep 2019 19:03:25 +0300", "msg_from": "Murat Tuncer <mtuncer@citusdata.com>", "msg_from_op": true, "msg_subject": "Re: having issues with PG12 debian packaging repository" }, { "msg_contents": "On Mon, Sep 9, 2019 at 6:03 PM Murat Tuncer <mtuncer@citusdata.com> wrote:\n\n>\n> On Sun, Sep 8, 2019, 21:43 Magnus Hagander <magnus@hagander.net> wrote:\n>\n>> On Wed, Sep 4, 2019 at 5:43 PM Murat Tuncer <mtuncer@citusdata.com>\n>> wrote:\n>>\n>>> Hello hackers\n>>>\n>>> I am getting sporadic errors when I tried to use PG12 bionic debian\n>>> repository.\n>>>\n>>> Here is the error message that is result of apt-get update.\n>>> -----------\n>>> Failed to fetch\n>>> http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-i386/Packages.gz\n>>> File has unexpected size (260865 != 260866). Mirror sync in progress? [IP:\n>>> 34.96.81.152 80]\n>>> Hashes of expected file:\n>>> - Filesize:260866 [weak]\n>>> -\n>>> SHA256:433bef097d8a54a9899350c182d0074c1a13f62c8e7e9987cc6c63cd11242abc\n>>> - SHA1:1be55e080a1dd277929f095690ae9b9cf01e971f [weak]\n>>> - MD5Sum:08189bf54aa297f53b9656bc3c529c62 [weak]\n>>> Release file created at: Mon, 02 Sep 2019 10:25:33 +0000\n>>> Failed to fetch\n>>> http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-amd64/Packages.gz\n>>> Some index files failed to download. They have been ignored, or old\n>>> ones used instead.\n>>> ------------------\n>>>\n>>> It usually succeeds when I run it again. Is there a way to avoid this?\n>>>\n>>>\n>> This sounds very similar to an issue people ran into on travis, which I\n>> believe was tracked down to travis putting a cache in between themselves\n>> and apt.postgresql.org, which broke the order of downloads. Any chance\n>> you also have a cache sitting there somewhere?\n>>\n>> //Magnus\n>>\n>\n>\n> Thanks.\n>\n> I should have added I was seeing this in travis. I tought it was a general\n> issue.\n>\n> Is there a workaround for this in travis ?\n>\n>\nI thought it was fixed by now. Travis has a thread at\nhttps://travis-ci.community/t/sometimes-build-fails-when-apt-is-updating-postgresql-apt-repository/4872\n\n//Magnus\n\nOn Mon, Sep 9, 2019 at 6:03 PM Murat Tuncer <mtuncer@citusdata.com> wrote:On Sun, Sep 8, 2019, 21:43 Magnus Hagander <magnus@hagander.net> wrote:On Wed, Sep 4, 2019 at 5:43 PM Murat Tuncer <mtuncer@citusdata.com> wrote:Hello hackersI am getting sporadic errors when I tried to use PG12 bionic debian repository.Here is the error message that is result of apt-get update.-----------Failed to fetch http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-i386/Packages.gz File has unexpected size (260865 != 260866). Mirror sync in progress? [IP: 34.96.81.152 80]Hashes of expected file: - Filesize:260866 [weak] - SHA256:433bef097d8a54a9899350c182d0074c1a13f62c8e7e9987cc6c63cd11242abc - SHA1:1be55e080a1dd277929f095690ae9b9cf01e971f [weak] - MD5Sum:08189bf54aa297f53b9656bc3c529c62 [weak] Release file created at: Mon, 02 Sep 2019 10:25:33 +0000 Failed to fetch http://apt.postgresql.org/pub/repos/apt/dists/bionic-pgdg/main/binary-amd64/Packages.gz  Some index files failed to download. They have been ignored, or old ones used instead.------------------It usually succeeds when I run it again.  Is there a way to avoid this? This sounds very similar to an issue people ran into on travis, which I believe was tracked down to travis putting a cache in between themselves and apt.postgresql.org, which broke the order of downloads. Any chance you also have a cache sitting there somewhere?//MagnusThanks.I should have added I was seeing this in travis. I tought it was a general issue.Is there a workaround for this in travis ?I thought it was fixed by now. Travis has a thread at https://travis-ci.community/t/sometimes-build-fails-when-apt-is-updating-postgresql-apt-repository/4872//Magnus", "msg_date": "Mon, 9 Sep 2019 19:04:05 +0200", "msg_from": "Magnus Hagander <magnus@hagander.net>", "msg_from_op": false, "msg_subject": "Re: having issues with PG12 debian packaging repository" } ]